/// <summary> /// Save the edition as a specified file. /// </summary> /// <param name="fileName">New file path of raster layer to be saved.</param> /// <param name="activeLayer">Raster layer to be saved.</param> /// <param name="edits">Pixel collection that contains edited pixels.</param> public static void SaveEditsAs(string fileName, IRasterLayer activeLayer, PixelCollection edits) { if (activeLayer == null || edits.Count == 0) { return; } //Random rnd = new Random(); //string tempFile = rnd.Next().ToString(); ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.EngineOrDesktop); // Get the original file // IRasterLayer rasterLayer = activeLayer; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); //IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(rasterLayer.FilePath), 0); //IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(rasterLayer.FilePath)); // Open the new file save location IWorkspace mWorkspace = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(fileName), 0); // Save the original file to a new file ISaveAs saveAs = (ISaveAs)activeLayer.Raster; IRasterDataset2 mRasterDataset = (IRasterDataset2)saveAs.SaveAs(System.IO.Path.GetFileName(fileName), mWorkspace, Raster.GetFormat(System.IO.Path.GetExtension(fileName))); IRaster mRaster = mRasterDataset.CreateFullRaster(); // Save edits to file Raster.WriteEdits(mRaster, edits); System.Runtime.InteropServices.Marshal.ReleaseComObject(mRaster); }
//执行栅格函数 public void Init() { try { //创建NDVI栅格函数参数对象 INDVIFunctionArguments ndviFunctionArguments = (INDVIFunctionArguments) new NDVIFunctionArguments(); //设置近红外波段信息 ndviFunctionArguments.InfraredBandID = InfraredBandID; //设置红波段信息 ndviFunctionArguments.VisibleBandID = VisibleBandID; //设置要处理的栅格 ndviFunctionArguments.Raster = m_raster; //创建栅格函数 IRasterFunction rasterFunction = new NDVIFunction(); //创建栅格函数数据集对象 IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); //设置栅格函数数据集名称对象,设置其临时文件存储地点 IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName) new FunctionRasterDatasetNameClass(); functionRasterDatasetName.FullName = @"D:\RDB"; functionRasterDataset.FullName = (IName)functionRasterDatasetName; //执行栅格函数 functionRasterDataset.Init(rasterFunction, ndviFunctionArguments); //将执行结果存入成员变量中 IRasterDataset2 rstDatasetr2 = (IRasterDataset2)functionRasterDataset; m_raster = rstDatasetr2.CreateFullRaster(); } catch (System.Exception ex)//异常处理,输出错误信息 { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private void btnOK_Click(object sender, EventArgs e) { try { if (this.CanDo()) { RasterUtil rasterUtil = new RasterUtil(); if (!(this.m_pOutName is IRasterCatalogName)) { IRasterWorkspaceEx rasterWorkspaceEx = this.m_pOutName.Open() as IRasterWorkspaceEx; for (int i = 0; i < this.m_pInNames.Count; i++) { IRasterDataset2 rasterDataset2 = (this.m_pInNames[i] as IName).Open() as IRasterDataset2; string fileNameWithoutExtension = Path.GetFileNameWithoutExtension((rasterDataset2 as IDataset).Name); if ((fileNameWithoutExtension[0] < '0' ? false : fileNameWithoutExtension[0] <= '9')) { fileNameWithoutExtension = string.Concat("A", fileNameWithoutExtension); } if (rasterWorkspaceEx is IWorkspace2) { int num = 1; string str = fileNameWithoutExtension; try { while ( (rasterWorkspaceEx as IWorkspace2).NameExists[ esriDatasetType.esriDTFeatureClass, str]) { str = string.Concat(fileNameWithoutExtension, "_", num.ToString()); num++; } } catch { } fileNameWithoutExtension = str; } ((IGeometryDefEdit)(new GeometryDef())).SpatialReference_2 = (rasterDataset2 as IGeoDataset).SpatialReference; rasterWorkspaceEx.SaveAsRasterDataset(fileNameWithoutExtension, rasterDataset2.CreateFullRaster(), null, "", null, null); } } else { IFeatureClass featureClass = this.m_pOutName.Open() as IFeatureClass; rasterUtil.ToRasterCatalog(this.m_pInNames, featureClass); } } } catch (Exception exception1) { Exception exception = exception1; CErrorLog.writeErrorLog(this, exception, ""); MessageBox.Show(exception.Message); } this.progressBar1.Visible = false; }
public ndviFunction(IRaster raster, XmlNode in_xmlNode) { try { InitializeComponent(); IRaster2 raster2 = raster as IRaster2; IRasterDataset2 rasterDataset = raster2.RasterDataset as IRasterDataset2; m_raster = rasterDataset.CreateFullRaster(); m_xmlNode = in_xmlNode; //处理xml,获取其中装载的近红外波段和红波段数据 XmlNodeList childlist = m_xmlNode.ChildNodes; foreach (XmlNode node in childlist) { if (node is XmlComment)//如果是评论,则跳过 { continue; } XmlElement element = node as XmlElement; if (element.Name == "InfraredBandID") { InfraredBandID = int.Parse(element.InnerText); } if (element.Name == "VisibleBandID") { VisibleBandID = int.Parse(element.InnerText); } } //获取栅格波段信息,将其添加到下拉框中 IRasterBandCollection rstBandColl = m_raster as IRasterBandCollection; for (int i = 0; i < rstBandColl.Count; i++) { cmb_infraredBandindex.Items.Add(i + 1); cmb_redBandindex.Items.Add(i + 1); } //如果输入的参数波段数大于栅格本身的波段数,则弹出警告,并重置选择波段为第一波段 if (InfraredBandID > rstBandColl.Count || VisibleBandID > rstBandColl.Count) { MessageBox.Show("波段数与输入数不匹配!" + "\n" + "请重新选择!"); cmb_infraredBandindex.SelectedIndex = 0; cmb_redBandindex.SelectedIndex = 0; } else { //否则,则将输入的参数作为下拉框的默认选项 cmb_infraredBandindex.SelectedIndex = InfraredBandID; cmb_redBandindex.SelectedIndex = VisibleBandID; } } catch (Exception e) { MessageBox.Show(e.Message); } }
/// <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 void Init() { try { //创建Stretch栅格函数参数对象 IStretchFunctionArguments stretchFunctionArguments = (IStretchFunctionArguments) new StretchFunctionArguments(); //设置要处理的栅格 stretchFunctionArguments.Raster = m_raster; //设置拉伸类型 stretchFunctionArguments.StretchType = (esriRasterStretchType)StretchType; if (cmb_StretchType.SelectedItem.ToString() == "StandardDeviation")//如果是按标准差拉伸,需要设置参数N { //设置参数N stretchFunctionArguments.NumberOfStandardDeviations = NumberOfStandardDeviations; } else if (cmb_StretchType.SelectedItem.ToString() == "PercentMinimumMaximum")//如果是按最大最小百分比拉伸,需要设置最大最小百分比 { //设置最大最小百分比 stretchFunctionArguments.MinPercent = MinPercent; stretchFunctionArguments.MaxPercent = MaxPercent; } //创建栅格函数 IRasterFunction rasterFunction = new StretchFunction(); //创建栅格函数数据集对象 IFunctionRasterDataset functionRasterDataset = new FunctionRasterDataset(); //设置栅格函数数据集名称对象,设置其临时文件存储地点 IFunctionRasterDatasetName functionRasterDatasetName = (IFunctionRasterDatasetName) new FunctionRasterDatasetNameClass(); functionRasterDatasetName.FullName = @"D:\RDB"; functionRasterDataset.FullName = (IName)functionRasterDatasetName; //执行栅格函数 functionRasterDataset.Init(rasterFunction, stretchFunctionArguments); //将执行结果存入成员变量中 IRasterDataset2 rstDatasetr2 = (IRasterDataset2)functionRasterDataset; m_raster = rstDatasetr2.CreateFullRaster(); } catch (System.Exception ex)//异常处理,输出错误信息 { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { // TODO: Add CmdRasterTransZ.OnClick implementation IMapControl3 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl3; if (pMapCtr != null) { FrmRasterTransZ m_frmRasterTranZ = new FrmRasterTransZ(); if (m_frmRasterTranZ.ShowDialog() == DialogResult.OK) { if (m_frmRasterTranZ.istrue == true) { ClsRasterOp pRasterOp = new ClsRasterOp(); IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; IRasterDataset2 pRasterDataset = pRaster2.RasterDataset as IRasterDataset2; pRasterOp.ChangeRasterValue(pRasterDataset, m_frmRasterTranZ.a, m_frmRasterTranZ.b); //此处要判断图层是否存在金字塔,如果存在则需要重新创建 IRasterPyramid3 pDstRasterPyramid3 = pRasterDataset as IRasterPyramid3; if (pDstRasterPyramid3.Present) { IDataLayer2 pDataLayer = pRasterLayer as IDataLayer2; pDataLayer.Disconnect(); pDstRasterPyramid3.DeletePyramid(); pDstRasterPyramid3.Create(); pRasterLayer.CreateFromDataset(pRasterDataset); } //更新图层渲染方式 ChangeStrechRender(pRasterLayer); pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null); if (m_axTocControl != null) { m_axTocControl.SetBuddyControl(pMapCtr); m_axTocControl.Update(); m_axTocControl.ActiveView.Refresh(); } } } } }
/// <summary> /// 读取指定块处的像元值到数组. /// </summary> /// <param name="pRasterDS">The p raster ds.</param> /// <param name="pBlockSize0">左上角点.</param> /// <param name="pBlockSize1">块大小.</param> /// <returns>System.Single[].</returns> public static float[,] ReadFloat(IRasterDataset2 pRasterDS, IPnt pBlockSize0, IPnt pBlockSize1) { try { //IRaster pRaster = thisRasterLayer.Raster; IRaster pRaster = pRasterDS.CreateFullRaster(); IRaster2 pRaster2 = (IRaster2)pRaster; IRasterProps pRSp = (IRasterProps)pRaster; IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize1).PixelBlock; pRaster.Read(pBlockSize0, pixelBlock); IPixelBlock3 block2 = (IPixelBlock3)pixelBlock; return((float[, ])block2.get_PixelData(0)); } catch (Exception ex) { XtraMessageBox.Show("读取影像失败!\n" + ex.Message); return(null); } }
public static void ReplacePixel(IRasterDataset2 irasterDataset2_0) { IRaster2 raster2 = irasterDataset2_0.CreateFullRaster() as IRaster2; IPnt pntClass = new Pnt() { X = 128, Y = 128 }; raster2.CreateCursorEx(pntClass); IRasterEdit rasterEdit = raster2 as IRasterEdit; if (rasterEdit.CanEdit()) { long count = (long)(irasterDataset2_0 as IRasterBandCollection).Count; IRasterProps rasterProp = raster2 as IRasterProps; object noDataValue = rasterProp.NoDataValue; rasterProp.NoDataValue = 255; (rasterProp as ISaveAs).SaveAs("j:\\image1.tif", null, "TIFF"); Marshal.ReleaseComObject(rasterEdit); } }
/// <summary> /// Save modification to the original file. /// </summary> public static void SaveEdits() { if (ActiveLayer == null || Edits.Count == 0) { return; } ESRI.ArcGIS.RuntimeManager.BindLicense(ESRI.ArcGIS.ProductCode.EngineOrDesktop); // Get the original file IRasterLayer rasterLayer = (IRasterLayer)Editor.ActiveLayer; IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(rasterLayer.FilePath), 0); IRasterDataset2 mRasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(rasterLayer.FilePath)); IRaster mRaster = mRasterDataset.CreateFullRaster(); Editor.WriteEdits(mRaster); System.Runtime.InteropServices.Marshal.ReleaseComObject(mRaster); ArcMap.Document.ActiveView.Refresh(); }
/// <summary> /// 一次读取整幅影像像元值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pRasterDS">The p raster ds.</param> /// <returns>T[].</returns> public static T[,] ReadPixelValue <T>(IRasterDataset2 pRasterDS) { try { //IRaster pRaster = thisRasterLayer.Raster; IRaster pRaster = pRasterDS.CreateFullRaster(); IRaster2 pRaster2 = (IRaster2)pRaster; IRasterProps pRSp = (IRasterProps)pRaster; IPnt pBlockSize = new PntClass(); pBlockSize.SetCoords((float)pRSp.Width, (float)pRSp.Height); IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize).PixelBlock; pBlockSize.SetCoords(0.0, 0.0); pRaster.Read(pBlockSize, pixelBlock); IPixelBlock3 block2 = (IPixelBlock3)pixelBlock; return((T[, ])block2.get_PixelData(0));; } catch (Exception ex) { XtraMessageBox.Show("读取分类影像失败!\n" + ex.Message); return(null); } }
//函数编号:Raster-07 //函数名:MosaicRasterToGDBRaster //函数功能:Raster文件Mosaic到SDE Raster文件中 //参数: public void MosaicRasterToGDBRaster(IRasterDataset pRasterFile, IRasterDatasetEdit pGDBRasterDs) { try { IRaster pRaster; IRasterDataset2 pRasterDs = pRasterFile as IRasterDataset2; //IDataset pDs; pRaster = pRasterDs.CreateFullRaster(); //CreateFullRaster()方法只有IRasterDataset2有 pGDBRasterDs.Mosaic(pRaster, 0.5); //no resample pRasterDs = null; pRaster = null; //pDs = null; } catch (Exception e) { if (e is StackOverflowException || e is OutOfMemoryException) { throw; } } }
public ESRI.ArcGIS.Carto.IRasterRenderer Pick(ESRI.ArcGIS.esriSystem.IArray pRenderers, ESRI.ArcGIS.Geodatabase.IRasterDataset pRasterDataset) { IRasterRenderer rasterRenderer = null; IRasterRGBRenderer rasterRGBRenderer = null; IRasterStretchColorRampRenderer rasterStretchColorRampRenderer = null; // Get the renderers int Count = pRenderers.Count; int i = 0; for (i = 0; i < Count; i++) { rasterRenderer = (IRasterRenderer)(pRenderers.get_Element(i)); if (rasterRenderer is IRasterStretchColorRampRenderer) { rasterStretchColorRampRenderer = (IRasterStretchColorRampRenderer)rasterRenderer; } else if (rasterRenderer is IRasterRGBRenderer) { rasterRGBRenderer = (IRasterRGBRenderer)rasterRenderer; } } IRasterDataset2 rasterDataset2 = (IRasterDataset2)pRasterDataset; IRasterBandCollection rasterBandCollection = (IRasterBandCollection)rasterDataset2; if (rasterBandCollection.Count > 5) { // Use band 4,5 and 3 as red, green and blue rasterRenderer = (IRasterRenderer)rasterRGBRenderer; rasterRGBRenderer.SetBandIndices(3, 4, 2); return((IRasterRenderer)rasterRGBRenderer); } else // Special stretch { IRasterBand rasterBand = rasterBandCollection.Item(0); bool hasTable = false; rasterBand.HasTable(out hasTable); if (hasTable == false) { // Simply change the color ramp for the stretch renderer //IColor fromColor = new RgbColorClass(); //fromColor.RGB = Microsoft.VisualBasic.Information.RGB(255, 200, 50); IColor fromColor = CreateRGBColor(255, 200, 50) as IColor; //IColor toColor = new RgbColorClass(); //toColor.RGB = Microsoft.VisualBasic.Information.RGB(180, 125, 0); IColor toColor = CreateRGBColor(180, 125, 0) as IColor; // Create color ramp IAlgorithmicColorRamp algorithmicColorRamp = new AlgorithmicColorRampClass(); algorithmicColorRamp.Size = 255; algorithmicColorRamp.FromColor = fromColor; algorithmicColorRamp.ToColor = toColor; bool createRamp = false; algorithmicColorRamp.CreateRamp(out createRamp); if (createRamp == true) { rasterRenderer = (IRasterRenderer)rasterStretchColorRampRenderer; rasterStretchColorRampRenderer.BandIndex = 0; rasterStretchColorRampRenderer.ColorRamp = algorithmicColorRamp; return((IRasterRenderer)rasterStretchColorRampRenderer); } } } return(rasterRenderer); }
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); } }
//构造函数2,传入Raster和XMlNode,对类进行初始化 public stretchFunction(IRaster raster, XmlNode in_xmlNode) { InitializeComponent(); IRaster2 raster2 = raster as IRaster2; IRasterDataset2 rasterDataset = raster2.RasterDataset as IRasterDataset2; m_raster = rasterDataset.CreateFullRaster(); m_xmlNode = in_xmlNode; //处理xml,获取其中装载的拉伸类型,最大最小百分比以及标准差n值信息。 XmlNodeList childlist = m_xmlNode.ChildNodes; foreach (XmlNode node in childlist) { if (node is XmlComment) { continue; } XmlElement element = node as XmlElement; if (element.Name == "StretchType") { StretchType = int.Parse(element.InnerText); } if (element.Name == "MaxPercent") { MaxPercent = double.Parse(element.InnerText); } if (element.Name == "MinPercent") { MinPercent = double.Parse(element.InnerText); } if (element.Name == "NumberOfStandardDeviations") { NumberOfStandardDeviations = double.Parse(element.InnerText); } } //加入可选拉伸类型 cmb_StretchType.Items.Add("None"); cmb_StretchType.Items.Add("StandardDeviation"); cmb_StretchType.Items.Add("HistogramEqualization"); cmb_StretchType.Items.Add("MinimumMaximum"); cmb_StretchType.Items.Add("PercentMinimumMaximum"); cmb_StretchType.Items.Add("Gaussian"); cmb_StretchType.Items.Add("HistogramSpecification"); //由于在StretchFunction参数设置中,拉伸类型并非按顺序123排列,需要进行特殊处理。 if (StretchType == 0) { cmb_StretchType.SelectedIndex = StretchType; } else { cmb_StretchType.SelectedIndex = StretchType - 2; } stxb_max.Visible = false; stxb_min.Visible = false; txb_max.Visible = false; txb_min.Visible = false; stxb_num.Visible = false; txb_NumberOfStandardDeviations.Visible = false; //如果选择的是按标准差拉伸,则将标准差拉伸相关组件显示 if (cmb_StretchType.SelectedItem.ToString() == "StandardDeviation") { stxb_num.Visible = true; txb_NumberOfStandardDeviations.Visible = true; } else if (cmb_StretchType.SelectedItem.ToString() == "PercentMinimumMaximum") { //如果选择的是按最大最小百分比拉伸,则将最大最小百分比拉伸相关组件显示 stxb_max.Visible = true; stxb_min.Visible = true; txb_max.Visible = true; txb_min.Visible = true; } txb_NumberOfStandardDeviations.Text = NumberOfStandardDeviations.ToString(); txb_max.Text = MaxPercent.ToString(); txb_min.Text = MinPercent.ToString(); }
private void btnUpdate_Click(object sender, EventArgs e) { //Class Setting int intClsCnt = lstClasses.CheckedItems.Count; string[] arrClsNMs = new string[intClsCnt]; for (int i = 0; i < intClsCnt; i++) { arrClsNMs[i] = lstClasses.CheckedItems[i].ToString(); } int[,] arrClsColor = new int[4, intClsCnt]; IRaster2 pClsRaster = (IRaster2)m_pClsRstLayer.Raster; IRasterBandCollection pClsBands = pClsRaster.RasterDataset as IRasterBandCollection; IRasterBand pClsBand = pClsBands.Item(0); ITable pClsTable = pClsBand.AttributeTable; ICursor pCursor = pClsTable.Search(null, false); IRow pRow = pCursor.NextRow(); string strRed = "Red", strGreen = "Green", strBlue = "Blue", strValue = "Value", strNameFld = "Class_name"; int intRedIdx = pClsTable.FindField(strRed); int intGreenIdx = pClsTable.FindField(strGreen); int intBlueIdx = pClsTable.FindField(strBlue); int intValueIdx = pClsTable.FindField(strValue); int intNameIdx = pClsTable.FindField(strNameFld); while (pRow != null) { for (int i = 0; i < intClsCnt; i++) { string strClassName = pRow.get_Value(intNameIdx).ToString(); if (arrClsNMs[i] == strClassName) { arrClsColor[0, i] = Convert.ToInt32(pRow.get_Value(intValueIdx)); arrClsColor[1, i] = Convert.ToInt32(pRow.get_Value(intRedIdx)); arrClsColor[2, i] = Convert.ToInt32(pRow.get_Value(intGreenIdx)); arrClsColor[3, i] = Convert.ToInt32(pRow.get_Value(intBlueIdx)); } } pRow = pCursor.NextRow(); } // Get NoDataValues IRasterProps pClsrasterProps = (IRasterProps)pClsRaster; System.Array pClsNoData = (System.Array)pClsrasterProps.NoDataValue; IPnt blocksize = new PntClass(); blocksize.SetCoords(pClsrasterProps.Width, pClsrasterProps.Height); // Create a raster cursor with a system-optimized pixel block size by passing a null. IRasterCursor pClsRstCursor = pClsRaster.CreateCursorEx(blocksize); IPixelBlock3 pClspBlock3 = (IPixelBlock3)pClsRstCursor.PixelBlock; System.Array pClspixels = (System.Array)pClspBlock3.get_PixelData(0); //Layer Setting int intLyrCnt = lstLayers.CheckedItems.Count; int[] arrLyrIdx = new int[intLyrCnt]; for (int i = 0; i < intLyrCnt; i++) { arrLyrIdx[i] = lstLayers.CheckedIndices[i]; } string strOriRSTpath = m_pOriRstLayer.FilePath; string strExtentFileSource = System.IO.Path.GetDirectoryName(strOriRSTpath); string strExtentFileName = System.IO.Path.GetFileName(strOriRSTpath); IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace) workspaceFactory.OpenFromFile(strExtentFileSource, 0); //Open a file raster dataset. IRasterDataset2 rasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(strExtentFileName); IRaster2 pOriRaster2 = (IRaster2)rasterDataset.CreateFullRaster(); //IRaster2 pOriRaster2 = (IRaster2)m_pOriRstLayer.Raster; //Create a raster cursor with a system-optimized pixel block size by passing a null. // Get NoDataValues m_pRasterProps = (IRasterProps)pOriRaster2; System.Array pOriNoData = (System.Array)m_pRasterProps.NoDataValue; IPnt Oriblocksize = new PntClass(); Oriblocksize.SetCoords(m_pRasterProps.Width, m_pRasterProps.Height); // Create a raster cursor with a system-optimized pixel block size by passing a null. IRasterCursor pOriRstCursor = pOriRaster2.CreateCursorEx(Oriblocksize); //IRasterCursor pOriRstCursor = pOriRaster2.CreateCursorEx(null); IPixelBlock3 pixelblock3 = (IPixelBlock3)pOriRstCursor.PixelBlock; System.Array[] OriPixels = new Array[intLyrCnt]; //UInt16[][,] intArry = new UInt16[intLyrCnt][,]; for (int i = 0; i < intLyrCnt; i++) { //intArry[i] = (UInt16[,])pixelblock3.get_PixelData(arrLyrIdx[i]); OriPixels[i] = (System.Array)pixelblock3.get_PixelData(arrLyrIdx[i]); } //Compare the Arrays and Draw int intBlockwidth = m_pRasterProps.Width; int intBlockHeight = m_pRasterProps.Height; //List<int[]>[] lstDN = new List<int[]>[intClsCnt]; List <int>[][] lstDN = new List <int> [intLyrCnt][]; for (int j = 0; j < intLyrCnt; j++) { lstDN[j] = new List <int> [intClsCnt]; } for (int j = 0; j < intLyrCnt; j++) { for (int i = 0; i < intClsCnt; i++) { lstDN[j][i] = new List <int>(); } } List <int>[][] lstLyrIDs = new List <int> [intLyrCnt][]; for (int j = 0; j < intLyrCnt; j++) { lstLyrIDs[j] = new List <int> [intClsCnt]; } for (int j = 0; j < intLyrCnt; j++) { for (int i = 0; i < intClsCnt; i++) { lstLyrIDs[j][i] = new List <int>(); } } //Uncertainty Layer Settings System.Array[] ProbPixels = null; int intProLyrCnt = 0; List <int>[][] lstProb = null; List <int>[][] lstProbIDs = null; string strProbRst = cboProbImage.Text; if (strProbRst != "" && chkAddProb.Checked) { IRasterLayer pProbRstLyr = GetRasterLayer(strProbRst, m_pActiveView); string strProbRSTpath = pProbRstLyr.FilePath; strExtentFileSource = System.IO.Path.GetDirectoryName(strProbRSTpath); strExtentFileName = System.IO.Path.GetFileName(strProbRSTpath); workspaceFactory = new RasterWorkspaceFactoryClass(); rasterWorkspace = (IRasterWorkspace) workspaceFactory.OpenFromFile(strExtentFileSource, 0); rasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(strExtentFileName); IRaster2 pProbRaster2 = (IRaster2)rasterDataset.CreateFullRaster(); // Get NoDataValues IRasterProps pProbrasterProps = (IRasterProps)pProbRaster2; System.Array pProbNoData = (System.Array)pProbrasterProps.NoDataValue; IRasterCursor pProbRstCursor = pProbRaster2.CreateCursorEx(Oriblocksize); // Using same block size IPixelBlock3 Probpixelblock3 = (IPixelBlock3)pProbRstCursor.PixelBlock; intProLyrCnt = Probpixelblock3.Planes; ProbPixels = new Array[intProLyrCnt]; for (int i = 0; i < intProLyrCnt; i++) { ProbPixels[i] = (System.Array)Probpixelblock3.get_PixelData(i); } lstProb = new List <int> [intProLyrCnt][]; for (int j = 0; j < intProLyrCnt; j++) { lstProb[j] = new List <int> [intClsCnt]; } for (int j = 0; j < intProLyrCnt; j++) { for (int i = 0; i < intClsCnt; i++) { lstProb[j][i] = new List <int>(); } } lstProbIDs = new List <int> [intProLyrCnt][]; for (int j = 0; j < intProLyrCnt; j++) { lstProbIDs[j] = new List <int> [intClsCnt]; } for (int j = 0; j < intProLyrCnt; j++) { for (int i = 0; i < intClsCnt; i++) { lstProbIDs[j][i] = new List <int>(); } } } //Store ID and Values for Brushing and Linking m_lstIDsValues = new List <int[]>(); int intID = 0; for (int colIndex = 0; colIndex < intBlockwidth; colIndex++) { for (int rowIndex = 0; rowIndex < intBlockHeight; rowIndex++) { int intClass = Convert.ToInt32(pClspixels.GetValue(colIndex, rowIndex)); int[] arrValues = new int[intLyrCnt + intProLyrCnt + 3]; if (intClass != Convert.ToInt32(pClsNoData.GetValue(0))) { //int[] arrValues = new int[intLyrCnt + intProLyrCnt + 3]; arrValues[0] = colIndex; arrValues[1] = rowIndex; arrValues[2] = intClass; for (int i = 0; i < intClsCnt; i++) { if (arrClsColor[0, i] == intClass) { //Get DNs for (int j = 0; j < intLyrCnt; j++) { if (colIndex == 0 && rowIndex == 241) { j = j; } int intValue = Convert.ToInt32(OriPixels[j].GetValue(colIndex, rowIndex)); lstDN[j][i].Add(intValue); lstLyrIDs[j][i].Add(intID); arrValues[j + 3] = intValue; } //Get Probs if (strProbRst != "" && chkAddProb.Checked) { for (int j = 0; j < intProLyrCnt; j++) { int intValue = Convert.ToInt32(Convert.ToInt32(ProbPixels[j].GetValue(colIndex, rowIndex)) * 2.55); lstProb[j][i].Add(intValue); lstProbIDs[j][i].Add(intID); arrValues[j + 3 + intLyrCnt] = intValue; } } } } } m_lstIDsValues.Add(arrValues); intID++; if (m_lstIDsValues.Count != intID) { MessageBox.Show("Diff"); //For deburgging } } } pChart.Series.Clear(); m_intColumnCnt = 0; if (strProbRst != "" && chkAddProb.Checked) { m_intColumnCnt = intLyrCnt + intProLyrCnt; } else { m_intColumnCnt = intLyrCnt; } m_lstPtsIdContainer = new List <List <int> >(); m_lstPtSeriesID = new List <int>(); for (int i = 0; i < intClsCnt; i++) { Color FillColor = Color.FromArgb(arrClsColor[1, i], arrClsColor[2, i], arrClsColor[3, i]); for (int j = 0; j < m_intColumnCnt; j++) { List <int> lstTarget; if (j < intLyrCnt) { lstTarget = lstDN[j][i]; } else { lstTarget = lstProb[j - intLyrCnt][i]; } List <int> lstIDs; if (j < intLyrCnt) { lstIDs = lstLyrIDs[j][i]; } else { lstIDs = lstProbIDs[j - intLyrCnt][i]; } List <int> sortedTarget = new List <int>(lstTarget); //to prevent overlapping of Boxplots double dblPlotHalfWidth = 0.05; double dblMin = (dblPlotHalfWidth * (intClsCnt - 1)) * (-1); double dblRefXvalue = j + (dblMin + (i * (dblPlotHalfWidth * 2))); //Find Max and Min double[] adblStats = BoxPlotStats(sortedTarget); bool blnDrawViolin = true; if (adblStats[0] == adblStats[4]) { blnDrawViolin = false; } //Restrict Plot min and max if (adblStats[0] < 0) { adblStats[0] = 0; } if (adblStats[4] > 255) { adblStats[4] = 255; } string strNumbering = i.ToString() + "_" + j.ToString(); double dblXmin = dblRefXvalue - (dblPlotHalfWidth / 2); double dblXmax = dblRefXvalue + (dblPlotHalfWidth / 2); if (blnDrawViolin) { //Draw Lines AddLineSeries(pChart, "m_" + strNumbering, Color.Red, 1, ChartDashStyle.Dash, dblRefXvalue - dblPlotHalfWidth, dblRefXvalue + dblPlotHalfWidth, adblStats[2], adblStats[2]); AddLineSeries(pChart, "v_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblRefXvalue, dblRefXvalue, adblStats[1], adblStats[3]); //AddLineSeries(pChart, "v2_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblRefXvalue, dblRefXvalue, adblStats[3], adblStats[4]); AddLineSeries(pChart, "h1_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adblStats[1], adblStats[1]); AddLineSeries(pChart, "h2_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adblStats[3], adblStats[3]); } else { //Draw Outliers var pMedPt = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "mpt_" + strNumbering, Color = Color.Red, BorderColor = FillColor, IsVisibleInLegend = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = MarkerStyle.Circle, MarkerSize = 2, }; pChart.Series.Add(pMedPt); pMedPt.Points.AddXY(dblRefXvalue, adblStats[2]); } if (blnDrawViolin) { //Draw Violin Plot var pviolin = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "vio1_" + strNumbering, Color = FillColor, BorderColor = FillColor, IsVisibleInLegend = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line }; pChart.Series.Add(pviolin); double[,] adblViolinStats = ViolinPlot(sortedTarget, 4); int intChartLenth = (adblViolinStats.Length) / 2; for (int k = 0; k < intChartLenth; k++) { if (adblViolinStats[k, 0] > adblStats[0] && adblViolinStats[k, 0] < adblStats[4]) { pviolin.Points.AddXY(dblRefXvalue - adblViolinStats[k, 1], adblViolinStats[k, 0]); } } pviolin.Points.AddXY(dblRefXvalue, adblStats[4]); for (int k = intChartLenth - 1; k >= 0; k--) { if (adblViolinStats[k, 0] > adblStats[0] && adblViolinStats[k, 0] < adblStats[4]) { pviolin.Points.AddXY(dblRefXvalue + adblViolinStats[k, 1], adblViolinStats[k, 0]); } } pviolin.Points.AddXY(dblRefXvalue, adblStats[0]); } //Draw Outliers var pOutlier = new System.Windows.Forms.DataVisualization.Charting.Series { Name = "out_" + strNumbering, Color = FillColor, BorderColor = FillColor, IsVisibleInLegend = false, ChartType = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point, MarkerStyle = MarkerStyle.Circle, MarkerSize = 1, }; pChart.Series.Add(pOutlier); m_lstPtSeriesID.Add(pChart.Series.Count - 1); //Add Series ID for brushing and linking List <int> lstPTsIds = new List <int>(); int intListCnt = lstTarget.Count; for (int k = 0; k < intListCnt; k++) { if (lstTarget[k] < adblStats[0] || lstTarget[k] > adblStats[4]) { pOutlier.Points.AddXY(dblRefXvalue, lstTarget[k]); lstPTsIds.Add(lstIDs[k]); //if (m_lstIDsValues[lstIDs[k]][3 + i] != lstTarget[k]) // MessageBox.Show("ddd"); } } m_lstPtsIdContainer.Add(lstPTsIds); } } m_intTotalNSeries = pChart.Series.Count; //Chart Setting pChart.ChartAreas[0].AxisY.Minimum = 0; pChart.ChartAreas[0].AxisY.Maximum = 255; pChart.ChartAreas[0].AxisY.IsLabelAutoFit = true; if (chkAddProb.Checked) { pChart.ChartAreas[0].AxisY.LabelStyle.Enabled = false; pChart.ChartAreas[0].AxisY.Title = "DN and Probability"; } else { pChart.ChartAreas[0].AxisY.Title = "DN"; } pChart.ChartAreas[0].AxisX.Maximum = m_intColumnCnt - 0.5; pChart.ChartAreas[0].AxisX.Minimum = -0.5; pChart.ChartAreas[0].AxisX.Title = "Layers"; pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false; pChart.ChartAreas[0].AxisX.CustomLabels.Clear(); for (int j = 0; j < m_intColumnCnt; j++) { System.Windows.Forms.DataVisualization.Charting.CustomLabel pcutsomLabel = new System.Windows.Forms.DataVisualization.Charting.CustomLabel(); pcutsomLabel.FromPosition = j - 0.5; pcutsomLabel.ToPosition = j + 0.5; if (j < intLyrCnt) { pcutsomLabel.Text = "DN of " + lstLayers.CheckedItems[j].ToString() + "(0-255)"; } else { pcutsomLabel.Text = "Prob " + lstClasses.Items[j - intLyrCnt].ToString() + "(0-100)"; } this.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel); } }
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; }
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) { } }
/// <summary> /// 获取文件大小 /// </summary> /// <param name="task"></param> /// <returns></returns> private int CalculateSize(TransferTask task) { if (task.Category == TaskCategory.Files) { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024)); } else if (task.Category == TaskCategory.Features) { DirectoryInfo dir = new DirectoryInfo(System.IO.Path.GetDirectoryName(task.SourceFileName)); string nickName = System.IO.Path.GetFileNameWithoutExtension(task.SourceFileName); FileInfo[] fs = dir.GetFiles(string.Format("*{0}*", nickName)); int length = 0; foreach (FileInfo f in fs) { length += (int)f.Length; } if (task.DestFileName.ToLower().Contains(".gdb")) { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { return(length / 1024 + 1150); } } else { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { return(length / 1024); } } } else if (task.Category == TaskCategory.Raster) { if (task.DestFileName.ToLower().Contains(".gdb")) { if (task.SourceFileName.ToLower().Contains(".gdb")) { IWorkspaceFactory inputWsF = null; IWorkspace inputWs = null; IRasterWorkspace inputRstWs = null; IRasterDataset2 inputRstDs = null; IRaster inputRaster = null; string inputDirectory = string.Empty; string inputRstName = string.Empty; string input = task.SourceFileName.Trim(); if (input.ToLower().Contains(".gdb")) { inputWsF = new FileGDBWorkspaceFactoryClass(); inputDirectory = input.Substring(0, input.IndexOf(".gdb") + 4); } else { inputWsF = new RasterWorkspaceFactoryClass(); inputDirectory = System.IO.Path.GetDirectoryName(input); } inputRstName = System.IO.Path.GetFileName(input); inputWs = inputWsF.OpenFromFile(inputDirectory, 0); inputRstWs = inputWs as IRasterWorkspace; inputRstDs = inputRstWs.OpenRasterDataset(inputRstName) as IRasterDataset2; inputRaster = inputRstDs.CreateDefaultRaster(); IRawBlocks inputRawBlocks = (IRawBlocks)inputRstDs; IRasterInfo inputRstInfo = inputRawBlocks.RasterInfo; IRasterProps in_rasterProps = (IRasterProps)inputRaster; int Height = in_rasterProps.Height; int Width = in_rasterProps.Width; rstPixelType in_rstPT = in_rasterProps.PixelType; int BandsCount = inputRstInfo.BandCount; Dictionary <rstPixelType, int> DictPT = new Dictionary <rstPixelType, int>(); DictPT.Clear(); DictPT.Add(rstPixelType.PT_DOUBLE, 64); DictPT.Add(rstPixelType.PT_FLOAT, 32); DictPT.Add(rstPixelType.PT_LONG, 32); DictPT.Add(rstPixelType.PT_SHORT, 32); DictPT.Add(rstPixelType.PT_UCHAR, 8); DictPT.Add(rstPixelType.PT_ULONG, 32); DictPT.Add(rstPixelType.PT_USHORT, 32); DictPT.Add(rstPixelType.PT_CHAR, 8); int Depth = 32; DictPT.TryGetValue(in_rasterProps.PixelType, out Depth); return((int)(1.0 * Height * Width * BandsCount * Depth / 8.0 / 1024)); } else { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024 + 1150)); } } else { if (task.SourceFileName.ToLower().Contains(".gdb")) { } else { System.IO.FileInfo fileInfo = new System.IO.FileInfo(task.SourceFileName); return((int)(fileInfo.Length / 1024)); } } } return(task.Size); }
//AE+C#修改栅格数据像素值 //private void ChangeRasterValue(IRasterDataset2 pRasterDatset, double dbScale, double dbOffset) //{ // 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); // if (double.IsNaN(dbNoData)) // return; // 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方向偏移 // } // //pixels.SetValue(ob, i, j); // 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()); // pRasterEdit.Refresh(); // System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); // } //} private bool rasterTransfer(IRasterLayer pRasterLayer, string szFilename, double[] dbRotateMatrix, double[] dbOffsetMatrix) { if (pRasterLayer == null || dbRotateMatrix == null || dbOffsetMatrix == null || dbRotateMatrix.Length != 9 || dbOffsetMatrix.Length != 3) { return(false); } //IRasterLayer pResultLayer = new RasterLayerClass(); //pResultLayer.CreateFromRaster(pRasterLayer.Raster); //pResult = new RasterLayer(); //pResult.co IGeoReference pGeoReference = pRasterLayer as IGeoReference; //XY平面平移和旋转 double dbScale = Math.Sqrt(dbRotateMatrix[0] * dbRotateMatrix[0] + dbRotateMatrix[1] * dbRotateMatrix[1]); double dbTheta = Math.Acos(dbRotateMatrix[0] / dbScale); IPoint pt = new PointClass(); pt.X = 0; pt.Y = 0; pGeoReference.Rotate(pt, -dbTheta / Math.PI * 180); //旋转 pGeoReference.Shift(-dbOffsetMatrix[0], -dbOffsetMatrix[1]); //平移 //pGeoReference.Rotate(pt, dbTheta / Math.PI * 180); //旋转 pGeoReference.ReScale(1 / dbScale, 1 / dbScale); //拉伸 try { if (!File.Exists(szFilename)) { pGeoReference.Rectify(szFilename, "TIFF"); IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2; IRasterEdit pRasterEdit = pRaster2 as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit); } //MessageBox.Show("转换完成!"); } catch (System.Exception ex) { //MessageBox.Show("转换出错!"); return(false); } finally { pGeoReference.Reset(); } //Open a raster file workspace. IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace) workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szFilename), 0); //Open a file raster dataset. IRasterDataset rasterDataset = rasterWorkspace.OpenRasterDataset(System.IO.Path.GetFileName(szFilename)); IRasterDataset2 rasterDataset2 = rasterDataset as IRasterDataset2; ClsRasterOp pRasterOp = new ClsRasterOp(); pRasterOp.ChangeRasterValue(rasterDataset2, dbRotateMatrix[8], dbOffsetMatrix[2]); ////Z方向变化 //System.Array pixels, dstPixels; //IPixelBlock3 pixelBlock3 = null; //IRaster2 pRaster2 = rasterDataset.Raster as IRaster2; //IRaster pRaster = pDstLayer.Raster; //IRasterEdit pEdit = pRaster as IRasterEdit; //IRasterCursor rasterCursor = pRaster2.CreateCursorEx(null);//null时为128*128 //do //{ // IPnt nSize = new PntClass(); // nSize.X = rasterCursor.PixelBlock.Width; // nSize.Y = rasterCursor.PixelBlock.Height; // pixelblock4 = rasterCursor.PixelBlock as IPixelBlock3; // pixelBlock3 = pRaster.CreatePixelBlock(nSize) as IPixelBlock3; // int nWidth = pixelBlock3.Width; // int nHeight = pixelBlock3.Height; // pixels = (System.Array)pixelBlock3.get_PixelData(0); // dstPixels = (System.Array)pixelblock4.get_PixelData(0); // for (int i = 0; i < nWidth; i++) // { // for (int j = 0; j < nHeight; j++) // { // object obj = pixels.GetValue(i, j); // double ob = Convert.ToDouble(obj); // ob *= dbRotateMatrix[8]; //翻转 // ob += dbOffsetMatrix[2]; //Z方向偏移 // dstPixels.SetValue(ob, i, j); // } // } // //写回数据 // pEdit.Write(rasterCursor.TopLeft, pixelblock4 as IPixelBlock); //} while (rasterCursor.Next() == true); return(true); }
public static void OpenFileRasterDataset(string inFolderName, string inRasterDatasetName, string inFeatureName, string inFieldName, double outCellSize, string outSummaryFile) { EnableEsriLiscences(); //Get feature raster from feature shp string outTempRasterName = "tempZoneRasterFromESRI.tif"; string outZoneRater = inFolderName + "\\" + outTempRasterName; int rasterBlockSize = 1024; RasterizeEsri.Rasterize(inFeatureName, outZoneRater, inFieldName, outCellSize); //Open raster file workspace IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass(); IRasterWorkspace rasterWorkspace = (IRasterWorkspace)workspaceFactory.OpenFromFile(inFolderName, 0); //Align raster string inValueRaster = inFolderName + "\\" + inRasterDatasetName; string inClipFeature = inFeatureName; string outClippedRasterName = "tempValueRasterFromESRI.tif"; string outClippedValueRaster = inFolderName + "\\" + outClippedRasterName; ClipRasterBoundaryEsri.ClipRaster(inValueRaster, inClipFeature, outClippedValueRaster); //Open zone raster dataset IRasterDataset zoneRasterDataset = rasterWorkspace.OpenRasterDataset(outTempRasterName); IRasterDataset2 zoneRasterDataset2 = zoneRasterDataset as IRasterDataset2; IRaster2 zoneRs2 = zoneRasterDataset2.CreateFullRaster() as IRaster2; //Open value raster dataset IRasterDataset valueRasterDataset = rasterWorkspace.OpenRasterDataset(outClippedRasterName); IRasterDataset2 valueRasterDataset2 = valueRasterDataset as IRasterDataset2; IRaster2 valueRs2 = valueRasterDataset2.CreateFullRaster() as IRaster2; //Extract bands from the raster IRasterBandCollection valueRasterPlanes = valueRasterDataset as IRasterBandCollection; //create raster cursor to read block by block IPnt blockSize = new PntClass(); blockSize.SetCoords(rasterBlockSize, rasterBlockSize); IRasterCursor valueRasterCursor = valueRs2.CreateCursorEx(blockSize); IRasterCursor zoneRasterCursor = zoneRs2.CreateCursorEx(blockSize); if (valueRasterPlanes != null) { Dictionary <int, StatisticsInfo>[] rasInfoDict = new Dictionary <int, StatisticsInfo> [valueRasterPlanes.Count]; int zoneRasterBandId = 0; for (int b = 0; b < valueRasterPlanes.Count; b++) { rasInfoDict[b] = new Dictionary <int, StatisticsInfo>(); } do { IPixelBlock3 valueRasterPixelBlock3 = valueRasterCursor.PixelBlock as IPixelBlock3; IPixelBlock3 zoneRasterPixelBlock3 = zoneRasterCursor.PixelBlock as IPixelBlock3; //No Idea how esri cursor fills the raster gap if zone is greater than value, so quick and fix using smallest extent int blockWidth = valueRasterPixelBlock3.Width < zoneRasterPixelBlock3.Width ? valueRasterPixelBlock3.Width : zoneRasterPixelBlock3.Width; int blockHeight = valueRasterPixelBlock3.Height < zoneRasterPixelBlock3.Height ? valueRasterPixelBlock3.Height : zoneRasterPixelBlock3.Height; //Console.WriteLine(zoneRasterPixelBlock3.Width); //Console.WriteLine(blockWidth); try { System.Array zoneRasterPixels = (System.Array)zoneRasterPixelBlock3.get_PixelData(zoneRasterBandId); for (int b = 0; b < valueRasterPlanes.Count; b++) { //Console.WriteLine(b); //Get pixel array System.Array valueRasterPixels = (System.Array)valueRasterPixelBlock3.get_PixelData(b); for (int i = 0; i < blockWidth; i++) { for (int j = 0; j < blockHeight; j++) { //Get pixel value object pixelValueFromValue = null; object pixelValueFromZone = null; try { pixelValueFromValue = valueRasterPixels.GetValue(i, j); pixelValueFromZone = zoneRasterPixels.GetValue(i, j); } catch (Exception ex) { Console.WriteLine(ex.Message); } //process each pixel value try { if (rasInfoDict[b].ContainsKey(Convert.ToInt32(pixelValueFromZone))) { StatisticsInfo rastStatistics = rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)]; rastStatistics.Count++; rastStatistics.Sum = rastStatistics.Sum + Convert.ToDouble(pixelValueFromValue); rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)] = rastStatistics; } else { rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)] = new StatisticsInfo() { Count = 1, Sum = Convert.ToDouble(pixelValueFromValue) }; } } catch (Exception ex) { Console.WriteLine(ex.Message); } //Console.WriteLine(i +"-"+j); //Console.WriteLine(pixelValueFromValue + "-" + pixelValueFromZone); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } } while (zoneRasterCursor.Next() == true); //Export results StatisticsExport writer = new StatisticsExport(outSummaryFile); writer.ExportZonalStatistics(ref rasInfoDict, outCellSize); } else { Console.WriteLine("No band available in the Value Raster"); } }