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); }
public static void exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat) //输出栅格数据 { string directory = parth.Substring(0, parth.LastIndexOf("\\")); string name = parth.Substring(parth.LastIndexOf("\\") + 1); IWorkspaceFactory workspaceFac = new RasterWorkspaceFactoryClass(); IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2; IRasterInfo rasterInfo = (rasterLayer.Raster as IRawBlocks).RasterInfo; IPoint originPoint = new Point(); originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y); IRasterProps rasterProps = rasterLayer.Raster as IRasterProps; IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height, rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true) as IRasterDataset2; IRaster2 raster2 = rasterDataSet.CreateDefaultRaster() as IRaster2; IPnt pntClass = new Pnt(); pntClass.X = rasterProps.Width; pntClass.Y = rasterProps.Height; IRasterCursor rasterCursor = raster2.CreateCursorEx(pntClass); IRasterCursor inRasterCursor = (rasterLayer.Raster as IRaster2).CreateCursorEx(pntClass); IRasterEdit rasterEdit = raster2 as IRasterEdit; if (rasterEdit.CanEdit()) { IPixelBlock3 pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; IPixelBlock3 inPixelBlock3 = inRasterCursor.PixelBlock as IPixelBlock3; System.Array pixels = (System.Array)rasterMat; pixelBlock3.set_PixelData(0, (System.Array)pixels); rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3); System.Runtime.InteropServices.Marshal.ReleaseComObject(pixelBlock3); } rasterEdit.Refresh(); IGeoDataset inDataset = rasterLayer.Raster as IGeoDataset; IGeoDataset outDataset = rasterDataSet as IGeoDataset; IExtractionOp op = new RasterExtractionOpClass(); var outDataset1 = op.Raster(outDataset, inDataset); var clipRaster = (IRaster)outDataset1; ISaveAs pSaveAs = clipRaster as ISaveAs; System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterCursor); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); System.Runtime.InteropServices.Marshal.ReleaseComObject(raster2); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataSet); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWorkspace2); System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFac); if (File.Exists(parth)) { File.Delete(parth); } workspaceFac = new RasterWorkspaceFactoryClass(); IDataset outdataset = pSaveAs.SaveAs(name, workspaceFac.OpenFromFile(directory, 0), "IMAGINE Image"); System.Runtime.InteropServices.Marshal.ReleaseComObject(outdataset); return; }
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); }
/// <summary> /// 栅格操作修改栅格的值 /// </summary> /// <param name="pRasterDataset2"></param> public static void ChangeRasterValue(IRasterDataset2 pRasterDataset2) { //设置读取栅格的大小 IRaster2 pRaster2 = pRasterDataset2.CreateFullRaster() as IRaster2; IPnt pPntBlock = new PntClass(); pPntBlock.X = 128; pPntBlock.Y = 128; IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock); IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; if (pRasterEdit.CanEdit()) { //循环波段,长和宽度 IRasterBandCollection pBands = pRasterDataset2 as IRasterBandCollection; IPixelBlock3 pPixelblock3 = null; int pBlockwidth = 0; int pBlockheight = 0; System.Array pixels; object pValue; long pBandCount = pBands.Count; // IRasterProps pRasterProps = pRaster2 as IRasterProps; object nodata = pRasterProps.NoDataValue; do { pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3; pBlockwidth = pPixelblock3.Width; pBlockheight = pPixelblock3.Height; for (int k = 0; k < pBandCount; k++) { pixels = (System.Array)pPixelblock3.get_PixelData(k); for (int i = 0; i < pBlockwidth; i++) { for (int j = 0; j < pBlockheight; j++) { pValue = pixels.GetValue(i, j); int value = Convert.ToInt32(pValue); if (Convert.ToInt32(pValue) != 3) { pixels.SetValue(Convert.ToByte(0), i, j); } } } pPixelblock3.set_PixelData(k, pixels); } pPntBlock = pRasterCursor.TopLeft; pRasterEdit.Write(pPntBlock, (IPixelBlock)pPixelblock3); } while (pRasterCursor.Next()); System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); } }
public static IRasterDataset exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat) { string directory = parth.Substring(0, parth.LastIndexOf("\\")); string name = parth.Substring(parth.LastIndexOf("\\") + 1); IWorkspaceFactory workspaceFac = new RasterWorkspaceFactoryClass(); IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2; IRasterInfo rasterInfo = (rasterLayer.Raster as IRawBlocks).RasterInfo; IPoint originPoint = new Point(); originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y); IRasterProps rasterProps = rasterLayer.Raster as IRasterProps; IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height, rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true); IRaster2 raster2 = rasterDataSet.CreateDefaultRaster() as IRaster2; IPnt pntClass = new Pnt(); pntClass.X = rasterProps.Width; pntClass.Y = rasterProps.Height; IRasterCursor rasterCursor = raster2.CreateCursorEx(pntClass); IRasterEdit rasterEdit = raster2 as IRasterEdit; if (rasterEdit.CanEdit()) { IRasterBandCollection bands = rasterDataSet as IRasterBandCollection; IPixelBlock3 pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; System.Array pixels = (System.Array)pixelBlock3.get_PixelData(0); for (int i = 0; i < rasterProps.Width; i++) { for (int j = 0; j < rasterProps.Height; j++) { pixels.SetValue(Convert.ToSingle(rasterMat[j, i]), i, j); } } pixelBlock3.set_PixelData(0, (System.Array)pixels); rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3); } (raster2 as IRasterProps).NoDataValue = 0f; rasterEdit.Refresh(); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); return(rasterDataSet); }
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); }
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 void UnderInit() { //接口转换 IRaster2 raster2 = m_raster as IRaster2; //获取栅格的属性 IRasterProps pRasterProps = raster2 as IRasterProps; //获取栅格的高度和宽度 int Height = pRasterProps.Height; int Width = pRasterProps.Width; //获取像元的大小 double cellsizex = pRasterProps.MeanCellSize().X; double cellsizey = pRasterProps.MeanCellSize().Y; //创建工作空间,存储NDVI计算结果 IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass(); IWorkspace pWs = pRasterWsFac.OpenFromFile(@"F:/RDB", 0); IRasterWorkspace2 pRasterWs; pRasterWs = pWs as IRasterWorkspace2; //设置原点与原栅格相同 IPoint origin = new PointClass(); origin.PutCoords(pRasterProps.Extent.XMin, pRasterProps.Extent.YMin); //定义空间参考系为未知参考系 ISpatialReference sr = new UnknownCoordinateSystemClass(); //创建栅格 IRasterDataset2 resultDataset = pRasterWs.CreateRasterDataset("NDVI.tif", "TIFF", origin, Width, Height, cellsizex, cellsizey, 1, rstPixelType.PT_DOUBLE, sr) as IRasterDataset2; //对创建的栅格创建栅格指针 IRaster resultRaster = resultDataset.CreateFullRaster(); IRasterCursor resultRasterCursor = ((IRaster2)resultRaster).CreateCursorEx(null); //对原始栅格创建栅格指针 IRasterCursor rasterCursor = raster2.CreateCursorEx(null); //创建两个像素块,用以同时遍历两个栅格 IPixelBlock3 resultPixelBlock = null; IPixelBlock3 tempPixelBlock = null; //创建IRasterEidt以便对结果栅格进行修改,填入计算结果 IRasterEdit resultRasterEdit = resultRaster as IRasterEdit; //初始化像素块宽度与高度 long blockWidth = 0; long blockHeight = 0; do { //对两个像素块进行更新 resultPixelBlock = resultRasterCursor.PixelBlock as IPixelBlock3; tempPixelBlock = rasterCursor.PixelBlock as IPixelBlock3; //获取原始栅格中近红外波段以及红波段的数据 System.Array pixels3 = (System.Array)tempPixelBlock.get_PixelData(VisibleBandID); System.Array pixels4 = (System.Array)tempPixelBlock.get_PixelData(InfraredBandID); //获取结果栅格像素块的高度和宽度,并以此进行遍历 blockHeight = resultPixelBlock.Height; blockWidth = resultPixelBlock.Width; //获取结果栅格像素块中第一波段的值 System.Array resultPixels = (System.Array)resultPixelBlock.get_PixelData(0); //根据NDVI公式,将计算结果写入到结果栅格像素块中 for (int i = 0; i < blockHeight; i++) { for (int j = 0; j < blockWidth; j++) { double up = double.Parse(pixels4.GetValue(j, i).ToString()) - double.Parse(pixels3.GetValue(j, i).ToString()); double down = double.Parse(pixels4.GetValue(j, i).ToString()) + double.Parse(pixels3.GetValue(j, i).ToString()); if (down != 0) { resultPixels.SetValue((up / down), j, i); } else { resultPixels.SetValue((0.0), j, i); } } } //将结算结果设置到结果栅格图像对应的像素块中,根据其位置进行更新后刷新 resultPixelBlock.set_PixelData(0, (System.Array)resultPixels); resultRasterEdit.Write(resultRasterCursor.TopLeft, (IPixelBlock)resultPixelBlock); resultRasterEdit.Refresh(); } while (resultRasterCursor.Next() == true && rasterCursor.Next() == true);//遍历完一块像素块之后遍历下一块,直到栅格遍历结束。 //将结果栅格存入到成员变量m_raster中 m_raster = resultRaster; //我在这里无法删除这个文件怎么办!!!!!!!!! //System.IO.File.Delete("F:/RDB/NDVI.tif"); }
public void ChangeRasterValue(IRasterDataset2 pRasterDatset, double dbScale, double dbOffset) { try { IRaster2 pRaster2 = pRasterDatset.CreateFullRaster() as IRaster2; IPnt pPntBlock = new PntClass(); pPntBlock.X = 128; pPntBlock.Y = 128; IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock); IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; if (pRasterEdit.CanEdit()) { IRasterBandCollection pBands = pRasterDatset as IRasterBandCollection; IPixelBlock3 pPixelblock3 = null; int pBlockwidth = 0; int pBlockheight = 0; System.Array pixels; IPnt pPnt = null; object pValue; long pBandCount = pBands.Count; //获取Nodata IRasterProps pRasterPro = pRaster2 as IRasterProps; object pNodata = pRasterPro.NoDataValue; //double dbNoData = Convert.ToDouble(((double[])pNodata)[0]); double dbNoData = getNoDataValue(pNodata); do { pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3; pBlockwidth = pPixelblock3.Width; pBlockheight = pPixelblock3.Height; for (int k = 0; k < pBandCount; k++) { pixels = (System.Array)pPixelblock3.get_PixelData(k); for (int i = 0; i < pBlockwidth; i++) { for (int j = 0; j < pBlockheight; j++) { pValue = pixels.GetValue(i, j); double ob = Convert.ToDouble(pValue); if (ob != dbNoData) { ob *= dbScale; //翻转 ob += dbOffset; //Z方向偏移 } IRasterProps pRP = pRaster2 as IRasterProps; if (pRP.PixelType == rstPixelType.PT_CHAR) { pixels.SetValue(Convert.ToChar(ob), i, j); } else if (pRP.PixelType == rstPixelType.PT_UCHAR) { pixels.SetValue(Convert.ToByte(ob), i, j); } else if (pRP.PixelType == rstPixelType.PT_FLOAT) { pixels.SetValue(Convert.ToSingle(ob), i, j); } else if (pRP.PixelType == rstPixelType.PT_DOUBLE) { pixels.SetValue(Convert.ToDouble(ob), i, j); } else if (pRP.PixelType == rstPixelType.PT_ULONG) { pixels.SetValue(Convert.ToInt32(ob), i, j); } else { ; } } } pPixelblock3.set_PixelData(k, pixels); System.Array textPixel = null; textPixel = (System.Array)pPixelblock3.get_PixelData(k); } pPnt = pRasterCursor.TopLeft; pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3); }while (pRasterCursor.Next()); //改变了Z值,重新统计下直方图 //IRasterDataset2 prd = pRaster2 as IRasterDataset2; IRasterDatasetEdit3 pRedtit = pRasterDatset as IRasterDatasetEdit3; pRedtit.DeleteStats();//This method is avaliable only on raster datasets in File and ArcSDE geodatabases. pRedtit.ComputeStatisticsHistogram(1, 1, null, true); pRasterEdit.Refresh(); System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); } } catch (System.Exception ex) { } }
//IRasterStatistics rasterStatic; private void SetRasterSymbol(IRasterLayer rasterLayer) { //获取选择的序号 int index = sBC.SelectedIndex; ISymbologyStyleClass symbologyStyleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassColorRamps); IStyleGalleryItem mStyleGalleryItem = symbologyStyleClass.GetItem(index); //获取选择的符号 IColorRamp select = (IColorRamp)mStyleGalleryItem.Item; IRasterStretchColorRampRenderer rasterStretchColorRampRenderer = new RasterStretchColorRampRendererClass(); IRasterRenderer rasterRenderer = rasterStretchColorRampRenderer as IRasterRenderer; rasterRenderer.Raster = (rasterLayer).Raster; if (checkBox1.Checked == true) { //修改像元值 线性拉伸 IRaster2 pRaster2 = rasterLayer.Raster as IRaster2; IPnt pPntBlock = new PntClass(); pPntBlock.X = 128; pPntBlock.Y = 128; IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock); IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; if (pRasterEdit.CanEdit()) { // IRasterBandCollection pBands = rasterLayer as IRasterBandCollection; IPixelBlock3 pPixelblock3 = null; int pBlockwidth = 0; int pBlockheight = 0; System.Array pixels; IPnt pPnt = null; object pValue; // long pBandCount = pBands.Count; //获取Nodata //IRasterProps pRasterPro = pRaster2 as IRasterProps; //object pNodata = pRasterPro.NoDataValue; do { pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3; pBlockwidth = pPixelblock3.Width; pBlockheight = pPixelblock3.Height; // for (int k = 0; k < pBandCount; k++) //IRasterBandCollection bandCollection; //IRasterLayer irasterLayer = rasterLayer; //IRaster2 raster = rasterLayer.Raster as IRaster2; //IRasterDataset rd = raster.RasterDataset; //bandCollection = rd as IRasterBandCollection; //IEnumRasterBand enumband = bandCollection.Bands; //IRasterBand rasterBand = enumband.Next(); //rasterStatic = null; //if (rasterBand != null && rasterBand.Statistics != null) //{ // rasterStatic = rasterBand.Statistics; //} int pixelmax, pixelmin; { pixels = (System.Array)pPixelblock3.get_PixelData(0); pixelmax = Convert.ToInt32(pixels.GetValue(0, 0)); pixelmin = pixelmax; for (int i = 0; i < pBlockwidth; i++) { for (int j = 0; j < pBlockheight; j++) { pValue = pixels.GetValue(i, j); { // pixels.SetValue(Convert.ToByte(Convert.ToInt32(pValue) * strscale), i, j); if (Convert.ToInt32(pValue) > pixelmax) { pixelmax = Convert.ToInt32(pValue); } if (Convert.ToInt32(pValue) < pixelmin) { pixelmin = Convert.ToInt32(pValue); } } } } double strscale = ((double)pixelmax - (double)pixelmin) / 255.0; for (int i = 0; i < pBlockwidth; i++) { for (int j = 0; j < pBlockheight; j++) { pValue = pixels.GetValue(i, j); { pixels.SetValue(Convert.ToByte((Convert.ToInt32(pValue) - pixelmin) / (strscale)), i, j); } } } pPixelblock3.set_PixelData(0, pixels); } pPnt = pRasterCursor.TopLeft; pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3); }while (pRasterCursor.Next()); System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); // MessageBox.Show("done"); } } rasterRenderer.Update(); rasterStretchColorRampRenderer.ColorRamp = select; rasterRenderer.Update(); ((IRasterLayer)rasterLayer).Renderer = rasterRenderer; }
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) { double x = loc.X; double y = loc.Y; string outLocStr = x.ToString() + ":" + y.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 { 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 c = 0; c < width; c++) { int ic = c + 1; for (int r = 0; r < height; r++) { List <string> cr = new List <string>(); cr.Add(c.ToString() + ":" + r.ToString()); int ir = r + 1; int inVl = System.Convert.ToInt32(inArr.GetValue(ic, ir)); //Console.WriteLine("Invalue = " + inVl.ToString()); if ((inVl == noDataVl) || (inVl == (noDataVl - 1))) { Console.WriteLine("Invalue = " + inVl.ToString()); continue; } else { int outVl32 = System.Convert.ToInt32(outArr.GetValue(c, r)); if (outVl32 == noDataVl2) { rCnt = 0; rPerm = 0; 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); } } } IRow row = vatTable.CreateRow(); row.set_Value(valueIndex, counter); row.set_Value(countIndex, rCnt); row.set_Value(permIndex, rPerm); row.Store(); counter++; } else { } } } } pb2.set_SafeArray(0, (System.Array)outArr); regRsE.Write(loc, pb2); outArrDic.Remove(outLocStr); }
public bool SetRegionToNoDataValue() { try { if (m_pSrcRaster == null || m_pClipPolygon == null || double.IsNaN(m_dbNoDataValue)) { return(false); } IGeoDataset pSrcGeoDataset = m_pSrcRaster as IGeoDataset; IExtractionOp pRasterExtractionOp = new RasterExtractionOpClass(); IRasterProps pSrcRasterProps = m_pSrcRaster as IRasterProps; double dbCellSize = (pSrcRasterProps.MeanCellSize().X + pSrcRasterProps.MeanCellSize().Y) / 2; //设置范围和分辨率 IRasterAnalysisEnvironment pRasterAnalysisEnv = pRasterExtractionOp as IRasterAnalysisEnvironment; pRasterAnalysisEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSize); pRasterAnalysisEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, m_pClipPolygon.Envelope, Type.Missing); //pRasterAnalysisEnv.OutSpatialReference = (m_pSrcRaster as IRasterProps).SpatialReference; //保留区域外的值,区域内的设置为原始栅格的无效值 IGeoDataset pDstGeoDataset = pRasterExtractionOp.Rectangle(pSrcGeoDataset, m_pClipPolygon.Envelope, true); //逐点判断像素是否在区域内,在区域内则改变为设置值,否则不变 IRelationalOperator pRelationalOp = m_pClipPolygon as IRelationalOperator; if (pDstGeoDataset is IRaster) { //得到原始栅格的对象,用于修改 IRaster2 pSrcRaster2 = m_pSrcRaster as IRaster2; IRasterDataset2 pSrcRasterDataset2 = pSrcRaster2.RasterDataset as IRasterDataset2; IRaster pTmpRaster = pSrcRasterDataset2.CreateFullRaster(); IRasterEdit pSrcEdit = pTmpRaster as IRasterEdit; //得到图层NoDataValue IRasterProps rasterProps = pSrcRaster2 as IRasterProps; double noData = ClsGDBDataCommon.getNoDataValue(rasterProps.NoDataValue); //得到输出的栅格 IRaster2 pDstRaster2 = pDstGeoDataset as IRaster2; IRasterProps pDstRasterProps = pDstRaster2 as IRasterProps; IRasterCursor pDstRasterCursor = pDstRaster2.CreateCursorEx(null); //pDstRasterCursor.Reset(); do { //得到当前处理的块 IPixelBlock3 pixelBlock3 = pDstRasterCursor.PixelBlock as IPixelBlock3; int nWidth = pixelBlock3.Width; int nHeight = pixelBlock3.Height; IPnt ptLeftTop = pDstRasterCursor.TopLeft; //block值转数组时,NoData转换时有时为NoData,有时为栅格中的最小值 System.Array array = pixelBlock3.get_PixelData(0) as System.Array; //逐点判断: 判断像素是否在区域内,在区域内则改变为设置值,否则不变 for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { double dbX = double.NaN, dbY = double.NaN; //得到当前像素点的地图坐标 int nCurrentX = Convert.ToInt32(ptLeftTop.X + i); int nCurrentY = Convert.ToInt32(ptLeftTop.Y + j); pDstRaster2.PixelToMap(nCurrentX, nCurrentY, out dbX, out dbY); IPoint ptInMap = new PointClass(); ptInMap.X = dbX; ptInMap.Y = dbY; //判断是否在区域内 bool bFlag = pRelationalOp.Contains(ptInMap as IGeometry); if (bFlag) //在当前区域内 { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { double v = Convert.ToDouble(array.GetValue(i, j)); if (v == 0 || v < -3.4e15 || v > 3.4e15) //if (v == 0 || Math.Abs(v -noData) <1e18) { int col, row; pSrcRaster2.MapToPixel(dbX, dbY, out col, out row); //表示getpixelvalue为null表示nodata object obj = pSrcRaster2.GetPixelValue(0, col, row); if (obj == null) { object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue); array.SetValue(oValidValue, i, j); } else { array.SetValue(obj, i, j); } } } } } pixelBlock3.set_PixelData(0, array); //得到当前区域块在原图中的左上角像素坐标, 直接修改原栅格的数据 int nPixelLeftX = -1, nPixelLeftY = -1; double dbMapLeftTopX = double.NaN, dbMapLeftTopY = double.NaN; pDstRaster2.PixelToMap(Convert.ToInt32(ptLeftTop.X), Convert.ToInt32(ptLeftTop.Y), out dbMapLeftTopX, out dbMapLeftTopY); //得到当前块左上角的地理坐标 pSrcRaster2.MapToPixel(dbMapLeftTopX, dbMapLeftTopY, out nPixelLeftX, out nPixelLeftY); IPnt ptPixelLeftTop = new PntClass(); ptPixelLeftTop.SetCoords(nPixelLeftX, nPixelLeftY); if (pSrcEdit.CanEdit()) { pSrcEdit.Write(ptPixelLeftTop, pixelBlock3 as IPixelBlock); //pSrcEdit.Refresh(); } else { return(false); } } while (pDstRasterCursor.Next() == true); //更新 pSrcEdit.Refresh(); } else { return(false); } return(true); } catch (System.Exception ex) { return(false); } }
private void btn_2e_Click(object sender, EventArgs e) { ILayer pLayer = new FeatureLayerClass(); IFeatureClass featureClass = GetFeatureClass(@"D:\a_gis工程设计实践课\china\墓穴地shp\grave.shp"); IGeoDataset geo = featureClass as IGeoDataset; object extend = geo.Extent; object o = null; IFeatureClassDescriptor feades = new FeatureClassDescriptorClass(); feades.Create(featureClass, null, "area"); IRasterRadius rasterrad = new RasterRadiusClass(); rasterrad.SetVariable(12, ref o); object dCell = 0.014800000;//可以根据不同的点图层进行设置 IInterpolationOp interpla = new RasterInterpolationOpClass(); IRasterAnalysisEnvironment rasanaenv = interpla as IRasterAnalysisEnvironment; rasanaenv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell); rasanaenv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o); IGeoDataset g_GeoDS_Raster = interpla.IDW((IGeoDataset)feades, 2, rasterrad, ref o); IRaster pOutRsater = (IRaster)g_GeoDS_Raster; IRasterLayer pOutRasterlayer = new RasterLayerClass(); pOutRasterlayer.CreateFromRaster(pOutRsater); pOutRasterlayer.Name = "两个因素都考虑"; //IRaster raster = pOutRasterlayer.Raster; IRaster2 raster2 = (IRaster2)pOutRsater; // 指定像素块大小 IPnt pntBlock = new PntClass(); pntBlock.X = 1280; pntBlock.Y = 1280; //创建一个光标以给定像素块大小 //定义RasterCursor初始化,参数设为null,内部自动设置PixelBlock大小 //IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(null); IRasterCursor rasterCursor = raster2.CreateCursorEx(null); //控制像素块级别的编辑操作 IRasterEdit rasterEdit = raster2 as IRasterEdit; if (rasterEdit.CanEdit()) { //得到一段光栅带 IRasterBandCollection bandCollection = (IRasterBandCollection)pOutRsater; System.Array pixels; IPnt pnt = null; object value; int bandCount = bandCollection.Count; //创建像素块 IPixelBlock3 pixelBlock3 = null; int blockWidth = 0; int blockHeight = 0; double temp = 0; do { pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; blockWidth = pixelBlock3.Width; blockHeight = pixelBlock3.Height; for (int k = 0; k < bandCount; k++) { //指定平面的像素的数组 pixels = (System.Array)pixelBlock3.get_PixelData(k); for (int i = 0; i < blockWidth; i++) { for (int j = 0; j < blockHeight; j++) { //value = pixels.GetValue(i, j); ////if (Convert.ToInt32(value) == 0) //{ //设置像素的颜色值 temp = PixelValue1[i, j] + PixelValue2[i, j]; pixels.SetValue((int)temp, i, j); //} } } pixelBlock3.set_PixelData(k, pixels); } pnt = rasterCursor.TopLeft; rasterEdit.Write(pnt, (IPixelBlock)pixelBlock3); }while (rasterCursor.Next()); System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit); //渲染 IRasterClassifyColorRampRenderer pRClassRend = new RasterClassifyColorRampRendererClass(); IRasterRenderer pRRend = pRClassRend as IRasterRenderer; IRaster pRaster = pOutRasterlayer.Raster; IRasterBandCollection pRBandCol = pRaster as IRasterBandCollection; IRasterBand pRBand = pRBandCol.Item(0); if (pRBand.Histogram == null) { pRBand.ComputeStatsAndHist(); } pRRend.Raster = pRaster; pRClassRend.ClassCount = 10; pRRend.Update(); IRgbColor pFromColor = new RgbColorClass(); pFromColor.Red = 135;//天蓝色 pFromColor.Green = 206; pFromColor.Blue = 235; IRgbColor pToColor = new RgbColorClass(); pToColor.Red = 124;//草坪绿 pToColor.Green = 252; pToColor.Blue = 0; IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass(); colorRamp.Size = 10; colorRamp.FromColor = pFromColor; colorRamp.ToColor = pToColor; bool createColorRamp; colorRamp.CreateRamp(out createColorRamp); IFillSymbol fillSymbol = new SimpleFillSymbolClass(); for (int i = 0; i < pRClassRend.ClassCount; i++) { fillSymbol.Color = colorRamp.get_Color(i); pRClassRend.set_Symbol(i, fillSymbol as ISymbol); pRClassRend.set_Label(i, pRClassRend.get_Break(i).ToString("0.00")); } pOutRasterlayer.Renderer = pRRend; this.axMapControl1.AddLayer(pOutRasterlayer); } }
public void underInit() { IRaster2 raster2 = m_raster as IRaster2; IRasterDataset rstDataset = raster2.RasterDataset; IRasterBandCollection rstBandColl = rstDataset as IRasterBandCollection; if (rstBandColl.Count > 1) { MessageBox.Show("暂不支持多波段的滤波计算", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IRasterProps pRasterProps = raster2 as IRasterProps; int Height = pRasterProps.Height; int Width = pRasterProps.Width; double cellsizex = pRasterProps.MeanCellSize().X; double cellsizey = pRasterProps.MeanCellSize().Y; rstPixelType pixelType = pRasterProps.PixelType; ISpatialReference spatialReference = pRasterProps.SpatialReference; //MessageBox.Show(spatialReference.Name.ToString()); IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass(); IWorkspace pWs = pRasterWsFac.OpenFromFile(@"D://RDB", 0); IRasterWorkspace2 pRasterWs; pRasterWs = pWs as IRasterWorkspace2; IPoint origin = new PointClass(); origin.PutCoords(pRasterProps.Extent.XMin, pRasterProps.Extent.YMin); //RasterWorkspace rasterWorkspace = (RasterWorkspace)workspace; ISpatialReference sr = new UnknownCoordinateSystemClass(); IRasterDataset2 resultDataset = pRasterWs.CreateRasterDataset("raster" + "_" + cmb_FliterMethod.SelectedItem.ToString() + ".tif", "TIFF", origin, Width, Height, cellsizex, cellsizey, 1, rstPixelType.PT_DOUBLE, sr) as IRasterDataset2; IRaster resultRaster = resultDataset.CreateFullRaster(); IRasterCursor resultRasterCursor = ((IRaster2)resultRaster).CreateCursorEx(null); IRasterDataset2 rasterDataset = raster2.RasterDataset as IRasterDataset2; IRaster2 raster = rasterDataset.CreateFullRaster() as IRaster2; IRasterCursor rasterCursor = raster.CreateCursorEx(null); IPixelBlock3 resultPixelBlock = null; IPixelBlock3 tempPixelBlock = null; IRasterEdit resultRasterEdit = resultRaster as IRasterEdit; long blockWidth = 0; long blockHeight = 0; // System.Array pixels; double[,] kernal = new double[3, 3] { { 0, 0, 0 }, { 0, 1, 0 }, { 0, 0, 0 } }; switch (cmb_FliterMethod.SelectedItem.ToString()) { case "LineDetectionHorizontal": kernal = new double[3, 3] { { -1, -1, -1 }, { 2, 2, 2 }, { -1, -1, -1 } }; break; case "LineDetectionVertical": kernal = new double[3, 3] { { -1, 2, -1 }, { -1, 2, -1 }, { -1, 2, -1 } }; break; case "Laplacian3x3": kernal = new double[3, 3] { { 0, -1, 0 }, { -1, 4, -1 }, { 0, -1, 0 } }; break; case "Smoothing3x3": kernal = new double[3, 3] { { 1, 2, 1 }, { 2, 4, 2 }, { 1, 2, 1 } }; break; case "Sharpening3x3": kernal = new double[3, 3] { { -1, -1, -1 }, { -1, 9, -1 }, { -1, -1, -1 } }; break; } do { resultPixelBlock = resultRasterCursor.PixelBlock as IPixelBlock3; tempPixelBlock = rasterCursor.PixelBlock as IPixelBlock3; System.Array pixels = (System.Array)tempPixelBlock.get_PixelData(0); //MessageBox.Show(pixels3.GetValue(0, 0).GetType().ToString()); blockHeight = resultPixelBlock.Height; blockWidth = resultPixelBlock.Width; System.Array resultPixels = (System.Array)resultPixelBlock.get_PixelData(0); //MessageBox.Show(resultPixels.GetValue(0, 0).GetType().ToString()); for (int i = 0; i < blockHeight; i++) { for (int j = 0; j < blockWidth; j++) { double sum = 0; for (int ki = -1; ki <= 1; ki++) { for (int kj = -1; kj <= 1; kj++) { long idxi = (i + ki) < 0 ? 0 : i + ki >= blockHeight ? blockHeight - 1 : (i + ki); long idxj = (j + kj) < 0 ? 0 : j + kj >= blockWidth ? blockWidth - 1 : (j + kj); double raw = double.Parse(pixels.GetValue(idxj, idxi).ToString()); sum += raw * kernal[ki + 1, kj + 1]; } } resultPixels.SetValue(sum, j, i); } } resultPixelBlock.set_PixelData(0, (System.Array)resultPixels); resultRasterEdit.Write(resultRasterCursor.TopLeft, (IPixelBlock)resultPixelBlock); resultRasterEdit.Refresh(); } while (resultRasterCursor.Next() == true && rasterCursor.Next() == true); IRasterDataset pRasterDs = pRasterWs.OpenRasterDataset("raster" + "_" + cmb_FliterMethod.SelectedItem.ToString() + ".tif"); IRaster praster = ((IRasterDataset2)pRasterDs).CreateFullRaster(); //IRasterLayer resLayer = new RasterLayerClass(); //resLayer.CreateFromRaster(praster); m_raster = praster; }
// 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); } }
//分析的主要实现函数 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 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); }