public static string ExportLayerImage(IRaster pRaster, string[] bbox, string[] size,string outputUrl,string serveroutDir) { //判断栅格文件是否已经存在,存在删除,原因是如果存在,不删除的话,保存图片出错 //创建rasterlayer IRasterLayer pRasterLayer = new RasterLayerClass(); //获取mapServer中所有的图层 IMap pMap = new MapClass(); pRasterLayer.CreateFromRaster(pRaster); pMap.AddLayer(pRasterLayer as ILayer); // // Size pSize = new Size(); pSize.Width = Convert.ToInt32(size[0]); pSize.Height = Convert.ToInt32(size[1]); // IEnvelope pEnvelop = new EnvelopeClass(); pEnvelop.PutCoords(Convert.ToDouble(bbox[0]), Convert.ToDouble(bbox[1]), Convert.ToDouble(bbox[2]), Convert.ToDouble(bbox[3])); Image pImage = SaveCurrentToImage(pMap, pSize, pEnvelop); string imageName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".png"; //outputUrl="http://localhost:6080/arcgis/rest/directories/arcgisoutput/imageserver/miyunspot_ImageServer/" // serveroutDir="D:\arcgisserver\directories\arcgisoutput\imageserver\miyunspot_ImageServer"; string url = outputUrl + imageName; string path = System.IO.Path.Combine(serveroutDir, imageName); pImage.Save(path); return url; }
/// <summary> /// Expands the first envelope to include the second. /// </summary> /// <param name="input1">The first input raster to union the envelope for.</param> /// <param name="input2">The second input raster to union the envelope for.</param> /// <returns>The expanded envelope.</returns> private static Extent UnionEnvelope(IRaster input1, IRaster input2) { Extent e1 = input1.Bounds.Extent; Extent e2 = input2.Bounds.Extent; e1.ExpandToInclude(e2); return e1; }
/// <summary> /// This function creates the HDR of Gridfile /// </summary> /// <param name="inExtents"> Extension of grid</param> /// <param name="cellSize">Size cell of the grid</param> /// <param name="projection">Projection (the same that shapefile)</param> /// <param name="noDataValue">No value definition</param> /// <param name="outGridPath">Path of the output</param> /// <param name="outGrid">Name of the output grid</param> public static void CreateGridFromExtents( Extent inExtents, double cellSize, ProjectionInfo projection, double noDataValue, string outGridPath, out IRaster outGrid) { double height = Math.Abs(inExtents.MaxY - inExtents.MinY); double width = Math.Abs(inExtents.MaxX - inExtents.MinX); int numberRows = Convert.ToInt32(Math.Ceiling(height / cellSize)) + 1; int numberCols = Convert.ToInt32(Math.Ceiling(width / cellSize)) + 1; // outGrid = Raster.CreateRaster(@outGridPath, null, demRaster.NumColumns, demRaster.NumRows, 1, demRaster.DataType, rasterOptions); outGrid = Raster.CreateRaster(@outGridPath, null, numberCols, numberRows, 1, typeof(float), new String[] { }); outGrid.NoDataValue = noDataValue; outGrid.Projection = projection; outGrid.CellHeight = cellSize; outGrid.CellWidth = cellSize; //if (inExtents.MinX < 0) // outGrid.Xllcenter = inExtents.MinX + (cellSize / 2.0); //else outGrid.Xllcenter = inExtents.MinX;// -(cellSize / 2.0); //if (inExtents.MinY < 0) // outGrid.Yllcenter = inExtents.MinY + (cellSize / 2.0); //else outGrid.Yllcenter = inExtents.MinY;// -(cellSize / 2.0); }
public void export(string name,IRaster raster) { //GATGrid grid = new GATGrid(); //grid.DataFileName = name; //grid.WriteChangesToFile = true; //grid.West = raster.Bounds.Left(); //grid.North = raster.Bounds.Top(); //grid.South = raster.Bounds.Bottom(); //grid.East = raster.Bounds.Right(); //grid.GridResolution = raster.CellHeight; //grid.DataType = "float"; //grid.DataScale = "continuous"; //grid.InitializeGrid(raster.NumColumns, raster.NumRows); //grid.Maximum = (float)raster.Maximum; //grid.Minimum = (float)raster.Minimum; //grid.SetBlockData(); //grid.HeaderFileName = name; //for (int row = 0; row < raster.NumRows; row++) // for (int col = 0; col < raster.NumColumns; col++) // { // float v = (float)raster.Value[row, col]; // grid[col, row] = v; // } //grid.WriteHeaderFile(); //grid.WriteDataInMemoryToFile(); //grid.ReleaseMemoryResources(); }
public static string ApplyMLClassifyFunction(IImageServer imageServer, IRaster pRaster, string signaturfile) { //Define a function. IRasterFunction hillshadeFunction = new MLClassifyFunctionClass(); IRasterFunctionArguments functionArgument = new MLClassifyFunctionArgumentsClass(); functionArgument.PutValue("Raster", pRaster); functionArgument.PutValue("SignatureFile", signaturfile); //Attach the function to a rendering rule. IRenderingRule renderRule = new RenderingRuleClass(); renderRule.Function = hillshadeFunction; renderRule.Arguments = functionArgument; renderRule.VariableName = "DEM"; //Define the image description. IGeoImageDescription geoImageDesc = new GeoImageDescriptionClass(); geoImageDesc.Compression = "LZ77"; geoImageDesc.Extent = imageServer.ServiceInfo.Extent; geoImageDesc.Width = 800; geoImageDesc.Height = 600; geoImageDesc.Interpolation = rstResamplingTypes.RSP_BilinearInterpolation; IGeoImageDescription2 geoImageDesc2 = (IGeoImageDescription2)geoImageDesc; geoImageDesc2.RenderingRule = renderRule; //Define the return image type. IImageType imgType = new ImageTypeClass(); imgType.Format = esriImageFormat.esriImagePNG; imgType.ReturnType = esriImageReturnType.esriImageReturnURL; //Export the image. IImageResult imgResult = imageServer.ExportImage(geoImageDesc2, imgType); return imgResult.URL; }
public QueryRasterLayer(IMapLayerInfo mapLayerInfo, IRaster raster) { this.Name = mapLayerInfo.Name; this.ID = mapLayerInfo.ID; this.Extent = mapLayerInfo.Extent; this.Raster = raster; }
public static void buildStats(IRaster inputRaster, string functionModelPath) { IRasterProps rsProps = (IRasterProps)inputRaster; double[] noDataArr = (double[])rsProps.NoDataValue; IRasterBandCollection rsBc = (IRasterBandCollection)inputRaster; string statPath = functionModelPath.Replace(".fds",".sta"); using (System.IO.StreamWriter sw = new System.IO.StreamWriter(statPath)) { for (int i = 0; i < rsBc.Count; i++) { double ndVl = noDataArr[i]; IRasterBand rsBand = rsBc.Item(i); IRasterStatistics rsStats = rsBand.Statistics; double max = checkStatNumber(rsStats.Maximum,ndVl); double min = checkStatNumber(rsStats.Minimum,ndVl); double mean = checkStatNumber(rsStats.Mean,ndVl); double std = checkStatNumber(rsStats.StandardDeviation,ndVl); string bndStatsLn = max.ToString() + ":" + mean.ToString() + ":" + min.ToString() + ":" + std.ToString()+ ":"+rsStats.SkipFactorX.ToString()+":"+rsStats.SkipFactorY; List<string> igVlLst = new List<string>(); if (!(rsStats.IgnoredValues == null)) { System.Array ignoredVl = (System.Array)rsStats.IgnoredValues; for (int j = 0; j < ignoredVl.Length; j++) { string vl = checkStatNumber((double)ignoredVl.GetValue(j),ndVl).ToString(); igVlLst.Add(vl); } } bndStatsLn = bndStatsLn + ":" + String.Join(",", igVlLst.ToArray()); sw.WriteLine(bndStatsLn); } sw.Close(); } }
/// <summary> /// This will resample the cells. /// If the cell size is zero, this will default to the shorter of the width or height /// divided by 256. /// </summary> /// <param name="input1">Input Raster.</param> /// <param name="cellHeight">New Cell Height or Null.</param> /// <param name="cellWidth">New Cell Width or Null.</param> /// <param name="destFilename">Output Raster Name.</param> /// <param name="progressHandler">An interface for handling the progress messages.</param> /// <returns>Resampled raster.</returns> public static IRaster ReSample(IRaster input1,double cellHeight, double cellWidth, string destFilename, IProgressHandler progressHandler) { if (input1 == null) return null; IEnvelope envelope = input1.Bounds.Envelope; if (cellHeight == 0) { cellHeight = envelope.Height / 256; } if(cellWidth==0) { cellWidth = envelope.Width / 256; } //Calculate new number of columns and rows int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / cellWidth)); int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / cellHeight)); IRaster output = Raster.Create(destFilename, "", noOfCol, noOfRow, 1, input1.DataType, new[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex index1; int max = (output.Bounds.NumRows); ProgressMeter pm = new ProgressMeter(progressHandler, "ReSize Cells", max); //Loop throug every cell for new value for (int i = 0; i < max; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { //Projet the cell position to Map Coordinate cellCenter = output.CellToProj(i, j); index1 = input1.ProjToCell(cellCenter); double val; if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1) { if (input1.Value[index1.Row, index1.Column] == input1.NoDataValue) val = output.NoDataValue; else val = input1.Value[index1.Row, index1.Column]; } else val = output.NoDataValue; output.Value[i, j] = val; } pm.CurrentPercent = i; } output.Save(); pm.Reset(); return output; }
public void addRasterToComboBox(string rstName, IRaster rst) { if (!cmbInRaster1.Items.Contains(rstName)) { cmbInRaster1.Items.Add(rstName); rstDic[rstName] = rst; } }
public dataPrepAdjustAccuracyAssessment(IFeatureClass ProjectArea, IRaster Map, string originalAccuracyAssessmentModel, string adjustedAccuracyAssessmentModel) { projectArea = ProjectArea; rstMap = Map; oModel = originalAccuracyAssessmentModel; aModel = adjustedAccuracyAssessmentModel; rsUtil = new rasterUtil(); }
public void addRasterToComboBox(string rstName, IRaster rst) { if (!cmbRaster.Items.Contains(rstName)) { cmbRaster.Items.Add(rstName); rstDic.Add(rstName, rst); } }
/// <summary> /// Finds the first raster column corresponding to the left-most edge of the poly /// </summary> /// <param name="polygon">the polygon</param> /// <param name="inputRaster">the input raster</param> /// <returns>The raster column corresponding to the left-most edge of the poly /// (if raster starts before left edge of the poly) /// or the first raster column (if raster starts after left edge of the poly)</returns> /// <remarks>If the poly sits to the left of the raster then the first column of the raster is returned.</remarks> private static int GetStartColumn(IFeature polygon, IRaster inputRaster) { double rasterMinXCenter = inputRaster.Xllcenter; // Does the poly sit to the left of the raster or does the raster start before the left edge of the poly if (polygon.Envelope.Minimum.X < rasterMinXCenter) return 0; else return ColumnIndexToProcess(polygon.Envelope.Minimum.X, rasterMinXCenter, inputRaster.CellWidth); }
/// <summary> /// Finds the last raster column corresponding to the right-most edge of the poly /// </summary> /// <param name="polygon">the polygon</param> /// <param name="inputRaster">the input raster</param> /// <returns>The raster column corresponding to the right-most edge of the poly /// (if raster ends after the right edge of the poly) /// or the last raster column (if raster ends before right edge of the poly)</returns> private static int GetEndColumn(IFeature polygon, IRaster inputRaster) { double rasterMaxXCenter = inputRaster.Extent.MaxX - inputRaster.CellWidth / 2; // Does the poly sit to the right of the raster or does the raster end after the right edge of the poly if (polygon.Envelope.Right() > rasterMaxXCenter) return inputRaster.NumColumns - 1; else return ColumnIndexToProcess(polygon.Envelope.Right(), rasterMaxXCenter, inputRaster.CellWidth); }
public IRasterRenderer CreateDefaultRasterRenderer(IRaster raster) { //Get raster dataset IRasterBandCollection rasterBandCollection = (IRasterBandCollection)raster; IRasterBand rasterBand = rasterBandCollection.Item(0); IRasterDataset rasterDataset = (IRasterDataset)rasterBand; //Check for TIFF format string format_Renamed = rasterDataset.Format; if (format_Renamed.Substring(0, 4) != "TIFF") { return null; } //check for bit depth IRasterProps rasterProps = (IRasterProps)rasterBand; if (rasterProps.PixelType != rstPixelType.PT_U1) { return null; } //create renderer for 1 bit raster //Create a unique value renderer and associate it with raster IRasterUniqueValueRenderer rasterUniqueValueRenderer = new RasterUniqueValueRendererClass(); IRasterRenderer rasterRenderer = (IRasterRenderer)rasterUniqueValueRenderer; rasterRenderer.Raster = raster; rasterRenderer.Update(); //Define the renderer rasterUniqueValueRenderer.HeadingCount = 1; rasterUniqueValueRenderer.set_Heading(0, ""); rasterUniqueValueRenderer.set_ClassCount(0, 2); rasterUniqueValueRenderer.Field = "VALUE"; rasterUniqueValueRenderer.AddValue(0, 0, 0); rasterUniqueValueRenderer.AddValue(0, 1, 1); rasterUniqueValueRenderer.set_Label(0, 0, "0"); rasterUniqueValueRenderer.set_Label(0, 1, "1"); // Define symbology for rendering value 0 IColor color1 = (IColor)(CreateRGBColor(200, 50, 0)); //Brown color ISimpleFillSymbol simpleFillSymbol1 = new SimpleFillSymbolClass(); simpleFillSymbol1.Color = color1; rasterUniqueValueRenderer.set_Symbol(0, 0, (ISymbol)simpleFillSymbol1); IColor color2 = new RgbColorClass(); color2.NullColor = true; ISimpleFillSymbol simpleFillSymbol2 = new SimpleFillSymbolClass(); simpleFillSymbol2.Color = color2; rasterUniqueValueRenderer.set_Symbol(0, 1, (ISymbol)simpleFillSymbol2); return rasterRenderer; }
public dataPrepStrata(IRaster VariableRaster, IRaster strataRaster) { InValueRaster = VariableRaster; InStrataRaster = strataRaster; VariableFieldNames = new string[((IRasterBandCollection)InValueRaster).Count]; for (int i = 0; i < VariableFieldNames.Length; i++) { VariableFieldNames[i] = (i + 1).ToString(); } buildModel(); }
public Dictionary<int, HashSet<Point>> Process(IRaster input) { _input = input; _width = input.NumColumns; _height = input.NumRows; _board = new int[_width, _height]; Dictionary<int, HashSet<Point>> patterns = Find(_width, _height); return patterns; }
public Coordinate GetXYCell(IRaster raster, int col, int row) { double xmin = raster.Xllcenter; double ymin = raster.Yllcenter; double cell = raster.CellWidth; int numColumns = raster.NumColumns; int numRows = raster.NumRows; double y = ((numRows - row) * cell) + ymin; double x = (col * cell) + xmin; return new Coordinate(x, y); }
public dataPrepPrincipleComponents(IRaster raster,string varianceCovariancePath=null) { inraster = raster; IRasterBandCollection bc = (IRasterBandCollection)inraster; int bcCnt = bc.Count; VariableFieldNames = new string[bcCnt]; for (int i = 0; i < bcCnt; i++) { VariableFieldNames[i] = "band_" + (i + 1).ToString(); } varcovpath = varianceCovariancePath; buildModel(); }
/// <summary> /// Export data from a raster layer. /// </summary> /// <param name="e"></param> public void ExportData(IRaster e) { using (var sfd = new SaveFileDialog { Filter = DataManager.DefaultDataManager.RasterWriteFilter }) { if (ShowDialog(sfd) == DialogResult.OK) { e.SaveAs(sfd.FileName); } } }
public dataPrepCluster(IRaster raster, int numberOfClasses) { inraster = raster; IRasterBandCollection bc = (IRasterBandCollection)inraster; int bcCnt = bc.Count; VariableFieldNames = new string[bcCnt]; for (int i = 0; i < bcCnt; i++) { VariableFieldNames[i] = "band_" + (i + 1).ToString(); } k = numberOfClasses; buildModel(); }
public dataPrepClusterKmean(IRaster raster, int numberOfClasses, double maxRec = 10000000d, double prec = 0.0001) { InRaster = raster; IRasterBandCollection bc = (IRasterBandCollection)InRaster; int bcCnt = bc.Count; VariableFieldNames = new string[bcCnt]; for (int i = 0; i < bcCnt; i++) { VariableFieldNames[i] = "band_" + (i + 1).ToString(); } K = numberOfClasses; cType = esriUtil.Statistics.clusterType.KMEANS; MaxRecords = maxRec; Precision = prec; buildModel(); }
public void Bind(object pArgument) { if (pArgument is MathFunctionArguments) { MathFunctionArguments args = (MathFunctionArguments)pArgument; inrs = args.InRaster; myFunctionHelper.Bind(inrs); myRasterInfo = myFunctionHelper.RasterInfo; myPixeltype = myRasterInfo.PixelType; myValidFlag = true; } else { throw new System.Exception("Incorrect arguments object. Expected: MathFunctionArguments"); } }
public dataPrepVarCovCorr(IRaster raster,int MaxN = 10000000) { inraster = raster; IRasterBandCollection bc = (IRasterBandCollection)inraster; int bcCnt = bc.Count; VariableFieldNames = new string[bcCnt]; for (int i = 0; i < bcCnt; i++) { VariableFieldNames[i] = "band_" + (i + 1).ToString(); } sumClms = new double[bcCnt]; sumCross = new double[bcCnt, bcCnt]; cov = new double[bcCnt, bcCnt]; maxn = MaxN; buildModel(); }
public bool TryGetMap(IViewport viewport, ref IRaster raster) { int width; int height; try { width = Convert.ToInt32(viewport.Width); height = Convert.ToInt32(viewport.Height); } catch (OverflowException) { Trace.Write("Could not convert double to int (ExportMap size)"); return false; } var uri = new Uri(GetRequestUrl(viewport.Extent, width, height)); WebRequest webRequest = WebRequest.Create(uri); try { using (var webResponse = (HttpWebResponse)webRequest.GetResponse()) using (var dataStream = webResponse.GetResponseStream()) { if (!webResponse.ContentType.StartsWith("image")) return false; byte[] bytes = BruTile.Utilities.ReadFully(dataStream); raster = new Raster(new MemoryStream(bytes), viewport.Extent); } return true; } catch (WebException webEx) { if (!ContinueOnError) throw (new RenderException( "There was a problem connecting to the WMS server", webEx)); Trace.Write("There was a problem connecting to the WMS server: " + webEx.Message); } catch (Exception ex) { if (!ContinueOnError) throw (new RenderException("There was a problem while attempting to request the WMS", ex)); Trace.Write("There was a problem while attempting to request the WMS" + ex.Message); } return false; }
public IRaster Surface(IRaster raster) { int nr = raster.NumRows; int nc = raster.NumColumns; for (int row = 0; row < nr; row++) { for (int col = 0; col < nc; col++) { raster.Value[row, col] = data[col, row]; } } raster.Save(); raster.Close(); return raster; }
public dataPrepTTest(IRaster StrataRaster, IRaster VariableRaster) { InValueRaster = VariableRaster; if (StrataRaster == null) { InStrataRaster = rsUtil.createRaster(rsUtil.constantRasterFunction(rsUtil.getBand(VariableRaster, 0), 1)); } else { InStrataRaster = StrataRaster; } VariableFieldNames = new string[((IRasterBandCollection)InValueRaster).Count]; for (int i = 0; i < VariableFieldNames.Length; i++) { VariableFieldNames[i] = (i + 1).ToString(); } buildModel(); }
/// <summary> /// Creates a new instance of a Raster layer, and will create a "FallLeaves" image based on the /// raster values. /// </summary> /// <param name="raster">The raster to use</param> public MapRasterLayer(IRaster raster):base(raster) { string imageFile = Path.ChangeExtension(raster.Filename, ".bmp"); if (File.Exists(imageFile)) File.Delete(imageFile); IRasterSymbolizer rs = new RasterSymbolizer(); rs.Raster = raster; rs.Scheme.ApplyScheme(ColorSchemes.FallLeaves, raster); Bitmap bmp = new Bitmap(raster.NumColumns, raster.NumRows); bmp.Save(imageFile); raster.PaintColorSchemeToBitmap(rs, bmp, raster.ProgressHandler); bmp.Save(imageFile); bmp.Dispose(); ImageData id = new ImageData(imageFile); id.Bounds.AffineCoefficients = raster.Bounds.AffineCoefficients; id.WorldFile.Affine = raster.Bounds.AffineCoefficients; Configure(id, raster); }
public static string CreateJPEGFromActiveView(IRaster pRaster,IEnvelope pEnv,string outurl, System.String pathFileName) { //创建rasterlayer IRasterLayer pRasterLayer = new RasterLayerClass(); //获取mapServer中所有的图层 IMap pMap = new MapClass(); pRasterLayer.CreateFromRaster(pRaster); pMap.AddLayer(pRasterLayer as ILayer); IActiveView activeView = pMap as IActiveView; activeView.Extent = pEnv; //parameter check if (activeView == null) { return null; } string imageName = System.DateTime.Now.ToString().Replace("/", "").Replace(":", "").Replace(" ", "") + ".png"; pathFileName = System.IO.Path.Combine(pathFileName, imageName); ESRI.ArcGIS.Output.IExport export = new ESRI.ArcGIS.Output.ExportPNGClass(); export.ExportFileName = pathFileName; // Microsoft Windows default DPI resolution ESRI.ArcGIS.esriSystem.tagRECT exportRECT = new ESRI.ArcGIS.esriSystem.tagRECT(); exportRECT.top = 0; exportRECT.left = 0; exportRECT.right = 800; exportRECT.bottom = 600; ESRI.ArcGIS.Geometry.IEnvelope envelope = new ESRI.ArcGIS.Geometry.EnvelopeClass(); envelope.PutCoords(exportRECT.top,exportRECT.left,exportRECT.right,exportRECT.bottom); export.PixelBounds = envelope; System.Int32 hDC = export.StartExporting(); activeView.Output(hDC, (System.Int16)export.Resolution, ref exportRECT, null, null); // Finish writing the export file and cleanup any intermediate files export.FinishExporting(); export.Cleanup(); return outurl + "/" + imageName; }
public dataPrepPairedTTest(IRaster StrataRaster, IRaster VariableRaster) { InValueRaster = VariableRaster; if (StrataRaster == null) { InStrataRaster = rsUtil.createRaster(rsUtil.constantRasterFunction(rsUtil.getBand(VariableRaster, 0), 1)); } else { InStrataRaster = StrataRaster; } VariableFieldNames = new string[((IRasterBandCollection)InValueRaster).Count]; for (int i = 0; i < VariableFieldNames.Length; i++) { VariableFieldNames[i] = (i + 1).ToString(); } IDataset dSet = (IDataset)((IRaster2)StrataRaster).RasterDataset; inpath = dSet.Workspace.PathName + "\\" + dSet.BrowseName; buildModel(); }
public void Bind(object pArgument) { if (pArgument is mergeFunctionArguments) { mergeFunctionArguments arg = (mergeFunctionArguments)pArgument; inrs = arg.InRaster; outrs = arg.OutRaster; //Console.WriteLine("Number of Bands in outrs = " + ((IRasterBandCollection)outrs).Count.ToString()); ftrCls = arg.Boundary; IRasterProps rsProp = (IRasterProps)outrs; myFunctionHelper.Bind(outrs); myRasterInfo = myFunctionHelper.RasterInfo; myPixeltype = myRasterInfo.PixelType; myValidFlag = true; } else { throw new System.Exception("Incorrect arguments object. Expected: mergeFunctionArguments"); } }
/// <summary> /// Executes the Area tool with programatic input /// Ping delete static for external testing /// </summary> /// <param name="input">The input raster</param> /// <param name="zField">The field name containing the values to interpolate</param> /// <param name="cellSize">The double geographic size of the raster cells to create</param> /// <param name="power">The double power representing the inverse</param> /// <param name="neighborType">Fixed distance of fixed number of neighbors</param> /// <param name="pointCount">The number of neighbors to include if the neighborhood type /// is Fixed</param> /// <param name="distance">Points further from the raster cell than this distance are not included /// in the calculation if the neighborhood type is Fixed Distance.</param> /// <param name="output">The output raster where values are stored. The fileName is used, but the number /// of rows and columns will be computed from the cellSize and input featureset</param> /// <param name="cancelProgressHandler">A progress handler for receiving progress messages</param> /// <returns>A boolean, true if the IDW process worked correctly</returns> public bool Execute(IFeatureSet input, string zField, double cellSize, double power, NeighborhoodType neighborType, int pointCount, double distance, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || output == null) { return(false); } // If the cellSize is 0 we calculate a cell size based on the input extents if (cellSize == 0) { cellSize = input.Extent.Width / 255; } // Defines the dimensions and position of the raster int numColumns = Convert.ToInt32(Math.Round(input.Extent.Width / cellSize)); int numRows = Convert.ToInt32(Math.Round(input.Extent.Height / cellSize)); output = Raster.CreateRaster(output.Filename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty }); output.CellHeight = cellSize; output.CellWidth = cellSize; output.Xllcenter = input.Extent.MinX + (cellSize / 2); output.Yllcenter = input.Extent.MinY + (cellSize / 2); // Used to calculate progress int lastUpdate = 0; // Populates the KD tree var kd = new KdTreeEx <IFeature>(); List <int> randomList = new List <int>(); for (int i = 0; i < input.Features.Count; i++) { randomList.Add(i); } Random rnd = new Random(); List <int> completed = new List <int>(); while (randomList.Count > 0) { int index = rnd.Next(0, randomList.Count - 1); Coordinate coord = input.Features[randomList[index]].Geometry.Coordinates[0]; while (kd.Search(coord) != null) { coord.X = coord.X * 1.000000000000001D; } kd.Insert(coord, input.Features[randomList[index]]); completed.Add(randomList[index]); randomList.RemoveAt(index); } if (neighborType == NeighborhoodType.FixedCount) { // we add all the old features to output for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { // Gets the pointCount number of cells closest to the current cell Coordinate cellCenter = output.CellToProj(y, x); var coord = output.CellToProj(y, x); var result = kd.NearestNeighbor(coord); if (result != null) { var featurePt = result.Data; if (featurePt != null) { // Sets up the IDW numerator and denominator double top = 0; double bottom = 0; double distanceToCell = cellCenter.Distance(featurePt.Geometry.Coordinates[0]); if (distanceToCell <= distance || distance == 0) { // If we can't convert the value to a double throw it out try { Convert.ToDouble(featurePt.DataRow[zField]); } catch { continue; } if (power == 2) { top += (1 / (distanceToCell * distanceToCell)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += 1 / (distanceToCell * distanceToCell); } else { top += (1 / Math.Pow(distanceToCell, power)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += 1 / Math.Pow(distanceToCell, power); } } output.Value[y, x] = top / bottom; } } } // Checks if we need to update the status bar if (Convert.ToInt32(Convert.ToDouble(x * numRows) / Convert.ToDouble(numColumns * numRows) * 100) > lastUpdate) { lastUpdate = Convert.ToInt32(Convert.ToDouble(x * numRows) / Convert.ToDouble(numColumns * numRows) * 100); cancelProgressHandler.Progress( string.Empty, lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows)); if (cancelProgressHandler.Cancel) { return(false); } } } } output.Save(); return(true); }
/// <summary> /// Creates a new instance of a color scheme using a predefined color scheme and the minimum and maximum specified /// from the raster itself /// </summary> /// <param name="schemeType">The predefined scheme to use</param> /// <param name="raster">The raster to obtain the minimum and maximum settings from</param> public ColorScheme(ColorSchemeType schemeType, IRaster raster) { Configure(); ApplyScheme(schemeType, raster); }
private void btnGO_Click(object sender, EventArgs e) { IFeatureClass pInPointFClass = null; //获得输入点特征数据类 IFeatureClass pLineBarrierFClass = null; //获得输入的线障碍类 IWorkspace pWorkspace; string fileName; string rasterPath; string shpFile; int startX, endX; string sFieldName;//选择要进行分析的字段 if (bDataPath == true) { fileName = comboBoxInPoint.Text; string shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); pInPointFClass = Utility.OpenFeatureClassFromShapefile(shpDir, shpFile); } else { pInPointFClass = GetFeatureFromMapLyr(comboBoxInPoint.Text); } if (bDataLinePath == true) { fileName = comboBoxBarrier.Text; string shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); pLineBarrierFClass = Utility.OpenFeatureClassFromShapefile(shpDir, shpFile); } else { pLineBarrierFClass = GetFeatureFromMapLyr(comboBoxBarrier.Text); } IFeatureLayer pFeatLayer = new FeatureLayerClass(); pFeatLayer.FeatureClass = pInPointFClass; rasterPath = txtOutputRasterPath.Text; IFeatureClassDescriptor pFeatClsDes = new FeatureClassDescriptorClass(); if (comboBoxZValueField.Text != "无") { pFeatClsDes.Create(pInPointFClass, null, comboBoxZValueField.Text); } else { pFeatClsDes.Create(pInPointFClass, null, ""); } try { IInterpolationOp pInterpolationOp = new RasterInterpolationOpClass(); string sCellSize = txtCellSize.Text; double dCellSize = Convert.ToDouble(sCellSize); IRasterRadius pRsRadius = new RasterRadiusClass(); string sPower = txtWeightValue.Text; double dPower = Convert.ToDouble(sPower); if (comboBoxSearchRadius.Text == "变化") { string sPointNums = txtPointNumbers.Text; int iPointNums = Convert.ToInt32(sPointNums); double maxDis = Convert.ToDouble(txtDisMaxValue.Text); object objMaxDis = maxDis; pRsRadius.SetVariable(iPointNums, ref objMaxDis); } else { string sDistance = txtDisValue.Text; double dDistance = Convert.ToDouble(sDistance); double maxPointNums = Convert.ToDouble(txtMaxPointNums.Text); object objMinPointNums = maxPointNums; pRsRadius.SetFixed(dDistance, ref objMinPointNums); } pInterpolationOp = Utility.SetRasterInterpolationAnalysisEnv(rasterPath, dCellSize, pFeatLayer); object objLineBarrier = null; if (chkBarrier.Checked == true) { objLineBarrier = comboBoxBarrier; } else { objLineBarrier = Type.Missing; } IRaster pOutRaster = null; pOutRaster = pInterpolationOp.IDW(pFeatClsDes as IGeoDataset, dPower, pRsRadius, ref objLineBarrier) as IRaster; //着色 IRasterLayer pRasterLayer = new RasterLayerClass(); pRasterLayer.Name = "反距离栅格"; Utility.ConvertRasterToRsDataset(rasterPath, pOutRaster, "反距离栅格"); pRasterLayer = Utility.SetRsLayerClassifiedColor(pOutRaster); pMainFrm.getMapControl().AddLayer(pRasterLayer, 0); } catch (Exception ex) { MessageBox.Show(ex.Message); } }
/// <summary> /// Creates the categories for this scheme based on statistics and values /// sampled from the specified raster. /// </summary> /// <param name="raster">The raster to use when creating categories</param> public void CreateCategories(IRaster raster) { GetValues(raster); CreateBreakCategories(); OnItemChanged(this); }
/// <summary> /// Finds the average slope in the given polygons with more user preferences. /// </summary> /// <param name="ras">The dem Raster(Grid file).</param> /// <param name="inZFactor">The scaler factor.</param> /// <param name="slopeInPercent">The slope in percentage.</param> /// <param name="poly">The flow poly shapefile path.</param> /// <param name="fldInPolyToStoreSlope">The field name to store average slope in the attribute.</param> /// <param name="outerShpFile">The Featureset where we have the area of interest.</param> /// <param name="outerShpIndex">The index of featureset which give paticular area of interest.</param> /// <param name="output">The path to save created slope Feature set.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>True, if executed successfully.</returns> public bool Execute(IRaster ras, double inZFactor, bool slopeInPercent, IFeatureSet poly, string fldInPolyToStoreSlope, IFeatureSet outerShpFile, int outerShpIndex, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || poly == null || outerShpFile == null || output == null) { return(false); } if (poly.FeatureType != FeatureType.Polygon || outerShpFile.FeatureType != FeatureType.Polygon) { return(false); } int previous = 0; IRaster slopegrid = new Raster(); int[] areaCount = new int[poly.Features.Count]; double[] areaTotal = new double[poly.Features.Count]; double[] areaAve = new double[poly.Features.Count]; Slope(ras, inZFactor, slopeInPercent, slopegrid, cancelProgressHandler); if (slopegrid == null) { throw new SystemException(TextStrings.Slopegridfileisnull); } foreach (IFeature f in poly.Features) { output.Features.Add(f); } for (int i = 0; i < slopegrid.NumRows; i++) { int current = Convert.ToInt32(Math.Round(i * 100D / slopegrid.NumRows)); // only update when increment in percentage if (current > previous + 5) { cancelProgressHandler.Progress(current, current + TextStrings.progresscompleted); previous = current; } for (int j = 0; j < slopegrid.NumColumns; j++) { Coordinate coordin = slopegrid.CellToProj(i, j); Point pt = new Point(coordin); IFeature point = new Feature(pt); if (!outerShpFile.Features[outerShpIndex].Geometry.Covers(point.Geometry)) { continue; // not found the point inside. } for (int c = 0; c < poly.Features.Count; c++) { if (output.Features[c].Geometry.Covers(point.Geometry)) { areaCount[c]++; areaTotal[c] += slopegrid.Value[i, j] / 100; } if (cancelProgressHandler.Cancel) { return(false); } } } } // Add the column output.DataTable.Columns.Add("FID", typeof(int)); output.DataTable.Columns.Add(fldInPolyToStoreSlope, typeof(double)); for (int c = 0; c < output.Features.Count; c++) { if (areaCount[c] == 0) { areaAve[c] = 0.0; } else { areaAve[c] = areaTotal[c] / areaCount[c]; } // Add the field values output.Features[c].DataRow["FID"] = c; output.Features[c].DataRow[fldInPolyToStoreSlope] = areaAve[c]; } output.SaveAs(output.Filename, true); slopegrid.Close(); ras.Close(); return(true); }
private void btnExecute_Click(object sender, EventArgs e) { string smpFtrNm = cmbSampleFeatureClass.Text; string mapFld = cmbMap.Text; string refFld = cmbRef.Text; string wght = cmbWeight.Text; string rstNm = cmbRst.Text; bool edSas = chbEditSas.Checked; bool exact = chbExact.Checked; double alpha = System.Convert.ToDouble(nudAlpha.Value); if (wght != null && wght != "") { WEIGHT = wght; } if (smpFtrNm == null || smpFtrNm == "") { MessageBox.Show("You must select a feature Class", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (mapFld == null || mapFld == "") { MessageBox.Show("You must select a map field", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (refFld == null || refFld == "") { MessageBox.Show("You must select a Reference field", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } this.Visible = false; IFeatureClass ftrCls = ftrDic[smpFtrNm]; accuracyAssessment aa = new accuracyAssessment(); aa.SampleLocations = ftrCls; aa.MapField = mapFld; aa.ReferenceField = refFld; aa.WeightField = WEIGHT; aa.Alpha = alpha; aa.Exact = exact; if (rstNm != null && rstNm != "") { //can be either a raster or feature class looking for the ITABLE object mapObj = rstDic[rstNm]; ITable mapTbl = null; if (mapObj is IRaster) { IRaster rs = (IRaster)mapObj; IRaster2 rs2 = (IRaster2)rs; mapTbl = rs2.AttributeTable; } else { IFeatureClass mFtrCls = (IFeatureClass)mapObj; mapTbl = (ITable)mFtrCls; } aa.InTable = mapTbl; } aa.runSasProcedure(); aa.showModelOutput(); if (edSas) { aa.editSasFile(); } this.Close(); }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// Ping deleted static for external testing 01/2010. /// </summary> /// <param name="input1">The first input raster.</param> /// <param name="input2">The second input raster.</param> /// <param name="output">The output raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>Boolean, true if the merge is successful.</returns> public bool Execute(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return(false); } Extent envelope = UnionEnvelope(input1, input2); // Figures out which raster has smaller cells IRaster smallestCellRaster = input1.CellWidth < input2.CellWidth ? input1 : input2; // Given the envelope of the two rasters we calculate the number of columns / rows int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / smallestCellRaster.CellWidth)); int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / smallestCellRaster.CellHeight)); // create output raster output = Raster.CreateRaster( output.Filename, string.Empty, noOfCol, noOfRow, 1, typeof(int), new[] { string.Empty }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex v1; RcIndex v2; int previous = 0; int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { Coordinate cellCenter = output.CellToProj(i, j); v1 = input1.ProjToCell(cellCenter); double val1; if (v1.Row <= input1.EndRow && v1.Column <= input1.EndColumn && v1.Row > -1 && v1.Column > -1) { val1 = input1.Value[v1.Row, v1.Column]; } else { val1 = input1.NoDataValue; } v2 = input2.ProjToCell(cellCenter); double val2; if (v2.Row <= input2.EndRow && v2.Column <= input2.EndColumn && v2.Row > -1 && v2.Column > -1) { val2 = input2.Value[v2.Row, v2.Column]; } else { val2 = input2.NoDataValue; } if (val1 == input1.NoDataValue && val2 == input2.NoDataValue) { output.Value[i, j] = output.NoDataValue; } else if (val1 != input1.NoDataValue && val2 == input2.NoDataValue) { output.Value[i, j] = val1; } else if (val1 == input1.NoDataValue && val2 != input2.NoDataValue) { output.Value[i, j] = val2; } else { output.Value[i, j] = val1; } if (cancelProgressHandler.Cancel) { return(false); } } int current = Convert.ToInt32(Math.Round(i * 100D / max)); // only update when increment in persentage if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); } previous = current; } // output = Temp; output.Save(); return(true); }
private void btnExecute_Click(object sender, EventArgs e) { string inRst1Nm = cmbInRaster1.Text; string txtNoDataVl = txtNodata.Text; int noVl = 0; if (!Int32.TryParse(txtNoDataVl, out noVl)) { noVl = 0; } string outNmRst = txtOutName.Text; if (inRst1Nm == "" || inRst1Nm == null) { MessageBox.Show("You must specify an input raster for In Raster 1 or type in a number", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } if (outNmRst == "" || outNmRst == null) { MessageBox.Show("You must specify an output raster name", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } IRaster rs1 = rstDic[inRst1Nm]; this.Visible = false; esriUtil.Forms.RunningProcess.frmRunningProcessDialog rp = new RunningProcess.frmRunningProcessDialog(false); DateTime dt = DateTime.Now; rp.addMessage("Creating Raster. This may take a while..."); rp.addMessage("Calculating Statistics..."); rp.stepPGBar(10); rp.TopMost = true; rp.Show(); rp.Refresh(); try { outraster = rsUtil.returnRaster(rsUtil.setNullValue(rs1, noVl)); outrastername = outNmRst; int bCnt = ((IRasterBandCollection)outraster).Count; if (mp != null && aM) { //rsUtil.calcStatsAndHist(((IRaster2)outRs).RasterDataset); IRasterLayer rsLyr = new RasterLayerClass(); rsLyr.CreateFromRaster(outraster); rsLyr.Name = outrastername; rsLyr.Visible = false; mp.AddLayer((ILayer)rsLyr); } this.DialogResult = DialogResult.OK; } catch (Exception ex) { rp.addMessage(ex.ToString()); Console.WriteLine(ex.ToString()); } finally { DateTime dt2 = DateTime.Now; TimeSpan ts = dt2.Subtract(dt); string t = " in " + ts.Days.ToString() + " days " + ts.Hours.ToString() + " hours " + ts.Minutes.ToString() + " minutes and " + ts.Seconds.ToString() + " seconds ."; rp.stepPGBar(100); rp.addMessage("Finished setting null" + t); rp.enableClose(); this.Close(); } }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); int pBHeight = pPixelBlock.Height; int pBWidth = pPixelBlock.Width; IPnt pbSize = new PntClass(); pbSize.SetCoords(pBWidth, pBHeight); IPixelBlock3 outPb = (IPixelBlock3)myFunctionHelperCoef.Raster.CreatePixelBlock(pbSize);//independent variables myFunctionHelperCoef.Read(pTlc, null, myFunctionHelperCoef.Raster, (IPixelBlock)outPb); int pBRowIndex = 0; int pBColIndex = 0; IPixelBlock3 ipPixelBlock = (IPixelBlock3)pPixelBlock; System.Array[] cArr = new System.Array[ipPixelBlock.Planes]; for (int outBand = 0; outBand < ipPixelBlock.Planes; outBand++) { System.Array pixelValues = (System.Array)ipPixelBlock.get_PixelData(outBand);//(System.Array)(td); cArr[outBand] = pixelValues; } for (int i = pBRowIndex; i < pBHeight; i++) { for (int k = pBColIndex; k < pBWidth; k++) { bool ndT = true; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { object pObj = outPb.GetVal(coefnBand, k, i); if (pObj == null) { ndT = false; break; } double pixelValue = Convert.ToDouble(pObj); xVls[coefnBand] = pixelValue; } if (ndT) { try { double[] pp = lm.computNew(xVls); for (int p = 0; p < pp.Length; p++) { double pVl = pp[p]; object spVl = rasterUtil.getSafeValue(pVl, ipPixelBlock.get_PixelType(p)); cArr[p].SetValue(spVl, k, i); } } catch (Exception e) { Console.WriteLine(e.ToString()); for (int p = 0; p < ipPixelBlock.Planes; p++) { cArr[p].SetValue(0, k, i); } } } else { for (int p = 0; p < ipPixelBlock.Planes; p++) { cArr[p].SetValue(0, k, i); } } } } for (int i = 0; i < ipPixelBlock.Planes; i++) { ipPixelBlock.set_PixelData(i, cArr[i]); } } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of Regression Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
private static float[][] CreateHillShadeT <T>(this IRaster raster, Func <int, int, T> getValue, IShadedRelief shadedRelief, ProgressMeter progressMeter) where T : IEquatable <T>, IComparable <T> { if (!raster.IsInRam) { return(null); } int numCols = raster.NumColumns; int numRows = raster.NumRows; var noData = Convert.ToSingle(raster.NoDataValue); float extrusion = shadedRelief.Extrusion; float elevationFactor = shadedRelief.ElevationFactor; float lightIntensity = shadedRelief.LightIntensity; float ambientIntensity = shadedRelief.AmbientIntensity; FloatVector3 lightDirection = shadedRelief.GetLightDirection(); float[] aff = new float[6]; // affine coefficients converted to float format for (int i = 0; i < 6; i++) { aff[i] = Convert.ToSingle(raster.Bounds.AffineCoefficients[i]); } float[][] hillshade = new float[numRows][]; if (progressMeter != null) { progressMeter.BaseMessage = "Creating Shaded Relief"; } for (int row = 0; row < numRows; row++) { hillshade[row] = new float[numCols]; for (int col = 0; col < numCols; col++) { // 3D position vectors of three points to create a triangle. FloatVector3 v1 = new FloatVector3(0f, 0f, 0f); FloatVector3 v2 = new FloatVector3(0f, 0f, 0f); FloatVector3 v3 = new FloatVector3(0f, 0f, 0f); float val = Convert.ToSingle(getValue(row, col)); // Cannot compute polygon ... make the best guess) if (col >= numCols - 1 || row <= 0) { if (col >= numCols - 1 && row <= 0) { v1.Z = val; v2.Z = val; v3.Z = val; } else if (col >= numCols - 1) { v1.Z = Convert.ToSingle(getValue(row, col - 1)); // 3 - 2 v2.Z = Convert.ToSingle(getValue(row - 1, col)); // | / v3.Z = Convert.ToSingle(getValue(row - 1, col - 1)); // 1 * } else if (row <= 0) { v1.Z = Convert.ToSingle(getValue(row + 1, col)); // 3* 2 v2.Z = Convert.ToSingle(getValue(row, col + 1)); // | / v3.Z = val; // 1 } } else { v1.Z = val; // 3 - 2 v2.Z = Convert.ToSingle(getValue(row - 1, col + 1)); // | / v3.Z = Convert.ToSingle(getValue(row - 1, col)); // 1* } // Test for no-data values and don't calculate hillshade in that case if (v1.Z == noData || v2.Z == noData || v3.Z == noData) { hillshade[row][col] = -1; // should never be negative otherwise. continue; } // Apply the Conversion Factor to put elevation into the same range as lat/lon v1.Z = v1.Z * elevationFactor * extrusion; v2.Z = v2.Z * elevationFactor * extrusion; v3.Z = v3.Z * elevationFactor * extrusion; // Complete the vectors using the latitude/longitude coordinates v1.X = aff[0] + aff[1] * col + aff[2] * row; v1.Y = aff[3] + aff[4] * col + aff[5] * row; v2.X = aff[0] + aff[1] * (col + 1) + aff[2] * (row + 1); v2.Y = aff[3] + aff[4] * (col + 1) + aff[5] * (row + 1); v3.X = aff[0] + aff[1] * col + aff[2] * (row + 1); v3.Y = aff[3] + aff[4] * col + aff[5] * (row + 1); // We need two direction vectors in order to obtain a cross product FloatVector3 dir2 = FloatVector3.Subtract(v2, v1); // points from 1 to 2 FloatVector3 dir3 = FloatVector3.Subtract(v3, v1); // points from 1 to 3 FloatVector3 cross = FloatVector3.CrossProduct(dir3, dir2); // right hand rule - cross direction should point into page... reflecting more if light direction is in the same direction // Normalizing this vector ensures that this vector is a pure direction and won't affect the intensity cross.Normalize(); // Hillshade now has an "intensity" modifier that should be applied to the R, G and B values of the color found at each pixel. hillshade[row][col] = FloatVector3.Dot(cross, lightDirection) * lightIntensity + ambientIntensity; } if (progressMeter != null) { progressMeter.Next(); } } // Setting this indicates that a hillshade has been created more recently than characteristics have been changed. shadedRelief.HasChanged = false; return(hillshade); }
/// <summary> /// This code is empty, but can be overridden in subtypes. This can be used to set the data of this raster to the data of the original raster. /// </summary> /// <param name="original">Original raster to get the value from.</param> public virtual void SetData(IRaster original) { }
/// <inheritdoc/> public virtual void WriteBlock(IRaster blockValues, int xOff, int yOff, int xSize, int ySize) { // Implemented in subclass }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); //noDataValueArr = (System.Array)((IRasterProps)inrsBandsCoef).NoDataValue;//inrsBandsCoef int pBHeight = pPixelBlock.Height; int pBWidth = pPixelBlock.Width; IPnt pbSize = new PntClass(); pbSize.SetCoords(pBWidth, pBHeight); IPixelBlock3 outPb = (IPixelBlock3)myFunctionHelperCoef.Raster.CreatePixelBlock(pbSize); myFunctionHelperCoef.Read(pTlc, null, myFunctionHelperCoef.Raster, (IPixelBlock)outPb); int pBRowIndex = 0; int pBColIndex = 0; IPixelBlock3 ipPixelBlock = (IPixelBlock3)pPixelBlock; //System.Array[] pArr = new System.Array[outPb.Planes]; //for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) //{ // System.Array pixelValues = (System.Array)(outPb.get_PixelData(coefnBand)); // pArr[coefnBand] = pixelValues; //} for (int nBand = 0; nBand < pPixelBlock.Planes; nBand++) { System.Array outArr = (System.Array)ipPixelBlock.get_PixelData(nBand); rstPixelType pty = ipPixelBlock.get_PixelType(nBand); for (int i = pBRowIndex; i < pBHeight; i++) { for (int k = pBColIndex; k < pBWidth; k++) { float[] IntSlpArr = slopes[nBand]; double sumVls = IntSlpArr[0]; bool checkNoData = true; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { double slp = System.Convert.ToDouble(IntSlpArr[coefnBand + 1]); if (slp == 0) { continue; } //double noDataValue = System.Convert.ToDouble(noDataValueArr.GetValue(coefnBand)); object objPvl = outPb.GetVal(coefnBand, k, i); if (objPvl == null) { checkNoData = false; break; } else { double pixelValue = Convert.ToDouble(objPvl); sumVls += pixelValue * slp; } } if (checkNoData) { object nVl = rasterUtil.getSafeValue(sumVls, pty); outArr.SetValue(nVl, k, i); } } } ipPixelBlock.set_PixelData(nBand, outArr); } } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of Tobit Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
private static void PaintColorSchemeToBitmapT <T>(this IRaster raster, T noData, Func <int, int, T> getValue, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler) where T : struct, IEquatable <T>, IComparable <T> { if (raster == null) { throw new ArgumentNullException("raster"); } if (rasterSymbolizer == null) { throw new ArgumentNullException("rasterSymbolizer"); } if (bitmap == null) { throw new ArgumentNullException("bitmap"); } if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) { return; } BitmapData bmpData; var numRows = raster.NumRows; var numColumns = raster.NumColumns; var rect = new Rectangle(0, 0, numColumns, numRows); try { bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); } catch { var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.MemoryBmp); ms.Position = 0; bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); } // Prepare progress meter var pm = new ProgressMeter(progressHandler, SymbologyMessageStrings.DesktopRasterExt_PaintingColorScheme, numRows); if (numRows * numColumns < 100000) { pm.StepPercent = 50; } if (numRows * numColumns < 500000) { pm.StepPercent = 10; } if (numRows * numColumns < 1000000) { pm.StepPercent = 5; } var sets = GetColorSets <T>(rasterSymbolizer.Scheme.Categories); var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor); var alpha = Argb.ByteRange(Convert.ToInt32(rasterSymbolizer.Opacity * 255)); var ptr = bmpData.Scan0; for (var row = 0; row < numRows; row++) { for (var col = 0; col < numColumns; col++) { var val = getValue(row, col); Argb argb; if (val.Equals(noData)) { argb = noDataColor; } else { // Usually values are not random, so check neighboring previous cells for same color int?srcOffset = null; if (col > 0) { if (val.Equals(getValue(row, col - 1))) { srcOffset = Offset(row, col - 1, bmpData.Stride); } } if (srcOffset == null && row > 0) { if (val.Equals(getValue(row - 1, col))) { srcOffset = Offset(row - 1, col, bmpData.Stride); } } if (srcOffset != null) { argb = new Argb( Marshal.ReadByte(ptr, (int)srcOffset + 3), Marshal.ReadByte(ptr, (int)srcOffset + 2), Marshal.ReadByte(ptr, (int)srcOffset + 1), Marshal.ReadByte(ptr, (int)srcOffset)); } else { var color = GetColor(sets, val); argb = new Argb(alpha, color.R, color.G, color.B); } } var offset = Offset(row, col, bmpData.Stride); Marshal.WriteByte(ptr, offset, argb.B); Marshal.WriteByte(ptr, offset + 1, argb.G); Marshal.WriteByte(ptr, offset + 2, argb.R); Marshal.WriteByte(ptr, offset + 3, argb.A); } pm.CurrentValue = row; } pm.Reset(); if (rasterSymbolizer.IsSmoothed) { var mySmoother = new Smoother(bmpData.Stride, bmpData.Width, bmpData.Height, bmpData.Scan0, progressHandler); mySmoother.Smooth(); } bitmap.UnlockBits(bmpData); rasterSymbolizer.ColorSchemeHasUpdated = true; }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. System.Array noDataValueArr = (System.Array)((IRasterProps)pRaster).NoDataValue; float noDataVl = System.Convert.ToSingle(noDataValueArr.GetValue(0)); myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); noDataValueArr = (System.Array)((IRasterProps)inrsBandsCoef).NoDataValue;//inrsBandsCoef int pBHeight = pPixelBlock.Height; int pBWidth = pPixelBlock.Width; IPnt pbSize = new PntClass(); pbSize.SetCoords(pBWidth, pBHeight); IPixelBlock3 outPb = (IPixelBlock3)myFunctionHelperCoef.Raster.CreatePixelBlock(pbSize); myFunctionHelper.Read(pTlc, null, myFunctionHelperCoef.Raster, (IPixelBlock)outPb); int pBRowIndex = 0; int pBColIndex = 0; IPixelBlock3 ipPixelBlock = (IPixelBlock3)pPixelBlock; System.Array[] pArr = new System.Array[outPb.Planes]; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { System.Array pixelValues = (System.Array)(outPb.get_PixelData(coefnBand)); pArr[coefnBand] = pixelValues; } for (int nBand = 0; nBand < pPixelBlock.Planes; nBand++) { System.Array outArr = (System.Array)ipPixelBlock.get_PixelData(nBand); rstPixelType pty = ipPixelBlock.get_PixelType(nBand); for (int i = pBRowIndex; i < pBHeight; i++) { for (int k = pBColIndex; k < pBWidth; k++) { float[] IntSlpArr = slopes[nBand]; double sumVls = IntSlpArr[0]; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { double noDataValue = System.Convert.ToDouble(noDataValueArr.GetValue(coefnBand)); double pixelValue = Convert.ToDouble(pArr[coefnBand].GetValue(k, i)); if (rasterUtil.isNullData(pixelValue, noDataValue)) { sumVls = noDataVl; break; } double slp = System.Convert.ToDouble(IntSlpArr[coefnBand + 1]); sumVls += pixelValue * slp; } if (sumVls < censored) { sumVls = censored; } object newVl = rasterUtil.getSafeValue(sumVls, pty); outArr.SetValue(newVl, k, i); } } ipPixelBlock.set_PixelData(nBand, outArr); } } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of Tobit Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
/// <summary> /// Creates a bitmap from this raster using the specified rasterSymbolizer. /// </summary> /// <param name="raster">The raster to draw to a bitmap.</param> /// <param name="rasterSymbolizer">The raster symbolizer to use for assigning colors.</param> /// <param name="bitmap">This must be an Format32bbpArgb bitmap that has already been saved to a file so that it exists.</param> /// <param name="progressHandler">The progress handler to use.</param> /// <exception cref="ArgumentNullException">rasterSymbolizer cannot be null</exception> public static void DrawToBitmap(this IRaster raster, IRasterSymbolizer rasterSymbolizer, Bitmap bitmap, IProgressHandler progressHandler = null) { if (raster == null) { throw new ArgumentNullException("raster"); } if (rasterSymbolizer == null) { throw new ArgumentNullException("rasterSymbolizer"); } if (bitmap == null) { throw new ArgumentNullException("bitmap"); } if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) { return; } BitmapData bmpData; var rect = new Rectangle(0, 0, raster.NumColumns, raster.NumRows); try { bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); } catch (Exception) { // if they have not saved the bitmap yet, it can cause an exception var ms = new MemoryStream(); bitmap.Save(ms, ImageFormat.Bmp); ms.Position = 0; bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb); } var numRows = raster.NumRows; var numColumns = raster.NumColumns; // Prepare progress meter if (progressHandler == null) { progressHandler = raster.ProgressHandler; } var pm = new ProgressMeter(progressHandler, "Drawing to Bitmap", numRows); if (numRows * numColumns < 100000) { pm.StepPercent = 50; } if (numRows * numColumns < 500000) { pm.StepPercent = 10; } if (numRows * numColumns < 1000000) { pm.StepPercent = 5; } DrawToBitmap(raster, rasterSymbolizer, bmpData.Scan0, bmpData.Stride, pm); bitmap.UnlockBits(bmpData); rasterSymbolizer.ColorSchemeHasUpdated = true; }
/// <summary> /// Runs the selected density operations on the input feature class. /// </summary> /// <param name="pFC"></param> /// <returns></returns> private IRaster Density(IFeatureClass pFC) { IRaster pRaster = null; try { IDensityOp pDensityOp = new RasterDensityOpClass(); //create a feature class descriptor to specify a field IFeatureClassDescriptor pFCD = new FeatureClassDescriptorClass(); if (m_sField != "None") { pFCD.Create(pFC, null, m_sField); } else { pFCD.Create(pFC, null, null); } //run the density op //set the output resolution //make sure this scale factor is always in right units. object oScaleFactor = 1; switch (m_sDensityUnits + m_sMapUnits) { case "per square km" + "Meter": oScaleFactor = 1000; break; case "per square mile" + "Meter": oScaleFactor = 1609.344; break; case "per square mile" + "Foot_US": case "per square mile" + "Foot": oScaleFactor = 5280; break; case "per square km" + "Foot_US": case "per square km" + "Foot": oScaleFactor = 3280.84; break; case "per square nm" + "Meter": oScaleFactor = 1852; break; case "per square nm" + "Foot_US": case "per square nm" + "Foot": oScaleFactor = 6076.12; break; } object oRadius = m_dRadius; IGeoDataset pOutRaster = null; if (m_sDensityType == "Kernel") { pOutRaster = pDensityOp.KernelDensity((IGeoDataset)pFCD, ref oRadius, ref oScaleFactor); } else { esriGeometryType thisType = pFC.ShapeType; if (thisType == esriGeometryType.esriGeometryPolyline) { pOutRaster = pDensityOp.LineDensity((IGeoDataset)pFCD, ref oRadius, ref oScaleFactor); } else if (thisType == esriGeometryType.esriGeometryPoint) { IRasterNeighborhood pNbr = new RasterNeighborhoodClass(); if (m_sRadiusType == "Cells") { pNbr.SetCircle(m_dRadius, esriGeoAnalysisUnitsEnum.esriUnitsCells); } else { pNbr.SetCircle(m_dRadius, esriGeoAnalysisUnitsEnum.esriUnitsMap); } pOutRaster = pDensityOp.PointDensity((IGeoDataset)pFCD, pNbr, ref oScaleFactor); //ref oCellSize); } } pRaster = (IRaster)pOutRaster; //check output spatial reference IRasterProps pRProps = (IRasterProps)pRaster; pRProps.SpatialReference = m_pLayerSR; //save the raster to disk IWorkspace pOutWS = clsStatic.OpenWorkspace(m_sOutPath); ISaveAs pSaveAs = (ISaveAs)pRaster; if (pSaveAs.CanSaveAs("GRID") == true) { pSaveAs.SaveAs(pFC.AliasName + "_" + m_sOutName, pOutWS, "GRID"); } IMap pMap = ArcMap.Document.FocusMap; //calculate raster stats IRasterDataset pRDS = clsStatic.OpenRasterDataset(m_sOutPath, pFC.AliasName + "_" + m_sOutName); CalcStats(pRDS); //add the layer to the map IRasterLayer pRL = clsStatic.RasterDataset2RasterLayer(m_sOutPath, pFC.AliasName + "_" + m_sOutName, false, pMap); IRgbColor pRGB1 = new RgbColorClass(); IRgbColor pRGB2 = new RgbColorClass(); pRGB2.Blue = 0; pRGB2.Green = 0; pRGB2.Red = 255; pRGB1.Blue = 255; pRGB1.Green = 0; pRGB1.Red = 0; //pRL.CreateFromRaster(pRaster); CreateRasterStretchRenderer(pRL, pRGB1, pRGB2); pMap.AddLayer(pRL); return(pRaster); } catch (Exception ex) { clsStatic.ShowErrorMessage(ex.ToString()); } return(pRaster); }
/// <summary> /// Executes the ReSample Opaeration tool programmatically /// Ping deleted the static property for external testing. /// </summary> /// <param name="input1">The input raster.</param> /// <param name="newCellHeight">The size of the cell's hight.</param> /// <param name="newCellWidth">The size of the cell's width.</param> /// <param name="output">The output raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>Boolean, true if the method was successful.</returns> public bool Execute(IRaster input1, double newCellHeight, double newCellWidth, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || newCellWidth == 0 || output == null) { return(false); } Extent envelope = input1.Bounds.Extent; // Calculate new number of columns and rows int noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / newCellWidth)); int noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / newCellHeight)); int previous = 0; // create output raster output = Raster.CreateRaster(output.Filename, string.Empty, noOfCol, noOfRow, 1, input1.DataType, new[] { string.Empty }); RasterBounds bound = new(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; // Loop throug every cell for new value int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { // Projet the cell position to Map Coordinate cellCenter = output.CellToProj(i, j); var index1 = input1.ProjToCell(cellCenter); double val; if (index1.Row <= input1.EndRow && index1.Column <= input1.EndColumn && index1.Row > -1 && index1.Column > -1) { val = input1.Value[index1.Row, index1.Column] == input1.NoDataValue ? output.NoDataValue : input1.Value[index1.Row, index1.Column]; } else { val = output.NoDataValue; } output.Value[i, j] = val; if (cancelProgressHandler.Cancel) { return(false); } } int current = Convert.ToInt32(Math.Round(i * 100D / max)); // only update when increment in persentage if (current > previous) { cancelProgressHandler.Progress(current, current + TextStrings.progresscompleted); } previous = current; } output.Save(); return(true); }
/// <summary> /// This will sample randomly from the raster, preventing duplicates. /// If the sampleSize is larger than this raster, this returns all of the values from the raster. /// If a "Sample" has been prefetched and stored in the Sample array, then this will return that. /// </summary> /// <param name="raster">The raster to obtain the values from.</param> /// <param name="sampleSize">Number of values to get.</param> /// <returns>List of random double values contained in the raster.</returns> public static List <double> GetRandomValues(this IRaster raster, int sampleSize) { if (raster.Sample != null) { return(raster.Sample.ToList()); } int numRows = raster.NumRows; int numCols = raster.NumColumns; List <double> result = new List <double>(); double noData = raster.NoDataValue; if (numRows * numCols < sampleSize) { for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { double val = raster.Value[row, col]; if (val != noData) { result.Add(raster.Value[row, col]); } } } return(result); } Random rnd = new Random(DateTime.Now.Millisecond); if (numRows * (long)numCols < (long)sampleSize * 5 && numRows * (long)numCols < int.MaxValue) { // When the raster is only just barely larger than the sample size, // we want to prevent lots of repeat guesses that fail (hit the same previously sampled values). // We create a copy of all the values and sample from this reservoir while removing sampled values. List <double> resi = new List <double>(); for (int row = 0; row < numRows; row++) { for (int col = 0; col < numCols; col++) { double val = raster.Value[row, col]; if (val != noData) { resi.Add(val); } } } //int count = numRows * numCols; //this could failed if there's lot of noDataValues long longcount = raster.NumValueCells; int count = numRows * numCols; if (count < int.MaxValue) { count = (int)longcount; } for (int i = 0; i < sampleSize; i++) { if (resi.Count == 0) { break; } int indx = rnd.Next(count); result.Add(resi[indx]); resi.RemoveAt(indx); count--; } raster.Sample = result; return(result); } // Use a HashSet here, because it has O(1) lookup for preventing duplicates HashSet <long> exclusiveResults = new HashSet <long>(); int remaining = sampleSize; while (remaining > 0) { int row = rnd.Next(numRows); int col = rnd.Next(numCols); long index = row * numCols + col; if (exclusiveResults.Contains(index)) { continue; } exclusiveResults.Add(index); remaining--; } // Sorting is O(n ln(n)), but sorting once is better than using a SortedSet for previous lookups. List <long> sorted = exclusiveResults.ToList(); sorted.Sort(); // Sorted values are much faster to read than reading values in at random, since the file actually // is reading in a whole line at a time. If we can get more than one value from a line, then that // is better than getting one value, discarding the cache and then comming back later for the value // next to it. result = raster.GetValues(sorted); raster.Sample = result; return(result); }
/// <summary> /// Executes the Erase Opaeration tool programmatically /// Ping Yang deleted static for external testing 01/2010. /// </summary> /// <param name="input1">The original input raster.</param> /// <param name="input2">The second input raster.</param> /// <param name="output">The output raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>Boolean, true if the method was successful.</returns> public bool Execute(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { RasterMagic magic = new(Operation); return(magic.RasterMath(input1, input2, output, cancelProgressHandler)); }
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"); }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="ras">The dem Raster(Grid file).</param> /// <param name="zFactor">The scaler factor</param> /// <param name="poly">The flow poly shapefile path.</param> /// <param name="output">The resulting DEM of slopes</param> /// <param name="cancelProgressHandler">The progress handler.</param> public bool Execute( IRaster ras, double zFactor, IFeatureSet poly, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || poly == null || output == null) { return(false); } output.FeatureType = poly.FeatureType; foreach (IFeature f in poly.Features) { output.Features.Add(f); } output.DataTable.Columns.Add("FID", typeof(int)); output.DataTable.Columns.Add(TextStrings.AveSlope, typeof(Double)); IRaster slopeGrid = new Raster { DataType = ras.DataType, Bounds = ras.Bounds }; // FeatureSet polyShape = new FeatureSet(); int previous = 0; if (Slope(ref ras, zFactor, false, ref slopeGrid, cancelProgressHandler) == false) { return(false); } int shapeCount = output.Features.Count; int[] areaCount = new int[shapeCount]; double[] areaTotal = new double[shapeCount]; double[] areaAve = new double[shapeCount]; double dxHalf = slopeGrid.CellWidth / 2; double dyHalf = slopeGrid.CellHeight / 2; // check whether those two envelope are intersect if (ras.Extent.Intersects(output.Extent) == false) { return(false); } RcIndex start = slopeGrid.ProjToCell(output.Extent.MinX, output.Extent.MaxY); RcIndex stop = slopeGrid.ProjToCell(output.Extent.MaxX, output.Extent.MinY); int rowStart = start.Row; int colStart = start.Column; int rowStop = stop.Row; int colStop = stop.Column; for (int row = rowStart - 1; row < rowStop + 1; row++) { int current = Convert.ToInt32((row - rowStart + 1) * 100.0 / (rowStop + 1 - rowStart + 1)); // only update when increment in percentage if (current > previous + 5) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } for (int col = colStart - 1; col < colStop + 1; col++) { Coordinate cent = slopeGrid.CellToProj(row, col); double xCent = cent.X; double yCent = cent.Y; for (int shpindx = 0; shpindx < output.Features.Count; shpindx++) { IFeature tempFeat = output.Features[shpindx]; Point pt1 = new Point(xCent, yCent); Point pt2 = new Point(xCent - dxHalf, yCent - dyHalf); Point pt3 = new Point(xCent + dxHalf, yCent - dyHalf); Point pt4 = new Point(xCent + dxHalf, yCent + dyHalf); Point pt5 = new Point(xCent - dxHalf, yCent + dyHalf); if ((((!tempFeat.Geometry.Covers(pt1) && !tempFeat.Geometry.Covers(pt2)) && !tempFeat.Geometry.Covers(pt3)) && !tempFeat.Geometry.Covers(pt4)) && !tempFeat.Geometry.Covers(pt5)) { continue; } areaCount[shpindx]++; areaTotal[shpindx] += slopeGrid.Value[row, col] / 100; if (cancelProgressHandler.Cancel) { return(false); } } } } for (int shpindx = 0; shpindx < output.Features.Count; shpindx++) { if (areaCount[shpindx] == 0) { areaAve[shpindx] = 0; } else { areaAve[shpindx] = areaTotal[shpindx] / areaCount[shpindx]; } output.Features[shpindx].DataRow["FID"] = shpindx; output.Features[shpindx].DataRow[TextStrings.AveSlope] = areaAve[shpindx]; } poly.Close(); slopeGrid.Close(); output.SaveAs(output.Filename, true); return(true); }
private static void DrawToBitmapT <T>(IRaster raster, T noData, Func <int, int, T> getValue, Func <int, byte> getByte, Action <int, byte> setByte, IRasterSymbolizer rasterSymbolizer, int stride, ProgressMeter pm) where T : struct, IEquatable <T>, IComparable <T> { if (raster == null) { throw new ArgumentNullException("raster"); } if (rasterSymbolizer == null) { throw new ArgumentNullException("rasterSymbolizer"); } if (rasterSymbolizer.Scheme.Categories == null || rasterSymbolizer.Scheme.Categories.Count == 0) { return; } float[][] hillshade = null; if (rasterSymbolizer.ShadedRelief.IsUsed) { pm.BaseMessage = "Calculating Shaded Relief"; hillshade = rasterSymbolizer.HillShade ?? raster.CreateHillShadeT(getValue, rasterSymbolizer.ShadedRelief, pm); } pm.BaseMessage = "Calculating Colors"; var sets = GetColorSets <T>(rasterSymbolizer.Scheme.Categories); var noDataColor = Argb.FromColor(rasterSymbolizer.NoDataColor); for (int row = 0; row < raster.NumRows; row++) { for (int col = 0; col < raster.NumColumns; col++) { var value = getValue(row, col); Argb argb; if (value.Equals(noData)) { argb = noDataColor; } else { // Usually values are not random, so check neighboring previous cells for same color int?srcOffset = null; if (col > 0) { if (value.Equals(getValue(row, col - 1))) { srcOffset = Offset(row, col - 1, stride); } } if (srcOffset == null && row > 0) { if (value.Equals(getValue(row - 1, col))) { srcOffset = Offset(row - 1, col, stride); } } if (srcOffset != null) { argb = new Argb(getByte((int)srcOffset + 3), getByte((int)srcOffset + 2), getByte((int)srcOffset + 1), getByte((int)srcOffset)); } else { argb = GetColor(sets, value); } } if (hillshade != null) { if (hillshade[row][col] == -1 || float.IsNaN(hillshade[row][col])) { argb = new Argb(argb.A, noDataColor.R, noDataColor.G, noDataColor.B); } else { var red = (int)(argb.R * hillshade[row][col]); var green = (int)(argb.G * hillshade[row][col]); var blue = (int)(argb.B * hillshade[row][col]); argb = new Argb(argb.A, red, green, blue); } } var offset = Offset(row, col, stride); setByte(offset, argb.B); setByte(offset + 1, argb.G); setByte(offset + 2, argb.R); setByte(offset + 3, argb.A); } pm.Next(); } }
/// <summary> /// Executes the slope generation raster. /// </summary> /// <param name="ras">The input altitude raster.</param> /// <param name="inZFactor">The multiplicitive scaling factor for elveation.</param> /// <param name="slopeInPercent">Boolean that is true if the slope values should be returned as percentages.</param> /// <param name="result">The output slope raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>Boolean, true if the method was successful.</returns> private static bool Slope( ref IRaster ras, double inZFactor, bool slopeInPercent, ref IRaster result, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (ras == null || result == null) { return(false); } try { int noOfCol = ras.NumColumns; int noOfRow = ras.NumRows; // Create the new raster with the appropriate dimensions IRaster temp = Raster.CreateRaster( "SlopeRaster.bgd", string.Empty, noOfCol, noOfRow, 1, typeof(double), new[] { string.Empty }); temp.NoDataValue = ras.NoDataValue; temp.Bounds = ras.Bounds; for (int i = 0; i < temp.NumRows; i++) { for (int j = 0; j < temp.NumColumns; j++) { if (i > 0 && i < temp.NumRows - 1 && j > 0 && j < temp.NumColumns - 1) { double z1 = ras.Value[i - 1, j - 1]; double z2 = ras.Value[i - 1, j]; double z3 = ras.Value[i - 1, j + 1]; double z4 = ras.Value[i, j - 1]; double z5 = ras.Value[i, j + 1]; double z6 = ras.Value[i + 1, j - 1]; double z7 = ras.Value[i + 1, j]; double z8 = ras.Value[i + 1, j + 1]; // 3rd Order Finite Difference slope algorithm double dZdX = inZFactor * ((z3 - z1) + 2 * (z5 - z4) + (z8 - z6)) / (8 * ras.CellWidth); double dZdY = inZFactor * ((z1 - z6) + 2 * (z2 - z7) + (z3 - z8)) / (8 * ras.CellHeight); double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI); // change to radious and in persentage if (slopeInPercent) { slope = Math.Tan(slope * Math.PI / 180) * 100; } temp.Value[i, j] = slope; if (cancelProgressHandler.Cancel) { return(false); } } else { temp.Value[i, j] = temp.NoDataValue; } if (cancelProgressHandler.Cancel) { return(false); } } } result = temp; if (result.IsFullyWindowed()) { result.Save(); return(true); } return(false); } catch (Exception ex) { // throw new SystemException("Error in Slope: ", ex); throw new SystemException(ex.ToString()); } }
/// <summary> /// Get the envelop's envelop. /// </summary> /// <param name="raster"></param> /// <returns></returns> public static Envelope FromRaster(IRaster raster) { IRasterProps rasterProps = (IRasterProps)raster; return(new Envelope(0, rasterProps.Width - 1, 0, rasterProps.Height - 1)); }
private void btnGO_Click(object sender, EventArgs e) { string fileName; string shpFile; int startX, endX; string shpDir; if (bDataPath == true) { fileName = txtOutData.Text; shpDir = fileName.Substring(0, fileName.LastIndexOf("\\")); startX = fileName.LastIndexOf("\\"); endX = fileName.Length; shpFile = fileName.Substring(startX + 1, endX - startX - 1); } else { shpDir = txtOutData.Text; shpFile = "象素统计栅格"; } try { IRasterBandCollection pLocalCollection = new RasterClass(); ILocalOp pLocalOp = new RasterLocalOpClass(); for (int i = 0; i <= listBoxAddedLayer.Items.Count - 1; i++) { IRaster pInRaster = GetRSLyrFromMapLyr(listBoxAddedLayer.Items[i].ToString().Trim()); IRasterDataset pRasterGeo = pInRaster as IRasterDataset; pLocalCollection.AppendBand(pRasterGeo as IRasterBand); } string sMethod = comboBoxMethod.Text; IRasterLayer pRasterLayer = new RasterLayerClass(); IRaster pOutRaster = null; switch (sMethod) { case "Majority": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMajority) as IRaster; break; case "Maximum": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMaximum) as IRaster; break; case "Mean": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMean) as IRaster; break; case "Median": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMedian) as IRaster; break; case "Minimum": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMinimum) as IRaster; break; case "Minority": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsMinority) as IRaster; break; case "Range": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsRange) as IRaster; break; case "Standard Deviation": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsStd) as IRaster; break; case "Sum": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsSum) as IRaster; break; case "Variety": pOutRaster = pLocalOp.LocalStatistics(pLocalCollection as IGeoDataset, esriGeoAnalysisStatisticsEnum.esriGeoAnalysisStatsVariety) as IRaster; break; } pRasterLayer.Name = "象素统计栅格"; Utility.ConvertRasterToRsDataset(shpDir, pOutRaster, "象素统计栅格"); pRasterLayer = Utility.SetStretchRenderer(pOutRaster); pMainFrm.getMapControl().AddLayer(pRasterLayer, 0); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } }
private void button2_Click(object sender, EventArgs e) { IReclassOp reCla; reCla = new RasterReclassOp() as IReclassOp; //符号化 IRemap pRemap; INumberRemap pSRemap; pSRemap = new NumberRemap() as INumberRemap; for (int i = 1; i <= Convert.ToInt32(comboBox2.SelectedItem.ToString()); i++) { try { string str; str = dataGridView1.Rows[i - 1].Cells[0].Value.ToString(); float fValue, tValue; int p; p = str.LastIndexOf("-"); fValue = Convert.ToSingle(str.Substring(0, p)); tValue = Convert.ToSingle(str.Substring(p + 1, str.Length - p - 1)); pSRemap.MapRange(fValue, tValue, Convert.ToInt32(dataGridView1.Rows[i - 1].Cells[1].Value)); } catch { MessageBox.Show("Error!"); return; } } pRemap = (IRemap)pSRemap; //获取栅格图层 IRasterLayer play = (IRasterLayer)GetLayerByName(comboBox1.SelectedItem.ToString()); IRaster pRster = play.Raster; IGeoDataset pOutputRaster = null; try { pOutputRaster = reCla.ReclassByRemap((IGeoDataset)pRster, pRemap, true); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } try { IWorkspaceFactory pWKSF = new RasterWorkspaceFactoryClass(); IWorkspace pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(textBox1.Text), 0); ISaveAs pSaveAs = pOutputRaster as ISaveAs; pSaveAs.SaveAs(System.IO.Path.GetFileName(textBox1.Text), pWorkspace, "TIFF"); } catch (Exception ex) { MessageBox.Show(ex.ToString()); } IRasterLayer pRlayer = new RasterLayer(); pRlayer.CreateFromRaster((IRaster)pOutputRaster); pRlayer.Name = System.IO.Path.GetFileName(textBox1.Text); global.p2DMap.AddLayer(pRlayer); global.p3DMap.Scene.AddLayer(pRlayer); mainForm.axTOCControl1.Update(); mainForm.axTOCControl2.Update(); }
public bool Execute(IFeatureSet input, string zField, double cellSize, double power, int neighborType, int pointCount, double distance, IRaster output) { if (input == null || output == null) { return(false); } if (cellSize == 0) { cellSize = input.Extent.Width / 255; } int numColumns = Convert.ToInt32(Math.Round(input.Extent.Width / cellSize)); int numRows = Convert.ToInt32(Math.Round(input.Extent.Height / cellSize)); output = Raster.CreateRaster(output.Filename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty });//error output.CellHeight = cellSize; output.CellWidth = cellSize; output.Xllcenter = input.Extent.MinX + (cellSize / 2); output.Yllcenter = input.Extent.MinY + (cellSize / 2); progress.Maximum = numColumns * numRows; progress.Value = 0; #region 构建KD树 List <KD_Point> lists = new List <KD_Point>();//构建KD-Tree的点集列表 foreach (var p in input.Features) { KD_Point kd = new KD_Point(p.BasicGeometry.Coordinates[0].X, p.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(p.DataRow[zField])); lists.Add(kd); } KDTree kDTree = new KDTree(); kDTree.CreateByPointList(lists); /* * double gdistance = input.Features[0].BasicGeometry.Coordinates[0].Distance(input.Features[1].BasicGeometry.Coordinates[0]); * double tdistance = Math.Sqrt(Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].X- input.Features[1].BasicGeometry.Coordinates[0].X, 2) + Math.Pow(input.Features[0].BasicGeometry.Coordinates[0].Y- input.Features[1].BasicGeometry.Coordinates[0].Y, 2)); * Console.WriteLine("gdistance: " + gdistance + " , tdistance: " + tdistance); */ #endregion if (neighborType == 0)//固定数目 { for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { //IDW算法的分子和分母 double top = 0; double bottom = 0; if (pointCount > 0) { Coordinate coord = output.CellToProj(y, x); KD_Point kD_Point = new KD_Point(coord.X, coord.Y); List <KD_Point> points = kDTree.K_Nearest(kD_Point, pointCount); //Console.WriteLine("KDTree points count: " + points.Count); for (int i = 0; i < points.Count; i++) { if (points[i] != null) { Coordinate kd = new Coordinate(points[i].X, points[i].Y); double distanceToCell = kd.Distance(coord); if (distanceToCell <= distance || distance == 0) { //Console.WriteLine(points[i].Z); if (power == 2) { top += (1 / (distanceToCell * distanceToCell)) * points[i].Z; bottom += 1 / (distanceToCell * distanceToCell); } else { top += (1 / Math.Pow(distanceToCell, power)) * points[i].Z; bottom += 1 / Math.Pow(distanceToCell, power); } } } } } else { for (int i = 0; i < input.Features.Count; i++) { Coordinate cellCenter = output.CellToProj(y, x); //Coordinate coord = output.CellToProj(y, x); var featurePt = input.Features[i]; if (featurePt != null) { double distanceToCell = cellCenter.Distance(featurePt.BasicGeometry.Coordinates[0]); if (distanceToCell <= distance || distance == 0) { try { Convert.ToDouble(featurePt.DataRow[zField]); } catch { continue; } if (power == 2) { top += (1 / (distanceToCell * distanceToCell)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += 1 / (distanceToCell * distanceToCell); } else { top += (1 / Math.Pow(distanceToCell, power)) * Convert.ToDouble(featurePt.DataRow[zField]); bottom += 1 / Math.Pow(distanceToCell, power); } } } } } //Console.WriteLine("top: " + top + " , bottom: " +bottom); output.Value[y, x] = top / bottom; //Console.WriteLine(y + " , " + x + " : " + output.Value[y, x]); //richText.Text += output.Value[y, x] + "\n"; progress.Value++; } } } output.Save(); return(true); }
/// <summary> /// Creates a new instance of a MapRasterLayer and the specified image data to use for rendering it. /// </summary> public MapRasterLayer(IRaster baseRaster, ImageData baseImage) : base(baseRaster) { base.LegendText = Path.GetFileNameWithoutExtension(baseRaster.Filename); BitmapGetter = baseImage; }
/// <summary> /// Occurs when this command is clicked /// </summary> public override void OnClick() { try { if (m_application == null) { return; } IDocument document = m_application.Document; ISxDocument sxDocument = (ISxDocument)(document); if (sxDocument != null) { m_scene = sxDocument.Scene; } if (m_scene == null) { return; } activeView = m_scene as IActiveView; //有图层选图层 if (m_scene.LayerCount == 0) { return; } //选择基准面 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, true, "选择自定义表面") == false) { return; } //QI IRasterLayer baseRasterLayer = m_scene.Layer[SelectedLyrIndex[0]] as IRasterLayer; //不管选多少个只选第一个 if (baseRasterLayer == null) { throw new ArgumentNullException("自定义表面RasterLayer转换失败,为空。"); } IRaster raster = baseRasterLayer.Raster; if (raster == null) { throw new ArgumentNullException("自定义表面Raster转换失败,为空。"); } IRasterSurface rasterSurface = new RasterSurfaceClass(); rasterSurface.PutRaster(raster, 0); ISurface surface = rasterSurface as ISurface; //选择图层 if (Common.SelectLayer(m_scene.Layers, out SelectedLyrIndex, false, "选择要进行偏移的图层") == false) { return; } //选择倍数 NumSelect MultiNS = new NumSelect("输入夸大倍数", true); if (MultiNS.ShowDialog() != DialogResult.OK) { return; } double Multiplier = MultiNS.Result; //选择偏移量 NumSelect NS = new NumSelect(); if (NS.ShowDialog() != DialogResult.OK) { return; } double Offset = NS.Result; bool DisableCache = NS.DisableCache; //Create a CancelTracker. ITrackCancel pTrackCancel = new CancelTrackerClass(); //Create the ProgressDialog. This automatically displays the dialog IProgressDialogFactory pProgDlgFactory = new ProgressDialogFactoryClass(); IProgressDialog2 pProDlg = pProgDlgFactory.Create(pTrackCancel, m_application.hWnd) as IProgressDialog2; pProDlg.CancelEnabled = true; pProDlg.Title = "正在进行自定义表面设置及偏移调整"; pProDlg.Description = "设置中,请稍候..."; pProDlg.Animation = esriProgressAnimationTypes.esriProgressSpiral; IStepProgressor pStepPro = pProDlg as IStepProgressor; pStepPro.MinRange = 0; pStepPro.MaxRange = SelectedLyrIndex.Count; pStepPro.StepValue = 1; pStepPro.Message = "初始化中..."; bool bCont = true; //对每一个选中的图层进行操作 for (int i = 0; i < SelectedLyrIndex.Count; i++) { //m_application.StatusBar.set_Message(0, i.ToString()); pStepPro.Message = "已完成(" + i.ToString() + "/" + SelectedLyrIndex.Count.ToString() + ")"; bCont = pTrackCancel.Continue(); if (!bCont) { break; } //选中一个栅格图层 IRasterLayer rasterLayer = m_scene.Layer[SelectedLyrIndex[i]] as IRasterLayer; if (rasterLayer == null) { pStepPro.Message = "选中的图层非栅格图层..."; continue; } I3DProperties p3DProperties = null; ILayerExtensions layerExtensions = rasterLayer as ILayerExtensions; //遍历LayerExtensions找到I3DProperties for (int j = 0; j < layerExtensions.ExtensionCount; j++) { if (layerExtensions.get_Extension(j) is I3DProperties) { p3DProperties = layerExtensions.get_Extension(j) as I3DProperties; } } //设置I3DProperties p3DProperties.ZFactor = Multiplier; //系数 p3DProperties.BaseOption = esriBaseOption.esriBaseSurface; //基准面浮动 p3DProperties.BaseSurface = surface; //基准面 p3DProperties.OffsetExpressionString = Offset.ToString(); //偏移常量 if (DisableCache) { p3DProperties.RenderMode = esriRenderMode.esriRenderImmediate; //直接从文件渲染 p3DProperties.RenderVisibility = esriRenderVisibility.esriRenderWhenStopped; //停止导航时渲染 } p3DProperties.Apply3DProperties(rasterLayer); } pProDlg.HideDialog(); //========================================== //刷新,不起作用 if (activeView == null) { throw new Exception("活动视图为空! "); } if (m_sceneHookHelper.ActiveViewer == null) { throw new Exception("无活动视图!"); } activeView.Refresh(); m_sceneHookHelper.ActiveViewer.Redraw(true); //========================================== } catch (Exception err) { MessageBox.Show(err.ToString()); } }