public static float[,] Raster2Mat(IRasterLayer rasterlayer) //将栅格数据转为二元数组 { IRaster raster = rasterlayer.Raster; IRaster2 raster2 = raster as IRaster2; IRasterProps pRasterProps = (IRasterProps)raster; IPnt pntstart = new DblPntClass(); pntstart.SetCoords(0, 0); IPnt pntend = new DblPntClass(); pntend.SetCoords(pRasterProps.Width, pRasterProps.Height); IPixelBlock3 unionPixelBlock = (IPixelBlock3)raster.CreatePixelBlock(pntend); System.Single[,] floatMat; try { raster.Read(pntstart, (IPixelBlock)unionPixelBlock); floatMat = (System.Single[, ])unionPixelBlock.get_PixelData(0); } catch (Exception e) { raster.Read(pntstart, (IPixelBlock)unionPixelBlock); int[,] intMat = (int[, ])unionPixelBlock.get_PixelData(0); floatMat = new System.Single[pRasterProps.Width, pRasterProps.Height]; Parallel.For(0, pRasterProps.Width, i => { for (int j = 0; j < pRasterProps.Height; j++) { floatMat[i, j] = Convert.ToSingle(intMat[i, j]); } }); } return(floatMat); }
public void Write(float?[,] rasterValue, string format) { FileHelper.DeleteFile(_workSpace, _fileName, ".tif", ".tfw", ".tif.aux"); IRasterWorkspace2 rasterWs = OpenRasterWorkspace(); if (rasterWs == null) { throw new NullReferenceException("栅格文件打开失败"); } IRasterDataset rasterDataset = rasterWs.CreateRasterDataset(_fileName + ".tif", format, RasterInfo.OriginPoint, RasterInfo.Width, RasterInfo.Height, RasterInfo.XCellSize, RasterInfo.YCellSize, 1, rstPixelType.PT_FLOAT, RasterInfo.SpatialReference, true); IRasterBandCollection rasterBands = (IRasterBandCollection)rasterDataset; var rasterBand = rasterBands.Item(0); var rasterProps = (IRasterProps)rasterBand; //Set NoData if necessary. For a multiband image, NoData value needs to be set for each band. rasterProps.NoDataValue = -1; //Create a raster from the dataset. IRaster raster = rasterDataset.CreateDefaultRaster(); //Create a pixel block. IPnt blocksize = new PntClass(); blocksize.SetCoords(RasterInfo.Width, RasterInfo.Height); IPixelBlock3 pixelblock = raster.CreatePixelBlock(blocksize) as IPixelBlock3; //Populate some pixel values to the pixel block. var pixels = (Array)pixelblock.get_PixelData(0); for (int i = 0; i < RasterInfo.Width; i++) { for (int j = 0; j < RasterInfo.Height; j++) { if (rasterValue[i, j].HasValue) { pixels.SetValue((float)rasterValue[i, j], i, j); } else { pixels.SetValue(-1, i, j); } } } pixelblock.set_PixelData(0, pixels); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(0, 0); //Write the pixel block. IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock); //Release rasterEdit explicitly. Marshal.ReleaseComObject(rasterEdit); }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); IPixelBlock3 pPixelBlock3 = (IPixelBlock3)pPixelBlock; IRaster2 inRs2 = (IRaster2)inrs; IRaster2 outRs2 = (IRaster2)outrs; double mx, my; outRs2.PixelToMap((int)pTlc.X, (int)pTlc.Y, out mx, out my); int clm, rw; inRs2.MapToPixel(mx, my, out clm, out rw); IPnt pntLoc = new PntClass(); pntLoc.SetCoords(clm, rw); IPnt pntSize = new PntClass(); pntSize.SetCoords(pPixelBlock.Width, pPixelBlock.Height); IPixelBlock3 pBIn = (IPixelBlock3)inrs.CreatePixelBlock(pntSize); inrs.Read(pntLoc, (IPixelBlock)pBIn); for (int p = 0; p < pPixelBlock.Planes; p++) { pPixelBlock3.set_PixelData(p, pBIn.get_PixelData(p)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/// <summary> /// Get the pixel values in a region of the input raster. /// </summary> /// <param name="tlCorner"></param> /// <param name="brCorner"></param> /// <param name="raster"></param> /// <returns></returns> public static double[,] GetValues(Position tlCorner, Position brCorner, IRaster raster) { int colCount = brCorner.Column - tlCorner.Column + 1; int rowCount = brCorner.Row - tlCorner.Row + 1; IPnt regionSize = new PntClass(); regionSize.SetCoords(colCount, rowCount); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(tlCorner.Column, tlCorner.Row); raster.Read(tl, pixelBlock); double[,] values = new double[colCount, rowCount]; for (int x = 0; x < colCount; x++) { for (int y = 0; y < rowCount; y++) { Pixel cell = Editor.Edits[x + tlCorner.Column, y + tlCorner.Row]; if (cell == null) { values[x, y] = Convert.ToDouble(pixelBlock.GetVal(0, x, y)); } else { values[x, y] = cell.NewValue; } } } return(values); }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. //Console.WriteLine("Before Read"); myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); IRaster mosRs = (IRaster)mos; IPnt pntSize = new PntClass(); pntSize.SetCoords(pPixelBlock.Width, pPixelBlock.Height); IPixelBlock pb = mosRs.CreatePixelBlock(pntSize); mosRs.Read(pTlc, pb); for (int i = 0; i < pb.Planes; i++) { pPixelBlock.set_SafeArray(i, pb.get_SafeArray(i)); } } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of mosaic Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. //System.Array noDataValueArr = (System.Array)((IRasterProps)inrsBandsCoef).NoDataValue; //Console.WriteLine("Before Read"); myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); //Console.WriteLine("After Read"); int pBHeight = pPixelBlock.Height; int pBWidth = pPixelBlock.Width; IPnt pbSize = new PntClass(); pbSize.SetCoords(pBWidth, pBHeight); IPixelBlock3 outPb = (IPixelBlock3)inrsBandsCoef.CreatePixelBlock(pbSize);//independent variables inrsBandsCoef.Read(pTlc, (IPixelBlock)outPb); int pBRowIndex = 0; int pBColIndex = 0; IPixelBlock3 ipPixelBlock = (IPixelBlock3)pPixelBlock; //System.Array[] pArr = new System.Array[outPb.Planes]; //for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) //{ // System.Array pixelValues = (System.Array)(outPb.get_PixelData(coefnBand)); // pArr[coefnBand] = pixelValues; //} System.Array pValues = (System.Array)ipPixelBlock.get_PixelData(0);//(System.Array)(td); for (int i = pBRowIndex; i < pBHeight; i++) { for (int k = pBColIndex; k < pBWidth; k++) { double[] xVls = new double[outPb.Planes]; bool ndT = true; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { //float noDataValue = System.Convert.ToSingle(noDataValueArr.GetValue(coefnBand)); object pObj = outPb.GetVal(coefnBand, k, i); if (pObj == null) { ndT = false; break; } float pixelValue = Convert.ToSingle(pObj); xVls[coefnBand] = pixelValue; } if (ndT) { int c = cluster.computNew(xVls); pValues.SetValue(c, k, i); } } } ipPixelBlock.set_PixelData(0, pValues); } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of Cluster Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
private void updateWithMergedValues(IEnvelope env, IPixelBlock3 ipPixelBlock) { System.Array[] outPixelValuesArr = new System.Array[ipPixelBlock.Planes]; List <System.Array[]> inPixelValuesArrLst = new List <System.Array[]>(); List <System.Array> inPixelNoDataArrLst = new List <System.Array>(); IPnt pntSize = new PntClass(); pntSize.SetCoords(ipPixelBlock.Width, ipPixelBlock.Height); ISpatialFilter spFlt = new SpatialFilterClass(); spFlt.Geometry = (IGeometry)env; spFlt.GeometryField = ftrCls.ShapeFieldName; spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelOverlaps; IFeatureCursor fCur = ftrCls.Search(spFlt, false); int fIndex = ftrCls.FindField("catIndex"); IFeature ftr = fCur.NextFeature(); for (int i = 0; i < ipPixelBlock.Planes; i++) { outPixelValuesArr[i] = (System.Array)ipPixelBlock.get_PixelData(i); } while (ftr != null) { int rsIndex = System.Convert.ToInt32(ftr.get_Value(fIndex)); IRaster rs = inrs[rsIndex]; IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); IRaster2 rs2 = (IRaster2)rs; int pClm, pRw; rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); IPnt tlc = new PntClass(); tlc.SetCoords(pClm, pRw); rs.Read(tlc, inputPb); System.Array[] inPixelValuesArr = new System.Array[inputPb.Planes]; for (int i = 0; i < inputPb.Planes; i++) { inPixelValuesArr[i] = (System.Array)inputPb.get_SafeArray(i); } inPixelNoDataArrLst.Add((System.Array)((IRasterProps)rs).NoDataValue); inPixelValuesArrLst.Add(inPixelValuesArr); ftr = fCur.NextFeature(); } for (int i = 0; i < outPixelValuesArr.Length; i++) { for (int r = 0; r < ipPixelBlock.Height; r++) { for (int c = 0; c < ipPixelBlock.Width; c++) { double vl = getValue(i, c, r, inPixelValuesArrLst, inPixelNoDataArrLst); outPixelValuesArr[i].SetValue(vl, c, r); } } } for (int i = 0; i < outPixelValuesArr.Length; i++) { ipPixelBlock.set_PixelData(i, outPixelValuesArr[i]); } }
private bool writeBlockDataToFile(Point2D ptLeftTop, byte[,] dbData, int[] nSize, IRaster pRaster /*, IRasterEdit rasterEdit*/) { if (pRaster == null) { return(false); } try { //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". int nWidth = nSize[0]; int nHeight = nSize[1]; IPnt blocksize = new PntClass(); blocksize.SetCoords(nWidth, nHeight); IPixelBlock3 pixelblock = pRaster.CreatePixelBlock(blocksize) as IPixelBlock3; //Populate some pixel values to the pixel block. System.Array pixels; pixels = (System.Array)pixelblock.get_PixelData(0); for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { pixels.SetValue(dbData[i, j], i, j); } } pixelblock.set_PixelData(0, (System.Array)pixels); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y); //Write the pixel block. IRasterEdit rasterEdit = (IRasterEdit)pRaster; rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock); //System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); rasterEdit.Refresh(); return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error: " + ex.Message); return(false); } GC.Collect(); return(true); }
//获取最大最小栅格值 private void SetMaxMinValue(int flag) { if (flag == 1) { textBoxMax.Text = "高:255"; textBoxMin.Text = "低:0"; return; } uint valueMax = 50; uint valueMin = 50; IRasterLayer pRasterLayer = m_layer as IRasterLayer; IRaster pRaster = pRasterLayer.Raster; IRasterProps pRasterProps = pRaster as IRasterProps; int Height = pRasterProps.Height; int Width = pRasterProps.Width; double dX = pRasterProps.MeanCellSize().X; double dY = pRasterProps.MeanCellSize().Y; //栅格的高度 IEnvelope extent = pRasterProps.Extent; //当前栅格数据集的范围 rstPixelType pixelType = pRasterProps.PixelType; //当前栅格像素类型 IPnt pntSize = new PntClass(); pntSize.SetCoords(dX, dY); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); IPnt pnt = new PntClass(); for (int i = 0; i < Height; i += 10) { for (int j = 0; j < Width; j += 10) { pnt.SetCoords(i, j); pRaster.Read(pnt, pixelBlock); if (pixelBlock != null) { object obj = pixelBlock.GetVal(0, 0, 0); uint temp = Convert.ToUInt32(obj); if (temp > valueMax) { valueMax = temp; } else if (temp < valueMin) { valueMin = temp; } } } } textBoxMax.Text = "高:" + valueMax.ToString(); textBoxMin.Text = "低:" + valueMin.ToString(); }
/// <summary> /// Gets value of pixel at the specified position. /// </summary> /// <param name="pos"></param> /// <param name="raster"></param> /// <returns></returns> public static double GetValue(Position pos, IRaster raster) { IPnt regionSize = new PntClass(); regionSize.SetCoords(1, 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(pos.Column, pos.Row); raster.Read(tl, pixelBlock); return(Convert.ToDouble(pixelBlock.GetVal(0, 0, 0))); }
private IPixelBlock GetAllPixelBlock(int width, int height) { IRaster pRaster = GetRaster(); IPnt pnt = new PntClass(); pnt.SetCoords(0, 0); IPnt pntSize = new PntClass(); pntSize.SetCoords(width, height); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); pRaster.Read(pnt, pixelBlock); return(pixelBlock); }
public bool readBlockDataToFile(Point2D ptLeftTop, ref double[,] dbData, IRaster pRaster /*, IRasterEdit rasterEdit*/) { if (pRaster == null) { return(false); } try { //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". int nWidth = dbData.GetLength(0); int nHeight = dbData.GetLength(1); IPnt blocksize = new PntClass(); blocksize.SetCoords(nWidth, nHeight); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y); IPixelBlock3 pixelblock = pRaster.CreatePixelBlock(blocksize) as IPixelBlock3; pRaster.Read(upperLeft, pixelblock as IPixelBlock); //Populate some pixel values to the pixel block. System.Array pixels; pixels = (System.Array)pixelblock.get_PixelData(0); for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { dbData[i, j] = Convert.ToDouble(pixels.GetValue(i, j));//.GetType().; } } return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error: " + ex.Message); return(false); } GC.Collect(); return(true); }
/// <summary> /// 读取数据 /// </summary> /// <param name="xIndex">水平方向的序号</param> /// <param name="yIndex">垂直方向的序号</param> /// <returns>获取的值,如果为null,表明该位置没有数据</returns> public object Read(int xIndex, int yIndex) { IRaster pRaster = GetRaster(); IPnt pnt = new PntClass(); pnt.SetCoords(xIndex, yIndex); IPnt pntSize = new PntClass(); pntSize.SetCoords(1, 1); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); pRaster.Read(pnt, pixelBlock); object obj = pixelBlock.GetVal(0, 0, 0); return(obj); }
public static double GetPixelVal(IRaster pRaster, IPoint pPoint) { IPixelBlock pPixelBlock; IPnt pPnt; IPnt pCurrentPnt; ISpatialReference pSR; pSR = pPoint.SpatialReference; pPnt = new DblPnt(); pPnt.SetCoords(1.0, 1.0); pPixelBlock = pRaster.CreatePixelBlock(pPnt); pCurrentPnt = GetCurrPnt(pRaster, pPoint.X, pPoint.Y, pSR); pRaster.Read(pCurrentPnt, pPixelBlock); return(Convert.ToDouble(string.Format("{0,10:###0.0000}", pPixelBlock.GetVal(0, 0, 0)))); }
public void WriteToSDEFromPixelArray(IRasterWorkspaceEx irasterWorkspaceEx_0, string string_0) { IRasterDataset rasterDataset = irasterWorkspaceEx_0.CreateRasterDataset(string_0, 3, rstPixelType.PT_SHORT, new RasterStorageDef(), "", new RasterDef(), null); IRaster raster = rasterDataset.CreateDefaultRaster(); IRasterProps rasterProp = raster as IRasterProps; int num = 1000; int num1 = 1000; IEnvelope envelopeClass = new Envelope() { XMin = 100, XMax = 500, YMin = 100, YMax = 500 } as IEnvelope; rasterProp.Extent = envelopeClass; rasterProp.Width = 1000; rasterProp.Height = 1000; IPnt pntClass = new Pnt(); pntClass.SetCoords((double)1000, (double)1000); IPixelBlock3 pixelBlock3 = raster.CreatePixelBlock(pntClass) as IPixelBlock3; pntClass.SetCoords(0, 0); for (int i = 0; i < 3; i++) { object pixelData = pixelBlock3.PixelData[i]; for (int j = 0; j < num; j++) { int num2 = 0; while (num2 < num1) { num2++; } } pixelBlock3.PixelData[i] = pixelData; } (raster as IRasterEdit).Write(pntClass, pixelBlock3 as IPixelBlock); }
private bool WriteToRaster(IRaster pRaster, byte[,] dbData, Point2D ptLeftTop) { //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". IRasterProps pProps = pRaster as IRasterProps; int width = pProps.Width; int height = pProps.Height; IPnt blocksize = new PntClass(); blocksize.SetCoords(width, height); IPixelBlock3 pixelblock = pRaster.CreatePixelBlock(blocksize) as IPixelBlock3; //Populate some pixel values to the pixel block. System.Array pixels; pixels = (System.Array)pixelblock.get_PixelData(0); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { pixels.SetValue(dbData[i, j], i, j); } } pixelblock.set_PixelData(0, (System.Array)pixels); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y); //Write the pixel block. IRasterEdit rasterEdit = (IRasterEdit)pRaster; rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock); return(true); }
private void updateWithMergedValues(IEnvelope env, IPixelBlock3 ipPixelBlock) { System.Array[] outPixelValuesArr = new System.Array[ipPixelBlock.Planes]; IPnt pntSize = new PntClass(); pntSize.SetCoords(ipPixelBlock.Width, ipPixelBlock.Height); ISpatialFilter spFlt = new SpatialFilterClass(); spFlt.Geometry = (IGeometry)env; spFlt.GeometryField = ftrCls.ShapeFieldName; spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIndexIntersects; IFeatureCursor fCur = ftrCls.Search(spFlt, false); ////int fIndex = ftrCls.FindField("catIndex"); IFeature ftr = fCur.NextFeature(); for (int i = 0; i < ipPixelBlock.Planes; i++) { outPixelValuesArr[i] = (System.Array)ipPixelBlock.get_PixelData(i); } //IQueryFilter qf = new QueryFilterClass(); //string s1 = "(XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s2 = "(XMIN > " + env.XMin.ToString() + " AND XMIN < " + env.XMax.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s3 = "(XMAX < " + env.XMax.ToString() + " AND XMIN > " + env.XMin.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s4 = "(YMIN > " + env.YMin.ToString() + " AND YMIN < " + env.YMax.ToString() + " AND XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + ")"; //string s5 = "(YMAX < " + env.YMax.ToString() + " AND YMIN > " + env.YMin.ToString() + " AND XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + ")"; //qf.WhereClause = s1 + " OR " + s2 + " OR " + s3 + " OR " + s4 + " OR " + s5; //ICursor cur = tbl.Search(qf, false); //IRow rw = cur.NextRow(); List <IPixelBlock> inPbValue = new List <IPixelBlock>(); //while (rw != null) //{ // int rsIndex = System.Convert.ToInt32(rw.get_Value(catIndex)); // IRaster rs = inrs[rsIndex]; // IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); // IRaster2 rs2 = (IRaster2)rs; // int pClm, pRw; // rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); // IPnt tlc = new PntClass(); // tlc.SetCoords(pClm, pRw); // rs.Read(tlc, inputPb); // inPbValue.Add(inputPb); // rw = cur.NextRow(); //} while (ftr != null) { int rsIndex = System.Convert.ToInt32(ftr.get_Value(catIndex)); IRaster rs = inrs[rsIndex]; IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); IRaster2 rs2 = (IRaster2)rs; int pClm, pRw; rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); IPnt tlc = new PntClass(); tlc.SetCoords(pClm, pRw); rs.Read(tlc, inputPb); inPbValue.Add(inputPb); ftr = fCur.NextFeature(); } for (int i = 0; i < ipPixelBlock.Planes; i++) { for (int r = 0; r < ipPixelBlock.Height; r++) { for (int c = 0; c < ipPixelBlock.Width; c++) { object vl = getValue(i, c, r, inPbValue); outPixelValuesArr[i].SetValue(vl, c, r); } } } for (int i = 0; i < outPixelValuesArr.Length; i++) { ipPixelBlock.set_PixelData(i, outPixelValuesArr[i]); } }
public IRaster TINToDEM(ITin pTin) { IPoint pOrigin = pTin.Extent.LowerLeft; IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory(); ESRI.ArcGIS.Geodatabase.IWorkspaceName pworkspaceName = pworkspaceFactory.Create(null, "MyWorkspace", null, 0); ESRI.ArcGIS.esriSystem.IName pname = (IName)pworkspaceName; ESRI.ArcGIS.Geodatabase.IWorkspace inmemWor = (IWorkspace)pname.Open(); IPoint originpoint = pOrigin; IRasterWorkspace2 rasterws = (IRasterWorkspace2)inmemWor; int nCol, nRow; nCol = 500; nRow = 500; double cellsizeX, cellsizeY; cellsizeX = pTin.Extent.Width / nCol; cellsizeY = pTin.Extent.Height / nRow; //用于计算的 float型的栅格数据 IRasterDataset demdataset = rasterws.CreateRasterDataset("Dataset", "MEM", originpoint, nCol, nRow, (double)cellsizeX, (double)cellsizeY, 1, rstPixelType.PT_DOUBLE, null, true); try { System.Runtime.InteropServices.Marshal.ReleaseComObject(pname); System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceFactory); System.Runtime.InteropServices.Marshal.ReleaseComObject(pworkspaceName); System.Runtime.InteropServices.Marshal.ReleaseComObject(inmemWor); } catch { } //IRawPixels pRawPixels = GetRawPixels(pRDS, 0); IRaster pRaster = demdataset.CreateDefaultRaster(); IPnt pBlockSize = new DblPnt(); //nCol = 50; //nRow = 50; pBlockSize.X = nCol; pBlockSize.Y = nRow; IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize); //IPixelBlock pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize); IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3; //object val = pPixelBlock.get_SafeArray(0); ITinSurface pTinSurf = pTin as ITinSurface; // IRasterProps pRasterProps = pRawPixels as IRasterProps; IRasterProps pRasterProps = pRaster as IRasterProps; object nodata; //pOrigin.X = pOrigin.X + (cellsize * 0.5); //pOrigin.Y = pOrigin.Y + (cellsize * nRow) - (cellsize * 0.5); pOrigin.X = pOrigin.X; pOrigin.Y = pOrigin.Y + (cellsizeY * nRow); nodata = pRasterProps.NoDataValue; IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass(); //这个pOrigin为栅格左上角 //pbridge2.QueryPixelBlock(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, esriRasterizationType.esriElevationAsRaster, nodata, ref val); //if (pTin.ProcessCancelled) // return null; //val.GetType(); CalPixelArray(pTinSurf, pOrigin.X, pOrigin.Y, cellsizeX, cellsizeY, ref pPixelBlock3); IPnt pOffset = new DblPnt(); pOffset.X = 0; pOffset.Y = 0; //pPixelBlock3.set_PixelData(0, val); //pRawPixels.Write(pOffset, (IPixelBlock)pPixelBlock3);//写入硬盘 IRasterEdit prasteredit = pRaster as IRasterEdit; prasteredit.Write(pOffset, (IPixelBlock)pPixelBlock3); //pRDS = OpenOutputRasterDataset(sDir, sName); //IPixelBlock pb = pRaster.CreatePixelBlock(pBlockSize); //pRaster.Read(pOffset,pb); return(pRaster); }
public IRasterDataset TinToRaster_new(ITinAdvanced pTin, esriRasterizationType eRastConvType, String sDir, String sName, rstPixelType ePixelType, Double cellsize, IEnvelope pExtent, bool bPerm) { IPoint pOrigin = pExtent.LowerLeft; //pOrigin.X = pOrigin.X - (cellsize * 0.5); //pOrigin.Y = pOrigin.Y - (cellsize * 0.5); pOrigin.X = pOrigin.X; pOrigin.Y = pOrigin.Y; int nCol, nRow; nCol = (int)Math.Round(pExtent.Width / cellsize); nRow = (int)Math.Round(pExtent.Height / cellsize); IGeoDataset pGDS = pTin as IGeoDataset; ISpatialReference2 pSR = pGDS.SpatialReference as ISpatialReference2; //这个pOrigin为栅格左下角 IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory(); IRasterWorkspace2 rasterws = pworkspaceFactory.OpenFromFile(sDir, 0) as IRasterWorkspace2; IPoint originpoint = pOrigin; //用于计算的 float型的栅格数据 IRasterDataset demdataset = rasterws.CreateRasterDataset(sName, "TIFF", originpoint, nCol, nRow, cellsize, cellsize, 1, rstPixelType.PT_DOUBLE, null, true); IRasterDataset pRDS = demdataset; //IRawPixels pRawPixels = GetRawPixels(pRDS, 0); IRaster pRaster = pRDS.CreateDefaultRaster(); IPnt pBlockSize = new DblPnt(); //nCol = 50; //nRow = 50; pBlockSize.X = nCol; pBlockSize.Y = nRow; IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize); //IPixelBlock pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize); IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3; //object val = pPixelBlock.get_SafeArray(0); ITinSurface pTinSurf = pTin as ITinSurface; // IRasterProps pRasterProps = pRawPixels as IRasterProps; IRasterProps pRasterProps = pRaster as IRasterProps; object nodata; //pOrigin.X = pOrigin.X + (cellsize * 0.5); //pOrigin.Y = pOrigin.Y + (cellsize * nRow) - (cellsize * 0.5); pOrigin.X = pOrigin.X; pOrigin.Y = pOrigin.Y + (cellsize * nRow); nodata = pRasterProps.NoDataValue; IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass(); //这个pOrigin为栅格左上角 //pbridge2.QueryPixelBlock(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, esriRasterizationType.esriElevationAsRaster, nodata, ref val); //if (pTin.ProcessCancelled) // return null; //val.GetType(); CalPixelArray(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, ref pPixelBlock3); IPnt pOffset = new DblPnt(); pOffset.X = 0; pOffset.Y = 0; //pPixelBlock3.set_PixelData(0, val); //pRawPixels.Write(pOffset, (IPixelBlock)pPixelBlock3);//写入硬盘 IRasterEdit prasteredit = pRaster as IRasterEdit; prasteredit.Write(pOffset, (IPixelBlock)pPixelBlock3); //pRDS = OpenOutputRasterDataset(sDir, sName); //IPixelBlock pb = pRaster.CreatePixelBlock(pBlockSize); //pRaster.Read(pOffset,pb); // ISaveAs pSaveas = pRasterProps as ISaveAs2; // pSaveas.SaveAs(sDir + "\\" + sName, null, "TIFF"); prasteredit.Refresh(); return(pRDS); }
//逐点算法 public bool ImageReprojectionRange(IRaster pSrcRaster, out IRaster pDstRaster, ExOriPara exori, double dbFocus, double fx, double fy, int nImgWidth, int nImgHeight, int nGeoRange) { pDstRaster = null; Pt2i ptSubImgLeftTop = new Pt2i(); double[,] dbSubDemData = getSubDem(pSrcRaster, exori.pos, nGeoRange, ref ptSubImgLeftTop); if (dbSubDemData == null) { return(false); } IRasterProps pProps = pSrcRaster as IRasterProps; int nDemHeight = pProps.Height; int nDemWidth = pProps.Width; IRaster2 pRaster2 = pSrcRaster as IRaster2; double dbNoDataValue = getNoDataValue(pProps.NoDataValue); //object pNodata = pProps.NoDataValue; //double value=((double[])pNodata)[0]; //double dbNoDataValue =double.Parse((float[]pNodata)[0].ToString()); //double dbNoDataValue = Convert.ToDouble(((double[]))[0]); //object dbNoDataValue = Convert.ToDouble(pProps.NoDataValue.ToString()); //object nodatavalue = pProps.NoDataValue; //Type type=pProps.NoDataValue.GetType(); //double dbNoDataValue = type.IsArray ? nodatavalue[0] as double : nodatavalue as double; //初始步长 double dbInitialStep = 0; int nGridW = nDemWidth / 10; int nGridH = nDemHeight / 10; int nCount = 0; double dbHeightAvg = 0; for (int i = 0; i < 10; i++) { for (int j = 0; j < 10; j++) { double dDemZ = double.NaN; double dbGeoX = pRaster2.ToMapX(i * nGridW); double dbGeoY = pRaster2.ToMapY(j * nGridH); if (GetGeoZ(pSrcRaster, dbSubDemData, ptSubImgLeftTop, dbGeoX, dbGeoY, ref dDemZ) && Math.Abs(dDemZ - dbNoDataValue) >= 10e-10) { nCount++; dbHeightAvg += dDemZ; } } } if (nCount != 0) { dbHeightAvg /= nCount; } else { return(false); } double dbCurCameraZ = 0; //IRaster2 pRaster2 = pSrcRaster as IRaster2; //int nCameraImgX = pRaster2.ToPixelColumn(exori.pos.X);//dXCumulate - pDem.m_PtOrigin.X) / dXRdem; //int nCameraImgY = pRaster2.ToPixelRow(exori.pos.Y); // (dYCumulate - pDem.m_PtOrigin.Y) / dYRdem; //if (nCameraImgY >= 0 || nCameraImgY < nDemHeight || nCameraImgX >= 0 || nCameraImgX < nDemWidth) //{ if (GetGeoZ(pSrcRaster, dbSubDemData, ptSubImgLeftTop, exori.pos.X, exori.pos.Y, ref dbCurCameraZ) && Math.Abs(dbCurCameraZ - dbNoDataValue) >= 10e-10) { dbHeightAvg = dbCurCameraZ; } //} dbInitialStep = Math.Abs(dbHeightAvg - exori.pos.Z) / 2; Point2D ptLeftTop = new Point2D(0, 0); double[] dbResolution = new double[2]; dbResolution[0] = pProps.MeanCellSize().X; dbResolution[1] = pProps.MeanCellSize().Y; int[] nSize = new int[2]; nSize[0] = nDemWidth; nSize[1] = nDemHeight; //pDstRaster = CreateRaster(ptLeftTop, dbResolution, nSize); //pDstRaster = createRasterWithoutData(ptLeftTop, dbResolution[0], nSize, "testOutput.tif"); // byte[,] dbData = new byte[nDemWidth, nDemHeight]; //double demGrayVal=double.NaN; //Pt3d demXYZ; //byte byteGray; //byte bt = (byte)255; //Pt2d pt; Matrix matA, matB; matA = new Matrix(2, 2); matB = new Matrix(2, 1); Matrix matR; matR = new Matrix(3, 3); //Matrix matX; double[] a = new double[4]; double[] b = new double[2]; OPK2RMat(exori.ori, ref matR); //求解相关系数 double a1 = matR.getNum(0, 0); double a2 = matR.getNum(0, 1); double a3 = matR.getNum(0, 2); double b1 = matR.getNum(1, 0); double b2 = matR.getNum(1, 1); double b3 = matR.getNum(1, 2); double c1 = matR.getNum(2, 0); double c2 = matR.getNum(2, 1); double c3 = matR.getNum(2, 2); double[] dbCoef = new double[] { a1, a2, a3, b1, b2, b3, c1, c2, c3 }; //double X, Y, Z, Z1; // Z = 0.0; //double dthreshold = 0.01; //初始化数组 //int[,] dbData = new int[nDemWidth, nDemHeight]; //for (int i = 0; i < nDemWidth; i++) //{ // for (int j = 0; j < nDemHeight; j++) // { // dbData[i, j] = 0; // } //} try { //生成RASTER Point2D pt2dTopLeft = new Point2D(); pt2dTopLeft.X = pProps.Extent.UpperLeft.X; pt2dTopLeft.Y = pProps.Extent.UpperLeft.Y; pDstRaster = CreateRaster(pt2dTopLeft, dbResolution, nSize); if (pDstRaster == null) { return(false); } //得到数组 IPnt pBlockSize = new DblPntClass(); pBlockSize.X = nDemWidth; pBlockSize.Y = nDemHeight; IPnt pntLeftTop = new DblPntClass(); pntLeftTop.SetCoords(ptLeftTop.X, ptLeftTop.Y); IPixelBlock pPixelBlock = pDstRaster.CreatePixelBlock(pBlockSize); IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3; pDstRaster.Read(pntLeftTop, pPixelBlock); System.Array pixels; pixels = (System.Array)pPixelBlock3.get_PixelData(0); //初始化 object oValue = getValidType(pDstRaster as IRasterProps, 0); for (int i = 0; i < nDemHeight; i++) { for (int j = 0; j < nDemWidth; j++) { pixels.SetValue(oValue, j, i); } } //逐像素判断是否可见 IRaster2 pSrcRaster2 = pSrcRaster as IRaster2; oValue = getValidType(pDstRaster as IRasterProps, 255); for (int i = 0; i < nImgHeight; i++) { for (int j = 0; j < nImgWidth; j++) { Point2D ptCurrent = null; if (getPixelIsCoverd(pSrcRaster, dbSubDemData, ptSubImgLeftTop, j, i, out ptCurrent, exori, dbCoef, dbFocus, fx, fy, dbInitialStep)) { int nCol = int.MaxValue, nRow = int.MaxValue; pSrcRaster2.MapToPixel(ptCurrent.X, ptCurrent.Y, out nCol, out nRow); if (nCol >= nDemWidth || nCol < 0 || nRow < 0 || nRow >= nDemHeight) { continue; } pixels.SetValue(oValue, nCol, nRow); //pixels[nCol, nRow] = 255; } } } pPixelBlock3.set_PixelData(0, (System.Array)pixels); //修改数据 IRasterEdit pRasterEdit = pDstRaster as IRasterEdit; pRasterEdit.Write(pntLeftTop, pPixelBlock); pRasterEdit.Refresh(); } catch (System.Exception ex) { MessageBox.Show(ex.Message); return(false); } return(true); }
/// <summary> /// Gets value of pixel at the specified position. /// </summary> /// <param name="pos"></param> /// <param name="raster"></param> /// <returns></returns> public static double GetValue(Position pos, IRaster raster) { IPnt regionSize = new PntClass(); regionSize.SetCoords(1, 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(pos.Column, pos.Row); raster.Read(tl, pixelBlock); return Convert.ToDouble(pixelBlock.GetVal(0, 0, 0)); }
public static IRasterDataset CreateRasterDataset(string filePath, string fileName, IRasterLayer rasterLayer, StructRasterMetaData structRasterMetaData, int[,] data, int noDataValue) { try { IRasterWorkspace2 rasterWorkspace2 = OpenRasterWorkspace(filePath); //Define the origin for the raster dataset, which is the lower left corner of the raster. IPoint originPoint = new PointClass(); originPoint.PutCoords(structRasterMetaData.XMin, structRasterMetaData.YMin); //Define the dimensions of the raster dataset. int width = structRasterMetaData.RowCount; //This is the width of the raster dataset. int height = structRasterMetaData.ColumnCount; //This is the height of the raster dataset. IRaster r = rasterLayer.Raster; IRasterDefaultProps rdp = r as IRasterDefaultProps; double xCellSize = rdp.DefaultPixelWidth; //This is the cell size in x direction. double yCellSize = rdp.DefaultPixelHeight; //This is the cell size in y direction. ISpatialReference spatialReference = rdp.DefaultSpatialReference; int bandCount = 1; // This is the number of bands the raster dataset contains. //Create a raster dataset in TIFF format. IRasterDataset rasterDataset = rasterWorkspace2.CreateRasterDataset(fileName, "IMAGINE Image", originPoint, height, width, xCellSize, yCellSize, bandCount, rstPixelType.PT_UCHAR, spatialReference, true); //If you need to set NoData for some of the pixels, you need to set it on band //to get the raster band. IRasterBandCollection rasterBands = (IRasterBandCollection)rasterDataset; IRasterBand rasterBand; IRasterProps rasterProps; rasterBand = rasterBands.Item(0); rasterProps = (IRasterProps)rasterBand; //Set NoData if necessary. For a multiband image, a NoData value needs to be set for each band. rasterProps.NoDataValue = -9999f; //Create a raster from the dataset. IRaster raster = rasterDataset.CreateDefaultRaster(); //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". IPnt blocksize = new PntClass(); blocksize.SetCoords(height, width); IPixelBlock3 pixelblock = raster.CreatePixelBlock(blocksize) as IPixelBlock3; object temp = pixelblock.get_PixelDataByRef(0); System.Byte[,] pixelData = (System.Byte[, ])temp; for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (data[i, j] == -9999f) { pixelData[j, i] = (System.Byte)noDataValue; //System.Diagnostics.Debug.WriteLine(i.ToString() + "+" + j.ToString()); } else { if (pixelData[j, i] != Convert.ToByte(data[i, j])) { pixelData[j, i] = Convert.ToByte(data[i, j]); } //System.Diagnostics.Debug.WriteLine(i.ToString() + "-" + j.ToString()); } } } pixelblock.set_PixelData(0, pixelData); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(0, 0); //Write the pixel block. IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock); //Release rasterEdit explicitly. System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); return(rasterDataset); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return(null); } }
private void middleRowColumn(IPnt loc, int[] startRows, int[] startColumns) { double x = loc.X; double y = loc.Y; string outLocStr = x.ToString() + ":" + y.ToString(); //string inLocStr = (x - 1).ToString() + ":" + (y - 1).ToString(); IPnt readLoc = new PntClass(); readLoc.SetCoords(x - 1, y - 1); IRasterEdit regRsE = (IRasterEdit)OutRaster; IPnt writePbSize = new PntClass(); writePbSize.SetCoords(pbwidth, pbheight); IPnt readPbSize = new PntClass(); readPbSize.SetCoords(pbwidth + 2, pbheight + 2); IPixelBlock pb = inRs.CreatePixelBlock(readPbSize); IPixelBlock pb2 = OutRaster.CreatePixelBlock(writePbSize); System.Array[] inOutArr; System.Array inArr = null; System.Array outArr = null; if (outArrDic.TryGetValue(outLocStr, out inOutArr)) { inArr = inOutArr[0]; outArr = inOutArr[1]; } else { //Console.WriteLine(outLocStr); OutRaster.Read(loc, pb2); inRs.Read(readLoc, pb); OutRaster.Read(loc, pb2); inArr = (System.Array)pb.get_SafeArray(0); outArr = (System.Array)pb2.get_SafeArray(0); outArrDic[outLocStr] = new System.Array[] { inArr, outArr }; } int height = pb2.Height; int width = pb2.Width; for (int si = 0; si < startRows.Length; si++) { int c = startColumns[si]; int r = startRows[si]; int ic = c + 1; int ir = r + 1; //Console.WriteLine(cr[0]); int inVl = System.Convert.ToInt32(inArr.GetValue(ic, ir)); if ((inVl == noDataVl) || (inVl == (noDataVl - 1))) { Console.WriteLine("Invalue form 2 middle = " + inVl.ToString()); continue; } else { int outVl32 = System.Convert.ToInt32(outArr.GetValue(c, r)); if (outVl32 != noDataVl2) { } else { List <string> cr = new List <string>(); cr.Add(c.ToString() + ":" + r.ToString()); outArr.SetValue(counter, c, r); List <int>[] nextArray = { new List <int>(), new List <int>(), new List <int>(), new List <int>() };//determines if the next pixel block must be queried {left,top,right,bottom} while (cr.Count > 0) { rCnt++; rPerm += findRegion(inVl, counter, noDataVl2, inArr, outArr, cr, nextArray); } for (int i = 0; i < nextArray.Length; i++) { List <int> pbNextLst = nextArray[i]; if (pbNextLst.Count > 0) { int[] startClms = new int[pbNextLst.Count]; int[] startRws = new int[pbNextLst.Count]; IPnt newLoc = new PntClass(); double nClP = loc.X; double nRwP = loc.Y; switch (i) { case 0: nClP = nClP - pbwidth; startRws = pbNextLst.ToArray(); int stcl = pbwidth - 1; for (int k = 0; k < startRws.Length; k++) { startClms[k] = stcl; } break; case 1: nRwP = nRwP - pbheight; startClms = pbNextLst.ToArray(); //rws=pbHeight-1 int strw = pbheight - 1; for (int k = 0; k < startClms.Length; k++) { startRws[k] = strw; } break; case 2: nClP = nClP + pbwidth; startRws = pbNextLst.ToArray(); //clms=0; break; default: nRwP = nRwP + pbheight; startClms = pbNextLst.ToArray(); //rws = 0; break; } if ((nClP >= 0 && nRwP >= 0 & nClP <= rsProps2.Width && nRwP <= rsProps2.Height)) { newLoc.SetCoords(nClP, nRwP); middleRowColumn(newLoc, startRws, startClms); } } } } } } return; }
/// <summary> /// Write edits to the input raster. /// </summary> /// <param name="raster">Raster of raster layer to be edited.</param> /// <param name="edits">Pixel collection that contains edited pixels.</param> private static void WriteEdits(IRaster raster, PixelCollection edits) { IRasterProps rasterProps = (IRasterProps)raster; int minRow = rasterProps.Height - 1; int maxRow = 0; int minCol = rasterProps.Width - 1; int maxCol = 0; for (int i = 0; i < edits.Count; i++) { #region Get the extent of the edition region Position cellPos = edits[i].Position; if (cellPos.Row > maxRow) { maxRow = cellPos.Row; } if (cellPos.Row < minRow) { minRow = cellPos.Row; } if (cellPos.Column > maxCol) { maxCol = cellPos.Column; } if (cellPos.Column < minCol) { minCol = cellPos.Column; } #endregion } IPnt pos = new PntClass(); pos.SetCoords(maxCol - minCol + 1, maxRow - minRow + 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(pos); pos.SetCoords(minCol, minRow); raster.Read(pos, pixelBlock); // Set new values IPixelBlock3 pixelBlock3 = (IPixelBlock3)pixelBlock; Array pixels = (Array)pixelBlock3.get_PixelData(0); for (int i = 0; i < edits.Count; i++) { object value = null; Raster.CSharpValue2PixelValue(edits[i].NewValue, rasterProps.PixelType, out value); pixels.SetValue(value, edits[i].Position.Column - minCol, edits[i].Position.Row - minRow); } pixelBlock3.set_PixelData(0, (System.Object)pixels); IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(pos, (IPixelBlock)pixelBlock3); }
/// <summary> /// Get the pixel values in a region of the input raster. /// </summary> /// <param name="tlCorner"></param> /// <param name="brCorner"></param> /// <param name="raster"></param> /// <returns></returns> public static double[,] GetValues(Position tlCorner, Position brCorner, IRaster raster) { int colCount = brCorner.Column - tlCorner.Column + 1; int rowCount = brCorner.Row - tlCorner.Row + 1; IPnt regionSize = new PntClass(); regionSize.SetCoords(colCount, rowCount); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(tlCorner.Column, tlCorner.Row); raster.Read(tl, pixelBlock); double[,] values = new double[colCount, rowCount]; for (int x = 0; x < colCount; x++) { for (int y = 0; y < rowCount; y++) { values[x, y] = Convert.ToDouble(pixelBlock.GetVal(0, x, y)); } } return values; }
// From ArcObjects Help: How to Create a Raster dataset // http://resources.arcgis.com/en/help/arcobjects-net/conceptualhelp/index.html#/How_to_create_a_raster_dataset/000100000464000000/ public static IRasterDataset CreateRasterDataset(string Path, string FileName) { try { IRasterWorkspace2 rasterWs = OpenRasterWorkspace(Path); // This is a custom method that's at the bottom of this code. //Define the spatial reference of the raster dataset. ISpatialReference sr = new UnknownCoordinateSystemClass(); //Define the origin for the raster dataset, which is the lower left corner of the raster. IPoint origin = new PointClass(); origin.PutCoords(15.0, 15.0); //Define the dimensions of the raster dataset. int width = 100; //This is the width of the raster dataset. int height = 100; //This is the height of the raster dataset. double xCell = 30; //This is the cell size in x direction. double yCell = 30; //This is the cell size in y direction. int NumBand = 1; // This is the number of bands the raster dataset contains. //Create a raster dataset in TIFF format. IRasterDataset rasterDataset = rasterWs.CreateRasterDataset(FileName, "TIFF", origin, width, height, xCell, yCell, NumBand, rstPixelType.PT_UCHAR, sr, true); //If you need to set NoData for some of the pixels, you need to set it on band //to get the raster band. IRasterBandCollection rasterBands = (IRasterBandCollection)rasterDataset; IRasterBand rasterBand; IRasterProps rasterProps; rasterBand = rasterBands.Item(0); rasterProps = (IRasterProps)rasterBand; //Set NoData if necessary. For a multiband image, a NoData value needs to be set for each band. rasterProps.NoDataValue = 255; //Create a raster from the dataset. IRaster raster = ((IRasterDataset2)rasterDataset).CreateFullRaster(); //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". IPnt blocksize = new PntClass(); blocksize.SetCoords(width, height); IPixelBlock3 pixelblock = raster.CreatePixelBlock(blocksize) as IPixelBlock3; //Populate some pixel values to the pixel block. System.Array pixels; pixels = (System.Array)pixelblock.get_PixelData(0); for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { if (i == j) { pixels.SetValue(Convert.ToByte(255), i, j); } else { pixels.SetValue(Convert.ToByte((i * j) / 255), i, j); } } } pixelblock.set_PixelData(0, (System.Array)pixels); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(0, 0); //Write the pixel block. IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock); //Release rasterEdit explicitly. System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); return(rasterDataset); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return(null); } }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst });//{esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst}); System.DateTime dt = System.DateTime.Now; System.DateTime dt2; TimeSpan ts; rasterUtil rsUtil = new rasterUtil(); geoDatabaseUtility geoUtil = new geoDatabaseUtility(); string pred = @"C:\Users\jshogland\Documents\John\projects\FtStewart\models\TreeEstimates\HdwPresentPred.bch"; string mdl = @"C:\Users\jshogland\Documents\John\projects\FtStewart\models\TreeEstimates\HdwPresent.mdl"; double[] minArr, maxArr; Console.WriteLine("Getting Min Max"); batchCalculations.getMinMaxArr(mdl, out minArr, out maxArr); Console.WriteLine("First Min Max: " + minArr[0].ToString() + ";" + maxArr[0].ToString()); IFunctionRasterDataset fdset = rsUtil.extactModelDomainFunction(pred, minArr, maxArr); Console.WriteLine(fdset.RasterInfo.PixelType.ToString()); IRaster rs = rsUtil.createRaster(fdset); IPnt pntSize = new PntClass(); pntSize.SetCoords(100, 100); IPixelBlock pb = rs.CreatePixelBlock(pntSize); rs.Read(pntSize, pb); int cnt = 0; for (int r = 0; r < pb.Height; r++) { for (int c = 0; c < pb.Width; c++) { object vl = pb.GetVal(0, c, r); if (vl != null) { if (System.Convert.ToInt32(vl) == 0) { cnt++; } } } } Console.WriteLine("Total zeros = " + cnt.ToString()); //string dir = @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Classes\Mining Big Data\Assignments\NatureServe\train\ALB"; //string[] fls = System.IO.Directory.GetFiles(dir, "*.jpg"); //foreach (string flPath in fls) //{ // string nm = System.IO.Path.GetFileNameWithoutExtension(flPath); // Console.WriteLine(nm); // Bitmap bm = new Bitmap(flPath); // Accord.Imaging.Moments.CentralMoments cm = new Accord.Imaging.Moments.CentralMoments(bm, 3); // //Console.WriteLine(cm.Mu00.ToString()); // Console.WriteLine("\t"+cm.Mu01.ToString()); // Console.WriteLine("\t" + cm.Mu02.ToString()); // Console.WriteLine("\t" + cm.Mu03.ToString()); // Console.WriteLine("\t" + cm.Mu10.ToString()); // Console.WriteLine("\t" + cm.Mu20.ToString()); // Console.WriteLine("\t" + cm.Mu30.ToString()); //} //string plots = @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\coReg.gdb\SampleLocations"; //string ls= @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\FloridaLandsat.tif"; //string naip= @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\GeorgiaNaipAgAl.tif"; //rasterUtil rsUtil = new rasterUtil(); //HashSet<string> uStr = new HashSet<string>(); //int[] filesLines = getClasses(prjDir,ref uStr); //Console.WriteLine("Files = " + filesLines[0].ToString()); //Console.WriteLine("Lines = " + filesLines[1].ToString()); //Console.WriteLine(uStr.Count().ToString()); //geoDatabaseUtility geoUtil = new geoDatabaseUtility(); //rasterUtil rsUtil = new rasterUtil(); //featureUtil ftrUtil = new featureUtil(rsUtil); ////string origPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\OriginalSample"; ////string nwPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\RandomtShiftSample"; ////CreateNewPoints(origPath, nwPath, rsUtil, ftrUtil, geoUtil, true); //string fiaTestPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\RandomtShiftSample"; //string fiaOutPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\adjustSample"; //string rsPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\models\predictorsOneVariable.bch"; //IFunctionRasterDataset fDset = rsUtil.createIdentityRaster(rsPath); //IFeatureClass ftrCls = geoUtil.getFeatureClass(fiaTestPath); //int error = 15; //adjustCoregistrationErrors aE = new adjustCoregistrationErrors(rsUtil); //aE.FunctionRasterDataset = fDset; //aE.DependentField = "Pred15"; //aE.GeometricErrorCells = error; //aE.OutFtrClassPath = fiaOutPath; //aE.PlotFeatureClass = ftrCls; //aE.adjustErrors(); dt2 = System.DateTime.Now; ts = dt2.Subtract(dt); Console.WriteLine("Total Seconds = " + ts.TotalSeconds.ToString()); m_AOLicenseInitializer.ShutdownApplication(); }
//分析的主要实现函数 private IRasterLayer Analyze(IRasterLayer pRasterLayer) { IRaster pRaster = pRasterLayer.Raster; IRasterProps rasterProps = (IRasterProps)pRaster; //设置栅格数据起始点 IPnt pBlockSize = new Pnt(); pBlockSize.SetCoords(rasterProps.Width, rasterProps.Height); //选取整个范围 IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize); //左上点坐标 IPnt tlp = new Pnt(); tlp.SetCoords(0, 0); //读入栅格 IRasterBandCollection pRasterBands = pRaster as IRasterBandCollection; IRasterBand pRasterBand = pRasterBands.Item(0); IRawPixels pRawRixels = pRasterBands.Item(0) as IRawPixels; pRawRixels.Read(tlp, pPixelBlock); //将PixBlock的值组成数组 Array pSafeArray = pPixelBlock.get_SafeArray(0) as Array; //Array转数组 double[,] myDoubleArr = new double[pSafeArray.GetLength(0), pSafeArray.GetLength(1)]; for (int i = 0; i < myDoubleArr.GetLength(0); i++) { for (int j = 0; j < myDoubleArr.GetLength(1); j++) { myDoubleArr[i, j] = Convert.ToDouble(pSafeArray.GetValue(i, j)); } } for (int i = 0; i < myDoubleArr.GetLength(0); i++) { for (int j = 0; j < myDoubleArr.GetLength(1); j++) { if (myDoubleArr[i, j] == 255) { myDoubleArr[i, j] = 0; } } } double[,] ZeroArray = GetArray(myDoubleArr, Convert.ToInt32(textBox4.Text)); double[,] OArray = SumArray(ZeroArray, Convert.ToInt32(textBox4.Text)); double[,] LastArray = ReturnLastArray(OArray, Convert.ToInt32(textBox4.Text)); pPixelBlock.set_SafeArray(0, LastArray); //StreamWriter sw = File.AppendText(@"E:\GIS底层实验\WorkSpace\result\arrry.txt"); //for (int y = 0; y < rasterProps.Height; y++) //{ // for (int x = 0; x < rasterProps.Width; x++) // { // //int value = Convert.ToInt32(pSafeArray.GetValue(x, y)); // Byte value = Convert.ToByte(pSafeArray.GetValue(x, y)); // string TxtCon = ("X:" + Convert.ToString(x) + "," + "Y:" + Convert.ToString(y) + "," + "Value" + pSafeArray.GetValue(x, y) + "\n"); // sw.Write(TxtCon); // } //} //sw.Flush(); //sw.Close(); // 编辑raster,将更新的值写入raster中 IRasterEdit rasterEdit = pRaster as IRasterEdit; rasterEdit.Write(tlp, pPixelBlock); rasterEdit.Refresh(); return(pRasterLayer); }
/// <summary> /// Write edits to the input raster. /// </summary> /// <param name="raster"></param> private static void WriteEdits(IRaster raster) { IRasterProps rasterProps = (IRasterProps)raster; int minRow = rasterProps.Height - 1; int maxRow = 0; int minCol = rasterProps.Width - 1; int maxCol = 0; for (int i = 0; i < Editor.Edits.Count; i++) { #region Get the extent of the edition region Position cellPos = Editor.Edits[i].Position; if (cellPos.Row > maxRow) { maxRow = cellPos.Row; } if (cellPos.Row < minRow) { minRow = cellPos.Row; } if (cellPos.Column > maxCol) { maxCol = cellPos.Column; } if (cellPos.Column < minCol) { minCol = cellPos.Column; } #endregion } IPnt pos = new PntClass(); pos.SetCoords(maxCol - minCol + 1, maxRow - minRow + 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(pos); pos.SetCoords(minCol, minRow); raster.Read(pos, pixelBlock); // Set new values IPixelBlock3 pixelBlock3 = (IPixelBlock3)pixelBlock; Array pixels = (Array)pixelBlock3.get_PixelData(0); for (int i = 0; i < Editor.Edits.Count; i++) { object value = null; Editor.CSharpValue2PixelValue(Editor.Edits[i].NewValue, rasterProps.PixelType, out value); pixels.SetValue(value, Editor.Edits[i].Position.Column - minCol, Editor.Edits[i].Position.Row - minRow); } pixelBlock3.set_PixelData(0, (System.Object)pixels); IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(pos, (IPixelBlock)pixelBlock3); }
public void ConvertGridMetricsToRaster(string metricsDir, string outDir, int[] metrics) { string[] metricFiles = System.IO.Directory.GetFiles(metricsDir, "*.csv"); string[] headerFiles = System.IO.Directory.GetFiles(metricsDir, "*.txt"); IPnt cellSize; IPnt[] tlPntArr; int[] rwArr; int[] clmArr; float noDataVl; IEnvelope ext = getExtentsFromHeader(headerFiles, out cellSize, out tlPntArr, out rwArr, out clmArr, out noDataVl); IWorkspace outWks = geoUtil.OpenRasterWorkspace(outDir); string exePath = "\"" + fusDir + "\\" + csv2Grid + "\""; IRasterEdit[] rsArr = new IRasterEdit[metrics.Length]; for (int i = 0; i < metrics.Length; i++) { int clm = metrics[i]; string metricName = MetricsArr[clm]; IRasterDataset rsDset = rsUtil.createNewRaster(ext, cellSize, outWks, metricName, 1, rstPixelType.PT_FLOAT, rasterUtil.rasterType.IMAGINE, null);//rsWk2.CreateRasterDataset(metricName+".img","IMAGINE Image",ext.LowerLeft,w,h,cellSize.X,cellSize.Y,1,rstPixelType.PT_FLOAT,null,true); IRasterBand rsB = ((IRasterBandCollection)rsDset).Item(0); IRasterProps rsP = (IRasterProps)rsB; rsP.NoDataValue = noDataVl; IRaster rs = ((IRasterDataset2)rsDset).CreateFullRaster(); rsArr[i] = (IRasterEdit)rs; } foreach (string s in metricFiles) { Console.WriteLine("Working on " + s); int pntIndex = System.Array.IndexOf(metricFiles, s); IPnt tl = tlPntArr[pntIndex]; int cl, rw; ((IRaster2)rsArr[0]).MapToPixel(tl.X, tl.Y, out cl, out rw); IPnt tlp = new PntClass(); tlp.X = cl; tlp.Y = rw; int rws = rwArr[pntIndex]; int clms = clmArr[pntIndex]; IPnt bSize = new PntClass(); bSize.SetCoords(clms, rws); System.Array[] pbSafeArr = new System.Array[metrics.Length]; IPixelBlock3[] pbArr = new IPixelBlock3[metrics.Length]; for (int i = 0; i < metrics.Length; i++) { IRasterEdit rsE = rsArr[i]; IRaster rs = (IRaster)rsE; IPixelBlock3 pb = (IPixelBlock3)rs.CreatePixelBlock(bSize); rs.Read(tlp, (IPixelBlock)pb); //pb.Mask(0); pbArr[i] = pb; System.Array vlArr = (System.Array)pb.get_PixelData(0); pbSafeArr[i] = vlArr; } using (System.IO.StreamReader sr = new System.IO.StreamReader(s)) { string hdr = sr.ReadLine(); while (!sr.EndOfStream) { string ln = sr.ReadLine(); string[] lnArr = ln.Split(new char[] { ',' }); int r = (rws - 1) - System.Convert.ToInt32(lnArr[0]); int c = System.Convert.ToInt32(lnArr[1]); for (int i = 0; i < metrics.Length; i++) { int clIndex = metrics[i]; float clVl = System.Convert.ToSingle(lnArr[clIndex]); if (clVl != noDataVl) { pbSafeArr[i].SetValue(clVl, c, r); } } } sr.Close(); } for (int i = 0; i < metrics.Length; i++) { IPixelBlock3 pb = pbArr[i]; pb.set_PixelData(0, pbSafeArr[i]); rsArr[i].Write(tlp, (IPixelBlock)pb); } } for (int i = 0; i < rsArr.Length; i++) { System.Runtime.InteropServices.Marshal.ReleaseComObject(rsArr[i]); } }