private void Btn_RasterStatistic_Click(object sender, EventArgs e) { IRasterLayer pTargetRasterLayer = m_selectedLayer as IRasterLayer; if (pTargetRasterLayer == null) { MessageBox.Show("非栅格图层"); return; } IRaster pTargetRaster = pTargetRasterLayer.Raster; IRasterBandCollection pTargetRasterBandCollection = pTargetRaster as IRasterBandCollection; string strReport = ""; for (int index = 0; index < pTargetRasterBandCollection.Count; index++) { IRasterBand pTarRasterBand = pTargetRasterBandCollection.Item(index); pTarRasterBand.HasStatistics(out bool bHasStat); if (!bHasStat) { pTarRasterBand.ComputeStatsAndHist(); } IRasterStatistics pRStatistic = pTarRasterBand.Statistics; strReport += String.Format("Band{0}\n Maximum:{1}\n Mean:{2}\n Median:{3}\n Minimum{4}\n Mode:{5}\n StandardDeviation:{6}\n", index, pRStatistic.Maximum, pRStatistic.Mean, pRStatistic.Median, pRStatistic.Minimum, pRStatistic.Mode, pRStatistic.StandardDeviation); } MessageBox.Show(strReport, m_selectedLayer.Name + "栅格信息统计"); }
public static void GetCurrentSurfaceMax(ILayer ilayer_0, out double double_0, out double double_1) { ISurface surfaceFromLayer = SurfaceInfo.GetSurfaceFromLayer(ilayer_0); if (surfaceFromLayer != null) { if (surfaceFromLayer is ITinAdvanced) { ITinAdvanced tinAdvanced = surfaceFromLayer as ITinAdvanced; IEnvelope extent = tinAdvanced.Extent; double_0 = ((extent.Width > extent.Height) ? extent.Width : extent.Height); double_1 = extent.ZMax; } else { IRasterSurface rasterSurface = surfaceFromLayer as IRasterSurface; IRasterProps rasterProps = rasterSurface.Raster as IRasterProps; IEnvelope extent = rasterProps.Extent; double_0 = ((extent.Width > extent.Height) ? extent.Width : extent.Height); IRasterBandCollection rasterBandCollection = rasterProps as IRasterBandCollection; IRasterBand rasterBand = rasterBandCollection.Item(0); IRasterStatistics statistics = rasterBand.Statistics; double_1 = statistics.Maximum; } } else { double_0 = 0.0; double_1 = 0.0; } }
internal static Dictionary <string, double> SummariseRasterStatistically(IGeoDataset pRasterGeoDataset) { IRasterBandCollection tClippedAsBandCollection = pRasterGeoDataset as IRasterBandCollection; IRasterBand tClippedBand = tClippedAsBandCollection.Item(0); logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster clipped, checking stats..."); bool tHasStatistics; tClippedBand.HasStatistics(out tHasStatistics); // what on earth? why not just have a bool return type to the HasStatistics method??! if (!tHasStatistics) { tClippedBand.ComputeStatsAndHist(); } IRasterStatistics tClippedStats = tClippedBand.Statistics; //tClippedStats.Recalculate(); logger.LogMessage(ServerLogger.msgType.debug, "SummariseContinuousRaster", 99, "Continuous raster stats made, recording info..."); Dictionary <string, double> tResults = new Dictionary <string, double>(); tResults["Mean"] = tClippedStats.Mean; tResults["Max"] = tClippedStats.Maximum; tResults["Min"] = tClippedStats.Minimum; //NB Median isn't available with floating data. (Neither are majority,minority,variety). Would need //to e.g. convert to int by multiplying raster first. //tResults["Median"] = tClippedStats.Median; return(tResults); }
/// <summary> /// 计算信息熵阈值 /// </summary> public bool CalEntropyMean(out string msg) { IRasterDataset pRasterDataset = null; try { pRasterDataset = EngineAPI.OpenRasterFile(_Hyper_Entropy); IRasterBandCollection pRasterBandCollection = pRasterDataset as IRasterBandCollection; IRasterBand pRasterBand = pRasterBandCollection.Item(0); bool hasSta = false; pRasterBand.HasStatistics(out hasSta); if (!hasSta) { pRasterBand.ComputeStatsAndHist(); } IRasterStatistics pRasterStatistics = pRasterBand.Statistics; _Hyper_Entropy_T = pRasterStatistics.Mean; msg = ""; return(true); } catch (Exception ex) { msg = ex.Message; return(false); } finally { if (pRasterDataset != null) { Marshal.ReleaseComObject(pRasterDataset); } } }
private void 噪声分级_Load(object sender, EventArgs e) { //向图层comboBox1中预置噪音图层 for (int i = 0; i < global.p2DMap.LayerCount; i++) { ILayer pLayer = global.p2DMap.get_Layer(i); if (pLayer != null) { if (pLayer is IRasterLayer) { comboBox1.Items.Add(pLayer.Name); } } } comboBox1.SelectedIndex = 0; //向分级数comBobox2中预置分级数,默认为5 for (int i = 1; i < 7; i++) { comboBox2.Items.Add(i); } //栅格像元统计 IRasterBandCollection bandCollection; ILayer mlayer = GetLayerByName(comboBox1.SelectedItem.ToString()); IRasterLayer rasterLayer = mlayer as IRasterLayer; 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; } datatable1 = new DataTable(); DataColumn datacolumn1 = new DataColumn("区间", System.Type.GetType("System.String")); DataColumn datacolumn2 = new DataColumn("值", System.Type.GetType("System.Int32")); datatable1.Columns.Add(datacolumn1); datatable1.Columns.Add(datacolumn2); comboBox2.SelectedIndex = 4; //for (int i = 0; i < 5; i++) //{ // DataRow datarow1 = datatable1.NewRow(); // datarow1[0] = ((rasterStatic.Maximum - rasterStatic.Minimum) * i / 5).ToString()+"-"+ ((rasterStatic.Maximum - rasterStatic.Minimum) * (i + 1) / 5).ToString(); // datarow1[1] = i + 1; // datatable1.Rows.Add(datarow1); //} dataGridView1.DataSource = datatable1; textBox1.Text = System.Environment.CurrentDirectory + "noiseclassification.tif"; }
private IRaster rescaleHt() { IRasterBand rsBand = ((IRasterBandCollection)htRs).Item(0); IRasterStatistics rsStats = rsBand.Statistics; double min = rsStats.Minimum; double max = rsStats.Maximum; double range = (max - min); double step = range / HeightLevels; IRemapFilter flt = new RemapFilterClass(); double cnt = 0; double i = 0; for (i = min; i < max; i += step) { double nMax = i + step; if (nMax == max) { nMax = max + 1; } flt.AddClass(i, nMax, cnt); cnt++; } IRaster rs2 = rsUtil.returnRaster(rsUtil.calcRemapFunction(htRs, flt)); return(rsUtil.returnRaster(rsUtil.calcArithmaticFunction(rs2, 1000000, esriRasterArithmeticOperation.esriRasterMultiply))); }
// Hämtar maxvärdet i rasterlager. public double rasterStatMax(IRaster inputRaster) { IRasterBandCollection bands = (IRasterBandCollection)inputRaster; IRasterBand rasterBand = bands.Item(0); IRasterStatistics rs = rasterBand.Statistics; return(rs.Maximum); }
private string GetRasterStistics(IRasterBand rasterBand) { IRasterStatistics rasterStatistics = rasterBand.Statistics; string statisticsResult; statisticsResult = "" + rasterBand.Bandname + "Mean is:" + rasterStatistics.Mean.ToString() + "\n SD is" + rasterStatistics.StandardDeviation.ToString(); return(statisticsResult); }
private void RasterStatistics(IRaster pInRaster) { IRasterBandCollection pRasterBands = pInRaster as IRasterBandCollection; IRasterBand pRasterBand = null; if (pRasterBands.Count > 0) { pRasterBand = pRasterBands.Item(0); IRasterStatistics pRasterStat = pRasterBand.Statistics; double dZMax = pRasterStat.Maximum; double dZMin = pRasterStat.Minimum; lblZMax.Text = dZMax.ToString(); lblZMin.Text = dZMin.ToString(); } }
/// <summary> /// 获取栅格统计结果 /// </summary> /// <param name="inFile">输入栅格文件</param> /// <param name="bandIndex">波段索引</param> /// <returns></returns> public static IRasterStatistics GetRasterStatistics(string inFile, int bandIndex = 0) { var rasterBand = GetRasterBandAt(inFile, bandIndex); bool hasStatistics; rasterBand.HasStatistics(out hasStatistics); if (!hasStatistics) { //计算栅格统计值 rasterBand.ComputeStatsAndHist(); } IRasterStatistics rasterStatistics = rasterBand.Statistics; return(rasterStatistics); }
private IFunctionRasterDataset createArivaltimeZones(IFunctionRasterDataset arrivalTime) { IRemapFilter arrivalRemap = new RemapFilterClass(); IRasterStatistics rsStats = ((IRasterBandCollection)arrivalTime).Item(0).Statistics; if (rsStats == null) { rsUtil.calcStatsAndHist(arrivalTime); rsStats = ((IRasterBandCollection)arrivalTime).Item(0).Statistics; } else if (!rsStats.IsValid) { rsStats.SkipFactorX = 1; rsStats.SkipFactorY = 1; rsStats.Recalculate(); } else { } double max = rsStats.Maximum; double min = rsStats.Minimum; double skip = 1; switch (arrCls) { case ArrivalClasses.Hours: skip = 60; break; case ArrivalClasses.Days: skip = 1440; break; default: break; } for (double i = 0; i <= max; i += skip) { double nVl = (i + skip) / skip; arrivalRemap.AddClass(min, i + skip, nVl); } IFunctionRasterDataset reRs = rsUtil.calcRemapFunction(arrivalTime, arrivalRemap); return(reRs);// reSampleRasterGrid(reRs); }
private void ChangeStrechRender(IRasterLayer rasterLayer /*, double dbMaxValue, double dbMinValue*/) { IRaster pRaster = rasterLayer.Raster; IRasterBandCollection pRasterBandCollection = pRaster as IRasterBandCollection; IRasterBand pRasterBand = pRasterBandCollection.Item(0); if (pRasterBand == null) { return; } bool bFlag = false; pRasterBand.HasStatistics(out bFlag); if (!bFlag) { pRasterBand.ComputeStatsAndHist(); } double dbMaxValue = double.NaN; double dbMinValue = double.NaN; IRasterStatistics pStaticts = pRasterBand.Statistics; dbMaxValue = pStaticts.Maximum; dbMinValue = pStaticts.Minimum; //设置最大最小渲染方式 IRasterStretch pRasterStretch = new RasterStretchColorRampRendererClass(); IRasterStretchMinMax pRasterStretchMinMax = pRasterStretch as IRasterStretchMinMax; pRasterStretchMinMax.UseCustomStretchMinMax = true; pRasterStretchMinMax.CustomStretchMin = dbMinValue; pRasterStretchMinMax.CustomStretchMax = dbMaxValue; pRasterStretch.StretchType = esriRasterStretchTypesEnum.esriRasterStretch_MinimumMaximum; //update IRasterStretchColorRampRenderer pStretchColorRasterRenderer = (IRasterStretchColorRampRenderer)pRasterStretch;; IRasterRenderer pRasterRenderer = pStretchColorRasterRenderer as IRasterRenderer; pRasterRenderer.Raster = rasterLayer.Raster; pRasterLayer.Renderer = pStretchColorRasterRenderer as IRasterRenderer; pRasterRenderer.Update(); }
private void btnStatistics_Click(object sender, EventArgs e) { if (frmHlp.FunctionRasterDictionary.ContainsKey(cmbInRaster1.Text)) { frmSetStatistics frmStats = new frmSetStatistics(); IFunctionRasterDataset rs = frmHlp.FunctionRasterDictionary[cmbInRaster1.Text]; IRasterBandCollection rsbc = (IRasterBandCollection)rs; frmStats.dgvStats.Rows.Clear(); for (int i = 0; i < rsbc.Count; i++) { IRasterStatistics rsStats = rsbc.Item(i).Statistics; object[] rVl = { i + 1, 0, 0, 0, 0 }; if (rsStats != null) { rVl = new object[] { i + 1, rsStats.Minimum, rsStats.Maximum, rsStats.Mean, rsStats.StandardDeviation }; } frmStats.dgvStats.Rows.Add(rVl); } if (frmStats.ShowDialog() == System.Windows.Forms.DialogResult.OK) { //MessageBox.Show("Dialog = ok"); stats = new double[rsbc.Count][]; //List<string> vlLst = new List<string>(); for (int i = 0; i < frmStats.dgvStats.Rows.Count; i++) { DataGridViewRow rw = frmStats.dgvStats.Rows[i]; double min = System.Convert.ToDouble(rw.Cells[1].Value); //vlLst.Add(min.ToString()); double max = System.Convert.ToDouble(rw.Cells[2].Value); double mean = System.Convert.ToDouble(rw.Cells[3].Value); double std = System.Convert.ToDouble(rw.Cells[4].Value); double[] rwS = { min, max, mean, std }; stats[i] = rwS; } //MessageBox.Show(String.Join(",",vlLst.ToArray())); } else { stats = null; } frmStats.Dispose(); } }
/// <summary> /// 设置显示的原值--新值 /// </summary> /// <param name="pInRaster"></param> /// <param name="sField"></param> /// <returns></returns> public void setViewValue(IRaster pInRaster, string sField) { try { IRasterDescriptor pRD = new RasterDescriptorClass(); pRD.Create(pInRaster, new QueryFilterClass(), sField); IGeoDataset pGeodataset = pInRaster as IGeoDataset; IRasterLayer pRLayer = new RasterLayerClass(); IRasterBandCollection pRsBandCol = pGeodataset as IRasterBandCollection; IRasterBand pRasterBand = pRsBandCol.Item(0); pRasterBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic = pRasterBand.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; if ((dMaxValue - dMinValue) / iReClassCount >= 1) { double dItemInterval = (dMaxValue - dMinValue) / iReClassCount; double dMinTemp = dMinValue; if (this.cmbFieldsName.Items.Count > 0) { this.lsvValue.Items.Clear(); } for (int i = 0; i < iReClassCount; i++) { ListViewItem li = new ListViewItem(); li.SubItems.Clear(); li.SubItems[0].Text = dMinTemp.ToString() + " - " + (dMinTemp + dItemInterval).ToString("N4"); li.SubItems.Add(i.ToString()); this.lsvValue.Items.Add(li); dMinTemp = dMinTemp + dItemInterval; } } } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); } }
public void RasterClassify(IRasterLayer rastlayer, string classMethod, int count, IColorRamp ramp) { IRasterBand band = GetBand(rastlayer); if (band.Histogram == null) { band.ComputeStatsAndHist(); } IRasterClassifyColorRampRenderer rasClassifyRender = new RasterClassifyColorRampRendererClass(); IRasterRenderer rasRender = rasClassifyRender as IRasterRenderer; rasRender.Raster = rastlayer.Raster; rasRender.Update(); int numClasses = count; IRasterHistogram pRasterHistogram = band.Histogram; double[] dblValues = pRasterHistogram.Counts as double[]; int intValueCount = dblValues.GetUpperBound(0) + 1; double[] vValues = new double[intValueCount]; IRasterStatistics pRasterStatistic = band.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; if (dMinValue == 0) { pRasterStatistic.IgnoredValues = pRasterStatistic.Minimum; pRasterStatistic.Recalculate(); dMinValue = pRasterStatistic.Minimum; } double BinInterval = Convert.ToDouble((dMaxValue - dMinValue) / intValueCount); for (int i = 0; i < intValueCount; i++) { vValues[i] = i * BinInterval + pRasterStatistic.Minimum; } long[] longvalues = new long[dblValues.Length]; for (int i = 0; i <= dblValues.Length - 1; i++) { longvalues[i] = long.Parse(Convert.ToString(dblValues[i])); } //IClassifyGEN classify = null; IClassify classify = null; switch (classMethod) { case "等间距分级": EqualInterval eqclassify = new EqualIntervalClass(); eqclassify.Classify(vValues, longvalues, ref numClasses); classify = eqclassify as IClassify; break; case "自然断点分级": NaturalBreaks naclassify = new NaturalBreaksClass(); naclassify.Classify(vValues, longvalues, ref numClasses); classify = naclassify as IClassify; break; } //switch (classMethod) //{ // case "等间距分级": // classify = new EqualIntervalClass(); // break; // case "自然断点分级": // classify = new NaturalBreaksClass(); // break; //} //classify.Classify(vValues, longvalues, ref numClasses); double[] Classes = classify.ClassBreaks as double[]; UID pUid = classify.ClassID; IRasterClassifyUIProperties rasClassifyUI = rasClassifyRender as IRasterClassifyUIProperties; rasClassifyUI.ClassificationMethod = pUid; rasClassifyRender.ClassCount = count; IColor pColor; ISimpleFillSymbol pSym; for (int j = 0; j < count; j++) { IRasterProps rasterProps = (IRasterProps)rastlayer.Raster; rasterProps.NoDataValue = 0; pColor = ramp.get_Color(j * (ramp.Size / count)); pSym = new SimpleFillSymbolClass(); pSym.Color = pColor; rasClassifyRender.set_Symbol(j, (ISymbol)pSym); rasRender.Update(); rasClassifyRender.set_Break(j, rasClassifyRender.get_Break(j)); rasClassifyRender.set_Label(j, Classes[j].ToString("0.000") + "-" + Classes[j + 1].ToString("0.000")); rasRender.Update(); } rastlayer.Renderer = rasClassifyRender as IRasterRenderer; }
public void RasterClassify(IRasterLayer rastlayer, string classMethod, int count, IColorRamp ramp) { try { //计算统计图 IRasterBand band = GetBand(rastlayer); if (band.Histogram == null) { band.ComputeStatsAndHist(); } IRasterClassifyColorRampRenderer rasClassifyRender = new RasterClassifyColorRampRendererClass(); IRasterRenderer rasRender = rasClassifyRender as IRasterRenderer; rasRender.Raster = rastlayer.Raster; rasRender.Update(); int numClasses = count; IRasterHistogram pRasterHistogram = band.Histogram; double[] dblValues = pRasterHistogram.Counts as double[]; int intValueCount = dblValues.GetUpperBound(0) + 1; double[] vValues = new double[intValueCount]; IRasterStatistics pRasterStatistic = band.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; double BinInterval = Convert.ToDouble((dMaxValue - dMinValue) / intValueCount); for (int i = 0; i < intValueCount; i++) { vValues[i] = i * BinInterval + pRasterStatistic.Minimum; } long[] longvalues = new long[dblValues.Length]; for (int i = 0; i <= dblValues.Length - 1; i++) { longvalues[i] = long.Parse(Convert.ToString(dblValues[i])); } //IClassifyGEN classify = null; IClassify classify = null; switch (classMethod) { case "等间距分级": classify = new EqualIntervalClass(); break; case "自然断点分级": classify = new NaturalBreaksClass(); break; } classify.Classify(ref numClasses); double[] Classes = classify.ClassBreaks as double[]; UID pUid = classify.ClassID; IRasterClassifyUIProperties rasClassifyUI = rasClassifyRender as IRasterClassifyUIProperties; rasClassifyUI.ClassificationMethod = pUid; rasClassifyRender.ClassCount = count; IColor pColor; ISimpleFillSymbol pSym; for (int j = 0; j < count; j++) { pColor = ramp.get_Color(j * (ramp.Size - 1) / (count - 1)); pSym = new SimpleFillSymbolClass(); pSym.Color = pColor; rasClassifyRender.set_Symbol(j, (ISymbol)pSym); rasRender.Update(); rasClassifyRender.set_Break(j, rasClassifyRender.get_Break(j)); //rasClassifyRender.set_Label(j, Classes[j].ToString("0.000") + "-" + Classes[j + 1].ToString("0.000")); rasRender.Update(); } //IRasterProps rasterProps = (IRasterProps)rastlayer.Raster; //rasterProps.NoDataValue = 0; //IRasterDisplayProps props = rasClassifyRender as IRasterDisplayProps; //props.NoDataColor = GET(255, 255, 255); //rasRender.Update(); rastlayer.Renderer = rasClassifyRender as IRasterRenderer; } catch { MessageBox.Show("唯一值数量已达到限制(65536)"); } }
//yjl 20110827 modify 根据渲染对象初始化界面 public void InitRasterRendererObject(IRasterLayer inRL, IRasterRenderer pRenderer) { flag = true; IRaster pRaster = inRL.Raster; IRasterBandCollection pRBC = pRaster as IRasterBandCollection; IRasterBand pRB = pRBC.Item(0);//获取第一波段 bool hasStatis = false; pRB.HasStatistics(out hasStatis); if (!hasStatis) { pRB.ComputeStatsAndHist();//统计直方图 } IRasterStatistics pRStatis = pRB.Statistics; minValueInput.Value = pRStatis.Minimum;//最大最小值 maxValueInput.Value = pRStatis.Maximum; IRasterStretchColorRampRenderer pRSCRRenderer = pRenderer as IRasterStretchColorRampRenderer; if (pRSCRRenderer.ColorScheme != "") { cmbColorRamp.Text = pRSCRRenderer.ColorScheme;//颜色方案 } DevComponents.Editors.ComboItem selItem = cmbColorRamp.SelectedItem as DevComponents.Editors.ComboItem; Bitmap bmp = new Bitmap(selItem.Image); bmp.RotateFlip(RotateFlipType.Rotate270FlipNone); pBoxColorRamp.Image = bmp; //txtMaxLb.Text=pRSCRRenderer.LabelHigh;//标签 //txtMinLb.Text=pRSCRRenderer.LabelLow; IRasterStretch pRStretch = pRSCRRenderer as IRasterStretch; if (pRStretch.Background)//背景值 { checkBackgroundColor.Checked = true; dbBackgrdVal.Value = pRStretch.get_BackgroundValues(); IColor pColor = pRStretch.BackgroundColor; //esri color System.Drawing.Color bakColor = cWinColor(pColor); colorPickerBackGround.SelectedColor = bakColor; //背景值颜色 } else { checkBackgroundColor.Checked = false; dbBackgrdVal.Enabled = false; } if (pRStretch.Invert)//色带方向 { checkReverse.Checked = true; } else { checkReverse.Checked = false; } IRasterDisplayProps pRDP = pRSCRRenderer as IRasterDisplayProps; System.Drawing.Color nodataColor = cWinColor(pRDP.NoDataColor); colorPickerNoData.SelectedColor = nodataColor;//无效值颜色 flag = false; }
private IRasterLayer SetViewShedRenderer(IRaster pInRaster, string sField, string sPath, double[,] dValue) { try { if (dValue == null) { return(null); } if (sField.Trim() == "") { return(null); } string path = ""; string fileName = ""; int iPath = sPath.LastIndexOf('\\'); path = sPath.Substring(0, iPath); fileName = sPath.Substring(iPath + 1, sPath.Length - iPath - 1); IRasterDescriptor pRD = new RasterDescriptorClass(); pRD.Create(pInRaster, null, sField); IReclassOp pReclassOp = new RasterReclassOpClass(); IGeoDataset pGeodataset = pInRaster as IGeoDataset; IRasterAnalysisEnvironment pEnv = pReclassOp as IRasterAnalysisEnvironment; IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass(); IWorkspace pWS = pWSF.OpenFromFile(path, 0); //pEnv.OutWorkspace = pWS; //object objSnap = null; //object objExtent = pGeodataset.Extent; //pEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref objExtent, ref objSnap); //pEnv.OutSpatialReference = pGeodataset.SpatialReference; IRasterBandCollection pRsBandCol = pGeodataset as IRasterBandCollection; IRasterBand pRasterBand = pRsBandCol.Item(0); pRasterBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic = pRasterBand.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; INumberRemap pNumRemap = new NumberRemapClass(); for (int i = 0; i < (dValue.Length / 3); i++) { pNumRemap.MapRange(dValue[i, 0], dValue[i, 1], (Int32)dValue[i, 2]); } IRemap pRemap = pNumRemap as IRemap; IGeoDataset pGeoDs = new RasterDatasetClass(); pGeoDs = pReclassOp.ReclassByRemap(pGeodataset, pRemap, false); IRasterBandCollection pRasBandCol = (IRasterBandCollection)pGeoDs; pRasBandCol.SaveAs(fileName, pWS, "GRID");//"IMAGINE Image" IRaster pOutRaster = pGeoDs as IRaster; IRasterLayer pRLayer = new RasterLayerClass(); pRLayer.CreateFromRaster(pOutRaster); pRLayer.Name = fileName; return(pRLayer); } catch (Exception ex) { MessageBox.Show(ex.Message.ToString()); return(null); } }
//绘制直方图的函数,传入参数为波段索引、最大像元数、绘图对象 private void DrawHisto(int index, int maxst, Graphics g) { try { //实现绘制直方图的函数 IRaster2 raster2 = m_rstlayer.Raster as IRaster2; IRasterDataset rstDataset = raster2.RasterDataset; IRasterBandCollection rstBandcoll = rstDataset as IRasterBandCollection; IRasterBand rstBand = rstBandcoll.Item(index); IRasterStatistics rstStatistics = rstBand.Statistics; double[] pixelCounts = rstBand.Histogram.Counts as double[]; //计算最大像元数(y轴) int maxCount = (int)pixelCounts[0]; for (int i = 0; i < pixelCounts.Length; i++) { if (maxCount < pixelCounts[i]) { maxCount = (int)pixelCounts[i]; } } Pen pen = new Pen(Brushes.Black, 1);//实例化细度为1的黑色画笔 Color color = new Color(); switch (index) { case 0: color = Color.Red; break; case 1: color = Color.Orange; break; case 2: color = Color.Yellow; break; case 3: color = Color.Green; break; case 4: color = Color.Blue; break; case 5: color = Color.Purple; break; case 6: color = Color.Peru; break; } //画笔颜色赋值 pen.Color = color; //不同波段用不同颜色的画笔绘制直方图 //绘制并标识最大灰度值 g.DrawString(maxCount.ToString(), new Font("New Timer", 8), Brushes.Black, new PointF(9, 34)); //绘制直方图 double xTemp = 0; double yTemp = 0; double yMax = 0; for (int i = 0; i < pixelCounts.Length; i++) { xTemp = i * 1.0 / pixelCounts.Length * (300 - 50); //计算横向位置 yTemp = 200.0 * pixelCounts[i] / maxst; //计算纵向长度并绘制 if (yTemp > yMax) { yMax = yTemp; } g.DrawLine(pen, 50 + (int)xTemp, 240, 50 + (int)xTemp, 240 - (int)yTemp); } //本来准备加一条线以表示最大值,但是感觉加上了也没什么用还混淆了界面QAQ // g.DrawLine(pen, 50,240-(int)yMax ,320, 240-(int)yMax); //释放资源 pen.Dispose(); } catch (Exception ex)//处理异常,输出异常信息 { MessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
private byte[] GetRasterStatisticsOperHandler(NameValueCollection boundVariables, JsonObject operationInput, string outputFormat, string requestProperties, out string responseProperties) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request received"); if (!_supportRasterItemAccess) { throw new ArgumentException("The image service does not have a catalog and does not support this operation"); } responseProperties = null; long?objectID; //case insensitive bool found = operationInput.TryGetAsLong("objectid", out objectID); if (!found || (objectID == null)) { throw new ArgumentNullException("ObjectID"); } IRasterCatalogItem rasterCatlogItem = null; IRasterBandCollection rasterBandsCol = null; IRasterStatistics statistics = null; try { rasterCatlogItem = _mosaicCatalog.GetFeature((int)objectID) as IRasterCatalogItem; if (rasterCatlogItem == null) { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } } catch { _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request finished with exception"); throw new ArgumentException("The input ObjectID does not exist"); } JsonObject result = new JsonObject(); try { rasterBandsCol = (IRasterBandCollection)rasterCatlogItem.RasterDataset; List <object> maxvalues = new List <object>(); List <object> minvalues = new List <object>(); List <object> standarddeviationvalues = new List <object>(); List <object> meanvalues = new List <object>(); for (int i = 0; i < rasterBandsCol.Count; i++) { statistics = rasterBandsCol.Item(i).Statistics; maxvalues.Add(statistics.Maximum); minvalues.Add(statistics.Minimum); standarddeviationvalues.Add(statistics.StandardDeviation); meanvalues.Add(statistics.Mean); Marshal.ReleaseComObject(statistics); } result.AddArray("maxValues", maxvalues.ToArray()); result.AddArray("minValues", minvalues.ToArray()); result.AddArray("meanValues", meanvalues.ToArray()); result.AddArray("stdvValues", standarddeviationvalues.ToArray()); } catch { _logger.LogMessage(ServerLogger.msgType.infoDetailed, "GetRasterStatistics", 8000, "request completed. statistics does not exist"); } finally { if (rasterBandsCol != null) { Marshal.ReleaseComObject(rasterBandsCol); } if (rasterCatlogItem != null) { Marshal.ReleaseComObject(rasterCatlogItem); } } _logger.LogMessage(ServerLogger.msgType.infoDetailed, _soename + ".GetRasterStatistics", 8000, "request completed successfully"); return(Encoding.UTF8.GetBytes(result.ToJson())); }
public IRasterDataset TinToRaster2(ITinAdvanced pTinAdvanced, esriRasterizationType pRastConvType, String sDir, String sName, rstPixelType ePixelType, Double cellsize, IEnvelope pExtent, bool bPerm, String strType) { try { ESRI.ArcGIS.Geometry.IPoint pOrigin = pExtent.LowerLeft; pOrigin.X = pOrigin.X - (cellsize * 0.5); pOrigin.Y = pOrigin.Y - (cellsize * 0.5); int nCol, nRow; nCol = Convert.ToInt32(Math.Round(pExtent.Width / cellsize)) + 1; nRow = Convert.ToInt32(Math.Round(pExtent.Height / cellsize)) + 1; IGeoDataset pGeoDataset = pTinAdvanced as IGeoDataset; ISpatialReference2 pSpatialReference2 = pGeoDataset.SpatialReference as ISpatialReference2; IRasterDataset pRasterDataset = CreateRasterSurf(sDir, sName, strType, pOrigin, nCol, nRow, cellsize, cellsize, ePixelType, pSpatialReference2, bPerm); IRawPixels pRawPixels = GetRawPixels(pRasterDataset, 0); IPnt pBlockSize = new DblPntClass(); pBlockSize.X = nCol; pBlockSize.Y = nRow; IPixelBlock3 pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize) as IPixelBlock3; object blockArray = pPixelBlock.get_PixelDataByRef(0); ITinSurface pTinSurface = pTinAdvanced as ITinSurface; IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass(); IRasterProps pRasterProps = pRawPixels as IRasterProps; object nodataFloat; object nodataInt; pOrigin.X = pOrigin.X + (cellsize * 0.5); pOrigin.Y = pOrigin.Y + (cellsize * nRow) - (cellsize * 0.5); if (ePixelType.ToString() == "PT_FLOAT") { nodataFloat = pRasterProps.NoDataValue; pTinSurface.QueryPixelBlock(pOrigin.X, pOrigin.Y, cellsize, cellsize, pRastConvType, nodataFloat, blockArray); } else { nodataInt = pRasterProps.NoDataValue; pTinSurface.QueryPixelBlock(pOrigin.X, pOrigin.Y, cellsize, cellsize, pRastConvType, nodataInt, blockArray); } if (pTinAdvanced.ProcessCancelled == false) { return(null); } IPnt pOffset = new DblPntClass(); pOffset.X = 0; pOffset.Y = 0; pRawPixels.Write(pOffset, pPixelBlock as IPixelBlock); if (!bPerm && ePixelType.ToString() == "PT_FLOAT") { IRasterBand pBand = pRawPixels as IRasterBand; IRasterStatistics pStats = pBand.Statistics; pStats.Recalculate(); } if (bPerm) { pRawPixels = null; pPixelBlock = null; pRasterProps = null; blockArray = 0; pRasterDataset = OpenRasterDataset(sDir, sName); } return(pRasterDataset); } catch { return(null); } }
/// <summary> /// 获取分析图层及Surfer /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void comboBoxOpen_SelectedIndexChanged(object sender, EventArgs e) { try { if (comboBoxOpen.Items.Count > 0) { label.Text = ""; Cls3DMarkDraw.DeleteAllElementsWithName(m_pCurrentSceneControl.Scene, sRefPlaneName); Cls3DMarkDraw.DeleteAllElementsWithName(m_pCurrentSceneControl.Scene, ContourName); m_pCurrentSceneControl.SceneGraph.RefreshViewers(); m_ScenePoly = null; m_StaPolygon = null; m_SurFace = null; txtArea2DSel.Text = ""; txtAreaAbove.Text = ""; txtAreaBelow.Text = ""; txtPara.Text = ""; txtPlaneHeight.Text = ""; txtVolumeAbove.Text = ""; txtVolumeBelow.Text = ""; DrawGeo.Enabled = false; sldPlaneHeight.Enabled = false; btncount.Enabled = false; string LayerName = comboBoxOpen.SelectedItem.ToString(); ILayer pLayer = GetLayerByName(ref LayerName); if (pLayer is IRasterLayer)//读取Raster数据的ISurface { IRasterLayer pRasterLayer = pLayer as IRasterLayer; IGeoDataset pDataset = pRasterLayer as IGeoDataset; ISpatialReference psr = pDataset.SpatialReference; if (!(psr is IProjectedCoordinateSystem)) { label.Text = "该数据为地理坐标,计算结果无效仅供参考!"; } IRasterSurface pRasterSurface = new RasterSurfaceClass(); pRasterSurface.PutRaster(pRasterLayer.Raster, 0); m_SurFace = pRasterSurface as ISurface; DrawGeo.Enabled = false; m_IsTin = false; } else if (pLayer is ITinLayer)//读取TIN数据的ISurface { ITinLayer pTinLayer = pLayer as ITinLayer; IGeoDataset pDataset = pTinLayer as IGeoDataset; ISpatialReference psr = pDataset.SpatialReference; if (!(psr is IProjectedCoordinateSystem)) { label.Text = "该数据为地理坐标,计算结果无效仅供参考!"; } m_SurFace = pTinLayer.Dataset as ISurface; m_IsTin = true; DrawGeo.Enabled = true; } if (m_SurFace == null) { MessageBox.Show("请选择需要进行分析的DEM数据", "提示!"); return; } if (m_StaPolygon == null) { if (m_SurFace is ITin) { ITin pTin = m_SurFace as ITin; sldPlaneHeight.Maximum = Convert.ToInt32(pTin.Extent.ZMax); sldPlaneHeight.Minimum = Convert.ToInt32(pTin.Extent.ZMin); } else { IRasterSurface pRasterSurface = m_SurFace as IRasterSurface; IRasterStatistics pRasterStatistic = pRasterSurface.RasterBand.Statistics; sldPlaneHeight.Maximum = Convert.ToInt32(pRasterStatistic.Maximum); sldPlaneHeight.Minimum = Convert.ToInt32(pRasterStatistic.Minimum); } double Vale = sldPlaneHeight.Maximum + sldPlaneHeight.Minimum; Vale = Vale / 2; txtPlaneHeight.Text = Vale.ToString(); Vale = Convert.ToDouble(txtPlaneHeight.Text); sldPlaneHeight.Value = Convert.ToInt32(Vale); } else { double zrange; zrange = m_StaPolygon.Envelope.ZMax - m_StaPolygon.Envelope.ZMin; sldPlaneHeight.Maximum = Convert.ToInt32(m_StaPolygon.Envelope.ZMax + zrange); sldPlaneHeight.Minimum = Convert.ToInt32(m_StaPolygon.Envelope.ZMin); sldPlaneHeight.Value = Convert.ToInt32(Math.Round(m_StaPolygon.Envelope.ZMin + (zrange * 0.5))); txtPlaneHeight.Text = sldPlaneHeight.Value.ToString(); } sldPlaneHeight.Enabled = true; btncount.Enabled = true; } } catch { return; } }
//拉伸到灰度图像 private bool stretchToGrayImage(IRaster pSrcRaster, string szOutputFilename, double dbMinThreshold = 0.02, double dbMaxThreshold = 0.98) { try { if (pSrcRaster == null || szOutputFilename == null) { return(false); } //深拷贝 IClone pSrcClone = pSrcRaster as IClone; IClone pDstClone = pSrcClone.Clone(); IRaster pDstRaster = pDstClone as IRaster; IRaster2 pDstRaster2 = pDstRaster as IRaster2; IRasterProps pRasterProps = pDstRaster as IRasterProps; //原始统计信息 bool bFlag = false; IRasterBand pRasterBand = (pDstRaster as IRasterBandCollection).Item(0); pRasterBand.HasStatistics(out bFlag); if (!bFlag) { pRasterBand.ComputeStatsAndHist(); } //得到原始栅格影像的最大最小值和步长 double dbSrcMaxValue = pRasterBand.Statistics.Maximum; double dbSrcMinValue = pRasterBand.Statistics.Minimum; double dbSrcStep = (dbSrcMaxValue - dbSrcMinValue) / 256; double dbStretchMaxValue = pRasterBand.Statistics.Maximum; double dbStretchMinValue = pRasterBand.Statistics.Minimum; #region 灰度映射,利用重分类来做 //第一次重分类 IReclassOp reclassOp = new RasterReclassOpClass(); INumberRemap numberRemap = new NumberRemapClass(); for (int i = 0; i < 256; i++) { numberRemap.MapRange(dbSrcMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i); } IRaster pRasterTemp = reclassOp.ReclassByRemap((IGeoDataset)(pDstRaster2.RasterDataset), (IRemap)numberRemap, true) as IRaster; IRaster2 pRasterTemp2 = pRasterTemp as IRaster2; IRasterProps pRasterTempProps = pRasterTemp as IRasterProps; //得到属性表 IRasterDatasetEdit3 pRasterDatasetEdit3 = pRasterTemp2.RasterDataset as IRasterDatasetEdit3; pRasterDatasetEdit3.ComputeStatisticsHistogram(1, 1, null, true); IRasterBand rasterBand = (pRasterTempProps as IRasterBandCollection).Item(0); IRasterHistogram rasterHistogram = rasterBand.Histogram; IRasterStatistics rasterStatistics = rasterBand.Statistics; double[] pHistogramCount = (double[])rasterHistogram.Counts; int nCurrentCount = 0; int nIndex = 0; int nPixelCount = 0;//pRasterProps.Width * pRasterProps.Height; //double dSum = 0.0; for (int i = 0; i < 256; i++) { nPixelCount += (int)pHistogramCount[i]; } //得到拉伸的最大最小值 while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMinThreshold) { nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]); } dbStretchMinValue = nIndex * dbSrcStep + dbSrcMinValue; while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMaxThreshold) { nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]); } dbStretchMaxValue = nIndex * dbSrcStep + dbSrcMinValue; dbSrcStep = (dbStretchMaxValue - dbStretchMinValue) / 256; #endregion #region 拉伸 INumberRemap numberRemapForStretch = new NumberRemapClass(); numberRemapForStretch.MapRange(dbSrcMinValue, dbStretchMinValue + dbSrcStep, 0); for (int i = 1; i < 255; i++) { numberRemapForStretch.MapRange(dbStretchMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i); } numberRemapForStretch.MapRange(dbStretchMinValue + 255 * dbSrcStep, dbSrcMaxValue, 255); IRaster pRasterStretch = reclassOp.ReclassByRemap((IGeoDataset)((pDstRaster as IRaster2).RasterDataset), (IRemap)numberRemapForStretch, true) as IRaster; IRasterProps pRasterStretchProps = pRasterStretch as IRasterProps; #region 注释代码 ////拉伸 //IPixelBlock3 pixelBlock3 = null; //IRasterCursor rasterCursor = (pDstRaster as IRaster2).CreateCursorEx(null);//null时为128*128 //do //{ // pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3; // int nWidth = pixelBlock3.Width; // int nHeight = pixelBlock3.Height; // System.Array pixels = (System.Array)pixelBlock3.get_PixelData(0); // for (int m = 0; m < nWidth; m++) // { // for (int n = 0; n < nHeight; n++) // { // double dbSrcValue = Convert.ToDouble(pixels.GetValue(m, n)); // if (double.IsNaN(dbSrcValue) || dbSrcValue == dbNoDataValue) // continue; // if (dbSrcValue >= dbStretchMaxValue) // pixels.SetValue(255, m, n); // else if (dbSrcValue <= dbStretchMinValue) // pixels.SetValue(0, m, n); // else // { // byte dbDstValue = Convert.ToByte((dbSrcValue - dbStretchMinValue) / (dbStretchMaxValue - dbStretchMinValue) * 255); // pixels.SetValue(dbDstValue, m, n); // } // } // } // pixelBlock3.set_PixelData(0, (System.Array)pixels); // //修改数据 // pRasterEdit.Write(rasterCursor.TopLeft, pixelBlock3 as IPixelBlock); // pRasterEdit.Refresh(); //} while (rasterCursor.Next() == true); #endregion #endregion #region 存储数据 IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass(); IWorkspace inmemWor = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szOutputFilename), 0); pRasterStretchProps.PixelType = rstPixelType.PT_UCHAR; ISaveAs2 pSaveAs = pRasterStretchProps as ISaveAs2; if (pSaveAs == null) { return(false); } IRasterStorageDef pRSDef = new RasterStorageDefClass(); IRasterDataset pDataset = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(szOutputFilename), inmemWor, "TIFF", pRSDef); (pDataset as IRasterDataset3).Refresh(); //IRasterEdit pRasterEdit = pDstRaster as IRasterEdit; IRasterEdit pRasterTempEdit = pRasterTemp as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterTempEdit); IRasterEdit pRasterStretchEdit = pRasterStretch as IRasterEdit; System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterStretchEdit); #endregion return(true); } catch (System.Exception ex) { MessageBox.Show(ex.Message); return(false); } }
/// <summary> /// 生成风险等级栅格 /// </summary> /// <param name="roadEvalName"></param> /// <param name="rains"></param> /// <param name="saveWorkspace"></param> /// <returns></returns> public bool RoadRaskCaulte(string roadEvalName, double rains, string saveWorkspace) { #region 备份 // IWorkspaceFactory rWorkspaceFactory = new RasterWorkspaceFactory(); // IWorkspace SWorkspace = rWorkspaceFactory.OpenFromFile(saveWorkspace, 0); // IRasterWorkspace rasterWorkspace = SWorkspace as IRasterWorkspace; // //栅格计算器 计算风险级数 先不要签你的三方协议 然后存储 表达式必须隔开 // IMapAlgebraOp mapAlgebra = new RasterMapAlgebraOpClass(); // IRasterDataset roadEvalRaster = OpenRasterDataSet(rasterWorkspace, roadEvalName); // IGeoDataset geo1 = roadEvalRaster as IGeoDataset; // mapAlgebra.BindRaster(geo1, "EvalRaster"); // IGeoDataset raskDataset = mapAlgebra.Execute("[EvalRaster] * 10 / 25");//然后存储 表达式必须间隔开 // //将生成的风险栅格重分类 // //<0.2 一级:可能性小 // //0.2-0.4 二级:可 // //能性较小 // //0.4-0.6 三级:可能性较大 // //0.6-0.8 四级:可能性大 // //>0.8 五级:可能性很大 // // 输入:raskDataset //// 输出:geoDataset_result // IRasterBandCollection pRsBandCol = raskDataset as IRasterBandCollection; // IRasterBand pRasterBand = pRsBandCol.Item(0); // pRasterBand.ComputeStatsAndHist(); // IRasterStatistics pRasterStatistic = pRasterBand.Statistics; // double dMaxValue = pRasterStatistic.Maximum; // double dMinValue = pRasterStatistic.Minimum; // IReclassOp pReclassOp = new RasterReclassOpClass(); // INumberRemap pNumRemap = new NumberRemapClass(); // //pNumRemap.MapRange(dMinValue, 0.2, 1); // //pNumRemap.MapRange(0.2, 0.4, 2); // //pNumRemap.MapRange(0.4, 0.6, 3); // //pNumRemap.MapRange(0.6, dMaxValue, 4); // //pNumRemap.MapRangeToNoData(-1000, 0); // //pNumRemap.MapRange(0.8, 1000, 5); // pNumRemap.MapRange(dMinValue,0.2, 0); // pNumRemap.MapRange(0.2, 0.4, 1); // pNumRemap.MapRange(0.4, 0.6, 2); // pNumRemap.MapRange(0.6, 0.8, 3); // pNumRemap.MapRange(0.8, dMaxValue, 4); // IRemap pRemap = pNumRemap as IRemap; // //IGeoDataset geoDataset_result = pReclassOp.ReclassByRemap(raskDataset, pRemap, true); // IRaster pOutRaster = pReclassOp.ReclassByRemap(raskDataset, pRemap, false) as IRaster; // IRasterLayer rasterLayer = new RasterLayerClass(); // rasterLayer.CreateFromRaster(pOutRaster); // if (rasterLayer != null) // { // //string fullPath = Common.RoadshapePath+"道路.shp"; // rasterLayer.Name = "公路风险"; // Boolean IsEqual = false; // //int Position = fullPath.LastIndexOf("\\"); // ////文件目录 // //string FilePath = fullPath.Substring(0, Position); // //string ShpName = fullPath.Substring(Position + 1); // //IWorkspaceFactory pWF; // //pWF = new ShapefileWorkspaceFactory(); // //IFeatureWorkspace pFWS; // //pFWS = (IFeatureWorkspace)pWF.OpenFromFile(FilePath, 0); // //IFeatureClass pFClass; // //pFClass = pFWS.OpenFeatureClass(ShpName); // //IFeatureLayer pFLayer = new FeatureLayer(); // //pFLayer.FeatureClass = pFClass; // for (int i = 0; i < MainFrom.m_mapControl.LayerCount;i++ ) // { // ILayer ComLayer=MainFrom.m_mapControl.get_Layer(i); // if (rasterLayer.Name == ComLayer.Name) // { // IsEqual = true; // } // } // if (!IsEqual) // { // //MainFrom.m_mapControl.AddLayer((ILayer)pFLayer); // MainFrom.m_mapControl.AddLayer(rasterLayer); // IEnvelope envelope = rasterLayer.AreaOfInterest; // MainFrom.m_mapControl.ActiveView.Extent = envelope;//缩放至图层 // } // } // return true; #endregion IWorkspaceFactory rWorkspaceFactory = new RasterWorkspaceFactory(); IWorkspace SWorkspace = rWorkspaceFactory.OpenFromFile(saveWorkspace, 0); IRasterWorkspace rasterWorkspace = SWorkspace as IRasterWorkspace; //栅格计算器 计算风险级数 先不要签你的三方协议 然后存储 表达式必须隔开 IMapAlgebraOp mapAlgebra = new RasterMapAlgebraOpClass(); IRasterDataset roadEvalRaster = OpenRasterDataSet(rasterWorkspace, roadEvalName); IGeoDataset geo1 = roadEvalRaster as IGeoDataset; mapAlgebra.BindRaster(geo1, "EvalRaster"); IGeoDataset raskDataset = mapAlgebra.Execute("[EvalRaster] * " + rains + " / 25");//然后存储 表达式必须间隔开 //将生成的风险栅格重分类 //<0.2 一级:可能性小 //0.2-0.4 二级:可 //能性较小 //0.4-0.6 三级:可能性较大 //0.6-0.8 四级:可能性大 //>0.8 五级:可能性很大 // 输入:raskDataset // 输出:geoDataset_result IRasterBandCollection pRsBandCol = raskDataset as IRasterBandCollection; IRasterBand pRasterBand = pRsBandCol.Item(0); pRasterBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic = pRasterBand.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; IReclassOp pReclassOp = new RasterReclassOpClass(); INumberRemap pNumRemap = new NumberRemapClass(); IDictionary <int, RoadRange> roadRanges = this.roadRiskConfig.GetRoadRiskLevelFromConfig(); foreach (var v in roadRanges) { pNumRemap.MapRange(v.Value.MinValue, v.Value.MaxValue, v.Key); } IRemap pRemap = pNumRemap as IRemap; //IGeoDataset geoDataset_result = pReclassOp.ReclassByRemap(raskDataset, pRemap, true); IRaster pOutRaster = pReclassOp.ReclassByRemap(raskDataset, pRemap, false) as IRaster; IRasterLayer rasterLayer = new RasterLayerClass(); rasterLayer.CreateFromRaster(pOutRaster); if (rasterLayer != null) { rasterLayer.Name = "公路风险"; for (int i = 0; i < MainFrom.m_mapControl.LayerCount; i++) { ILayer ComLayer = MainFrom.m_mapControl.get_Layer(i); if (rasterLayer.Name == ComLayer.Name) { MainFrom.m_mapControl.Map.DeleteLayer(ComLayer); } } Common.funColorForRaster_Classify(rasterLayer, roadRanges.Count); IEnvelope envelope = rasterLayer.AreaOfInterest; MainFrom.m_mapControl.ActiveView.Extent = envelope;//缩放至图层 } return(true); }
/// <summary> /// 风险因素等级划分 /// </summary> /// <param name="RasterWorkspace"></param> /// <param name="roadEvalName"></param> /// <returns></returns> public static bool RaskCaulte(string RasterWorkspace, string roadEvalName) { IWorkspaceFactory rWorkspaceFactory = new RasterWorkspaceFactory(); IWorkspace SWorkspace = rWorkspaceFactory.OpenFromFile(RasterWorkspace, 0); IRasterWorkspace rasterWorkspace = SWorkspace as IRasterWorkspace; //栅格计算器 计算风险级数 先不要签你的三方协议 然后存储 表达式必须隔开 IMapAlgebraOp mapAlgebra = new RasterMapAlgebraOpClass(); IRasterDataset roadEvalRaster = rasterWorkspace.OpenRasterDataset(roadEvalName); IGeoDataset geo1 = roadEvalRaster as IGeoDataset; mapAlgebra.BindRaster(geo1, "EvalRaster"); IGeoDataset raskDataset = mapAlgebra.Execute("[EvalRaster]");//然后存储 表达式必须间隔开 //将生成的风险栅格重分类 //<0.2 一级:可能性小 //0.2-0.4 二级:可 //能性较小 //0.4-0.6 三级:可能性较大 //0.6-0.8 四级:可能性大 //>0.8 五级:可能性很大 // 输入:raskDataset // 输出:geoDataset_result IRasterBandCollection pRsBandCol = raskDataset as IRasterBandCollection; IRasterBand pRasterBand = pRsBandCol.Item(0); pRasterBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic = pRasterBand.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; IReclassOp pReclassOp = new RasterReclassOpClass(); INumberRemap pNumRemap = new NumberRemapClass(); //等级参数 List <double> raskRanges = new List <double>(); for (int n = 0; n < 5; n++) { raskRanges.Add(dMinValue + (dMaxValue - dMinValue) * n / 4); } for (int m = 0; m < 4; m++) { pNumRemap.MapRange(raskRanges[m], raskRanges[m + 1], m + 1); } IRemap pRemap = pNumRemap as IRemap; IRaster pOutRaster = pReclassOp.ReclassByRemap(raskDataset, pRemap, false) as IRaster; IRasterLayer rasterLayer = new RasterLayerClass(); rasterLayer.CreateFromRaster(pOutRaster); if (rasterLayer != null) { rasterLayer.Name = roadEvalName; for (int i = 0; i < MainFrom.m_mapControl.LayerCount; i++) { ILayer ComLayer = MainFrom.m_mapControl.get_Layer(i); if (rasterLayer.Name == ComLayer.Name) { MainFrom.m_mapControl.Map.DeleteLayer(ComLayer); } } Common.funColorForRaster_Classify(rasterLayer, 4); IEnvelope envelope = rasterLayer.AreaOfInterest; MainFrom.m_mapControl.ActiveView.Extent = envelope;//缩放至图层 } return(true); }
//public void RasterClassify(IRasterLayer rastlayer, string classMethod, int count, IColorRamp ramp,double minValue) //{ // IRasterBand band = GetBand(rastlayer); // if (band.Histogram == null) // { // band.ComputeStatsAndHist(); // } // IRasterClassifyColorRampRenderer rasClassifyRender = new RasterClassifyColorRampRendererClass(); // IRasterRenderer rasRender = rasClassifyRender as IRasterRenderer; // rasRender.Raster = rastlayer.Raster; // rasRender.Update(); // int numClasses = count; // IRasterHistogram pRasterHistogram = band.Histogram; // double[] dblValues = pRasterHistogram.Counts as double[]; // int intValueCount = dblValues.GetUpperBound(0) + 1; // double[] vValues = new double[intValueCount]; // IRasterStatistics pRasterStatistic = band.Statistics; // //double dMaxValue = pRasterStatistic.Maximum; // double dMaxValue = minValue; // double dMinValue = pRasterStatistic.Minimum; // double BinInterval = Convert.ToDouble((dMaxValue - dMinValue) / intValueCount); // for (int i = 0; i < intValueCount; i++) // { // vValues[i] = i * BinInterval + pRasterStatistic.Minimum; // } // long[] longvalues = new long[dblValues.Length]; // for (int i = 0; i <= dblValues.Length - 1; i++) // { // longvalues[i] = long.Parse(Convert.ToString(dblValues[i])); // } // //IClassifyGEN classify = null; // IClassify classify = null; // switch (classMethod) // { // case "等间距分级": // EqualInterval eqclassify = new EqualIntervalClass(); // eqclassify.Classify(vValues, longvalues, ref numClasses); // classify = eqclassify as IClassify; // break; // case "自然断点分级": // NaturalBreaks naclassify = new NaturalBreaksClass(); // naclassify.Classify(vValues, longvalues, ref numClasses); // classify = naclassify as IClassify; // break; // } // //switch (classMethod) // //{ // // case "等间距分级": // // classify = new EqualIntervalClass(); // // break; // // case "自然断点分级": // // classify = new NaturalBreaksClass(); // // break; // //} // //classify.Classify(vValues, longvalues, ref numClasses); // double[] Classes = classify.ClassBreaks as double[]; // UID pUid = classify.ClassID; // IRasterClassifyUIProperties rasClassifyUI = rasClassifyRender as IRasterClassifyUIProperties; // rasClassifyUI.ClassificationMethod = pUid; // rasClassifyRender.ClassCount = count; // IColor pColor; // ISimpleFillSymbol pSym; // for (int j = 0; j < count; j++) // { // pColor = ramp.get_Color(j * (ramp.Size / count)); // pSym = new SimpleFillSymbolClass(); // pSym.Color = pColor; // rasClassifyRender.set_Symbol(j, (ISymbol)pSym); // rasRender.Update(); // if (Classes[j] == 0) // { // rasClassifyRender.set_Label(j, Classes[j].ToString() + "-" + Classes[j + 1].ToString("0.000")); // rasRender.Update(); // } // else // { // rasClassifyRender.set_Label(j, Classes[j].ToString("0.000") + "-" + Classes[j + 1].ToString("0.000")); // rasRender.Update(); // } // } // rastlayer.Renderer = rasClassifyRender as IRasterRenderer; public void RasterClassify(IRasterLayer rastlayer, string classMethod, int count, IColorRamp ramp) { try { //进行唯一值判断 IUniqueValues values = new UniqueValuesClass(); IRasterCalcUniqueValues unique = new RasterCalcUniqueValuesClass(); unique.AddFromRaster(rastlayer.Raster, 0, values); int uniquecount = values.get_UniqueCount(0); //计算统计图 IRasterBand band = GetBand(rastlayer); if (band.Histogram == null) { band.ComputeStatsAndHist(); } IRasterClassifyColorRampRenderer rasClassifyRender = new RasterClassifyColorRampRendererClass(); IRasterRenderer rasRender = rasClassifyRender as IRasterRenderer; rasRender.Raster = rastlayer.Raster; rasRender.Update(); int numClasses = count; IRasterHistogram pRasterHistogram = band.Histogram; double[] dblValues = pRasterHistogram.Counts as double[]; int intValueCount = dblValues.GetUpperBound(0) + 1; double[] vValues = new double[intValueCount]; IRasterStatistics pRasterStatistic = band.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; if (dMinValue == 0) { pRasterStatistic.IgnoredValues = pRasterStatistic.Minimum; pRasterStatistic.Recalculate(); dMinValue = pRasterStatistic.Minimum; } double BinInterval = Convert.ToDouble((dMaxValue - dMinValue) / intValueCount); for (int i = 0; i < intValueCount; i++) { vValues[i] = i * BinInterval + pRasterStatistic.Minimum; } long[] longvalues = new long[dblValues.Length]; for (int i = 0; i <= dblValues.Length - 1; i++) { longvalues[i] = long.Parse(Convert.ToString(dblValues[i])); } //IClassifyGEN classify = null; IClassify classify = null; switch (classMethod) { case "等间距分级": EqualInterval eqclassify = new EqualIntervalClass(); eqclassify.Classify(vValues, longvalues, ref numClasses); classify = eqclassify as IClassify; break; case "自然断点分级": NaturalBreaks naclassify = new NaturalBreaksClass(); naclassify.Classify(vValues, longvalues, ref numClasses); classify = naclassify as IClassify; break; } #region //switch (classMethod) //{ // case "等间距分级": // classify = new EqualIntervalClass(); // break; // case "自然断点分级": // classify = new NaturalBreaksClass(); // break; //} //classify.Classify(vValues, longvalues, ref numClasses); #endregion double[] Classes = classify.ClassBreaks as double[]; int n = Classes.Count(); double dn = Classes[0]; UID pUid = classify.ClassID; IRasterClassifyUIProperties rasClassifyUI = rasClassifyRender as IRasterClassifyUIProperties; rasClassifyUI.ClassificationMethod = pUid; rasClassifyRender.ClassCount = count; IColor pColor; ISimpleFillSymbol pSym; //排除数值 double[] exdouble = new double[2] { 0, Classes[0] }; IRasterDataExclusion ex = rasClassifyRender as IRasterDataExclusion; ex.ExcludeValues = exdouble; ex.ExcludeColor = GET(255, 255, 255); for (int j = 0; j < count; j++) { pColor = ramp.get_Color(j * (ramp.Size / count)); pSym = new SimpleFillSymbolClass(); pSym.Color = pColor; rasClassifyRender.set_Symbol(j, (ISymbol)pSym); rasRender.Update(); rasClassifyRender.set_Break(j, rasClassifyRender.get_Break(j)); rasClassifyRender.set_Label(j, Classes[j].ToString("0.000") + "-" + Classes[j + 1].ToString("0.000")); rasRender.Update(); } //IRasterProps rasterProps = (IRasterProps)rastlayer.Raster; //rasterProps.NoDataValue = 0; //IRasterDisplayProps props = rasClassifyRender as IRasterDisplayProps; //props.NoDataColor = GET(255, 255, 255); //rasRender.Update(); rastlayer.Renderer = rasClassifyRender as IRasterRenderer; } catch (Exception ex) { //MessageBox.Show(ex.ToString()); if (ex.ToString().Contains("唯一值过多")) { MessageBox.Show("唯一值数量已达到限制(65536)"); } else { MessageBox.Show("还未计算唯一值,进行唯一值计算!"); } } //catch //{ // MessageBox.Show("数据需要先计算统计值,请点击确定进行计算!"); //} }
private IRasterLayer SetRsLayerClassifiedColor(IRaster pRaster) { IRasterClassifyColorRampRenderer pClassRen = new RasterClassifyColorRampRendererClass(); IRasterRenderer pRasRen = (IRasterRenderer)pClassRen; //Set raster for the render and update pRasRen.Raster = pRaster; pClassRen.ClassCount = 9; pRasRen.Update(); //Create a color ramp to use //定义起点和终点颜色 IColor pFromColor = new RgbColorClass(); IRgbColor pRgbColor = (IRgbColor)pFromColor; pRgbColor.Red = 255; pRgbColor.Green = 200; pRgbColor.Blue = 0; IColor pToColor = new RgbColorClass(); pRgbColor = (IRgbColor)pToColor; pRgbColor.Red = 0; pRgbColor.Green = 0; pRgbColor.Blue = 255; //创建颜色分级 IAlgorithmicColorRamp pRamp = new AlgorithmicColorRampClass(); pRamp.Size = 9; pRamp.FromColor = pFromColor; pRamp.ToColor = pToColor; bool ok = true; pRamp.CreateRamp(out ok); //获得栅格统计数值 IRasterBandCollection pRsBandCol = (IRasterBandCollection)pRaster; IRasterBand pRsBand = pRsBandCol.Item(0); pRsBand.ComputeStatsAndHist(); IRasterStatistics pRasterStatistic = pRsBand.Statistics; double dMaxValue = pRasterStatistic.Maximum; double dMinValue = pRasterStatistic.Minimum; //Create symbol for the classes IFillSymbol pFSymbol = new SimpleFillSymbolClass(); double LabelValue = Convert.ToDouble((dMaxValue - dMinValue) / 9); for (int i = 0; i < pClassRen.ClassCount; i++) { pFSymbol.Color = pRamp.get_Color(i); pClassRen.set_Symbol(i, (ISymbol)pFSymbol); double h1 = (LabelValue * i) + dMinValue; double h2 = (LabelValue * (i + 1)) + dMinValue; pClassRen.set_Label(i, h1.ToString() + "-" + h2.ToString()); } //Update the renderer and plug into layer pRasRen.Update(); IRasterLayer pRLayer = new RasterLayerClass(); pRLayer.CreateFromRaster(pRaster); pRLayer.Renderer = (IRasterRenderer)pClassRen; return(pRLayer); }