//Execute the drop of two cells private double Drop(RasterPixel rp1, RasterPixel rp2) //rp1 is the middle pixel. { Coordinate coor1 = ExecuteRaster.CellToProj(rp1.Row, rp1.Column); Coordinate coor2 = ExecuteRaster.CellToProj(rp2.Row, rp2.Column); double distance = coor1.Distance(coor2); double change_z = rp1.Value - rp2.Value; double drop = change_z / distance; return(drop); }
public bool Excute(string outputFilename, Extent extent, double cellSize) { int numColumns = (int)(extent.Width / cellSize); int numRows = (int)(extent.Height / cellSize); for (int i = 0; i < DIRECTION_COUNT; i++) { IRaster output = Raster.CreateRaster( outputFilename, string.Empty, numColumns, numRows, 1, typeof(double), new[] { string.Empty }); output.Extent = extent; output.Projection = DotSpatial.Projections.ProjectionInfo.FromEpsgCode(4326); for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { Coordinate cellCenter = output.CellToProj(y, x); var nearestSeg = segmentationRTree.Query(new Envelope(cellCenter)); for (int j = 0; j < nearestSeg.Count; j++) { GPSSegmentation gs = nearestSeg[j] as GPSSegmentation; if (GetIndexOfDirection(gs.Angle) == i) { //do something } } } } } return(false); }
/// <summary> /// Calculates the snow-covered area, if the raster is Decimal Degrees (WGS84) and /// the z-units are millimeters /// </summary> /// <param name="cRaster">the Snow Water Equivalent raster with units in mm</param> /// /// <returns>a list of 2 values. First value is snow-covered area. /// second value is total area. Units of area are m^2.</returns> public List <double> CalculateAreaForLatLon(IRaster cRaster) { //area in meters squared double snow_area_m2 = 0; double total_area_m2 = 0; //our raster is in decimal degrees (Lat/Lon). In this case //the cell width changes with latitude! //cell height (this is same for all rows) double cellHeight_m = CalculateCellHeight(cRaster.CellHeight); for (int row = 0; row < cRaster.NumRows; row++) { //cell width for the row depends on latitude Coordinate lonLat = cRaster.CellToProj(0, row); double lat = lonLat.Y; double cellWidth_m = CalculateCellWidth(cRaster.CellWidth, lat); for (int col = 0; col < cRaster.NumColumns; col++) { //SWE in millimeters double cellValue_mm = cRaster.Value[row, col]; //if cellValue is more than zero then there is some snow in the cell. if (cellValue_mm > 0) { double cellArea_m2 = cellHeight_m * cellWidth_m; //add it to the total area snow_area_m2 += cellArea_m2; } //for every cell, we add cell area to total area total_area_m2 += (cellHeight_m * cellWidth_m); } } List <double> result = new List <double>(); result.Add(snow_area_m2); result.Add(total_area_m2); return(result); }
/// <summary> /// Calculates the volume, if the raster is Decimal Degrees (WGS84) and /// the z-units are millimeters /// </summary> /// <param name="cRaster">the Snow Water Equivalent raster with units in mm</param> /// <returns>the snow water volume in cubic meters</returns> private double CalculateVolumeForLatLon(IRaster cRaster) { //volume in cubic meters double volume_m3 = 0; //our raster is in decimal degrees (Lat/Lon). In this case //the cell width changes with latitude! //cell height (this is same for all rows) double cellHeight_m = CalculateCellHeight(cRaster.CellHeight); for (int row = 0; row < cRaster.NumRows; row++) { //cell width for the row depends on latitude Coordinate lonLat = cRaster.CellToProj(0, row); double lat = lonLat.Y; double cellWidth_m = CalculateCellWidth(cRaster.CellWidth, lat); for (int col = 0; col < cRaster.NumColumns; col++) { //SWE in millimeters double cellValue_mm = cRaster.Value[row, col]; //set any NoData to Zero if (cellValue_mm < 0) { cellValue_mm = 0; } //SWE in meters double cellValue_m = cellValue_mm / 1000.0; //Snow Volume in cubic meters double cellVolume_m3 = cellValue_m * cellHeight_m * cellWidth_m; //Add the cell volume to the total volume volume_m3 += cellVolume_m3; } } return(volume_m3); }
/// <summary> /// Executes the Erase Opaeration tool programaticaly. /// Ping deleted static for external testing 01/2010 /// </summary> /// <param name="input1">The input raster.</param> /// <param name="input2">The input raster.</param> /// <param name="output">The output raster.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns></returns> public bool Execute(IRaster input1, IFeatureSet input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } double cellWidth = input1.CellWidth; double cellHeight = input1.CellHeight; //Calculate the Intersect Envelope IEnvelope envelope1 = input1.Bounds.Envelope; IEnvelope envelope2 = input2.Envelope; envelope1 = envelope1.Intersection(envelope2); int noOfCol = Convert.ToInt32(envelope1.Height / cellHeight); int noOfRow = Convert.ToInt32(envelope1.Width / cellWidth); //create output raster output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, typeof(int), new[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope1); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex v1; // MapWindow.Analysis.Topology.Algorithm.PointLocator pointLocator1 = new MapWindow.Analysis.Topology.Algorithm.PointLocator(); 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); //test if the coordinate is inside of the polygon bool isInside = false; IFeature pointFeat = new Feature(new Point(cellCenter)); foreach (IFeature f in input2.Features) { if (f.Contains(pointFeat)) { //output.Value[i, j] = val1; isInside = true; break; } } if (isInside) { 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 = output.NoDataValue; output.Value[i, j] = val1; } else { output.Value[i, j] = output.NoDataValue; } if (cancelProgressHandler.Cancel) return false; } int current = Convert.ToInt32(Math.Round(i * 100D / max)); //only update when increment in percentage if (current > previous) cancelProgressHandler.Progress("", current, current + TextStrings.progresscompleted); previous = current; } //output = Temp; output.Save(); return true; }
/// <summary> /// Executes the ReSample Opaeration tool programaticaly /// Ping deleted the static property for external testing /// </summary> /// <param name="input1">The input raster</param> /// <param name="oldCellSize">The size of the cells Hight</param> /// <param name="newCellSize">The size of the cells Width</param> /// <param name="output">The output raster</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></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; } IEnvelope envelope = input1.Bounds.Envelope; //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; //************OLD Method ////Create the new raster with the appropriate dimensions //Raster Temp = new Raster(); ////Temp.CreateNew(output.Filename, noOfRow, noOfCol, input1.DataType); //Temp.CreateNew(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new string[] { "" }); //Temp.CellWidth = newCellSize; //Temp.CellHeight = oldCellSize; //Temp.Xllcenter = input1.Bounds.Envelope.Minimum.X + (Temp.CellWidth / 2); //Temp.Yllcenter = input1.Bounds.Envelope.Minimum.Y + (Temp.CellHeight / 2); //*************** //create output raster output = Raster.Create(output.Filename, "", noOfCol, noOfRow, 1, input1.DataType, new[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; RcIndex index1; //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); 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; 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 = Temp; output.Save(); return true; }
/// <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">the input raster.</param> /// <param name="cellHeight">The new cell height or null.</param> /// <param name="cellWidth">The new cell width or null.</param> /// <param name="outputFileName">The string name of the output raster.</param> /// <param name="progressHandler">An interface for handling the progress messages.</param> /// <returns>The resampled raster.</returns> public static IRaster Resample(IRaster input1, double cellHeight, double cellWidth, string outputFileName, IProgressHandler progressHandler) { if (input1 == null) { return(null); } Extent envelope = input1.Bounds.Extent; 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.CreateRaster(outputFileName, string.Empty, noOfCol, noOfRow, 1, input1.DataType, new[] { string.Empty }); 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 through every cell for new value for (int i = 0; i < max; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { //Project 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) { 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; } pm.CurrentValue = i; } output.Save(); pm.Reset(); return(output); }
public bool RasterMath(IRaster input1, IRaster input2, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input1 == null || input2 == null || output == null) { return(false); } // Figures out which raster has smaller cells var smallestCellRaster = input1.CellWidth < input2.CellWidth ? input1 : input2; var envelope = UnionEnvelope(input1, input2); envelope.MinX = envelope.MinX + smallestCellRaster.CellWidth / 2; envelope.MinY = envelope.MinY - smallestCellRaster.CellHeight / 2; envelope.MaxX = envelope.MaxX + smallestCellRaster.CellWidth / 2; envelope.MaxY = envelope.MaxY - smallestCellRaster.CellHeight / 2; // 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 }); var bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = input1.NoDataValue; 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); var 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; } var 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 { output.Value[i, j] = Operation(val1, val2); } 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 Point getCellCornerPoint(IRaster g, int x, int y, int corner) { ICoordinate center; double centerX; double centerY; double hcellwidth; double hcellheight; double cornerX; double cornerY; hcellwidth = g.CellWidth/2; hcellheight = g.CellHeight/2; center = g.CellToProj(x, y); centerX = center.X; centerY = center.Y; switch (corner) { case 2: { cornerX = centerX + hcellwidth; cornerY = centerY - hcellheight; break; } case 4: { cornerX = centerX - hcellwidth; cornerY = centerY - hcellheight; break; } case 6: { cornerX = centerX - hcellwidth; cornerY = centerY + hcellheight; break; } case 8: { cornerX = centerX + hcellwidth; cornerY = centerY + hcellheight; break; } default: { cornerX = -1; cornerY = -1; break; } } Point tmpPoint = new Point(cornerX, cornerY); return tmpPoint; }
private void fillTrackGrid(IRaster gridTrack, IFeatureSet polyOut, int idxToFill) { int rowStart; int rowStop; int colStart; int colStop; RcIndex start; RcIndex stop; ICoordinate I; start = gridTrack.ProjToCell(polyOut.Features[idxToFill].Envelope.Minimum.X, polyOut.Features[idxToFill].Envelope.Maximum.Y); stop = gridTrack.ProjToCell(polyOut.Features[idxToFill].Envelope.Maximum.X, polyOut.Features[idxToFill].Envelope.Minimum.Y); rowStart = start.Row; colStart = start.Column; rowStop = stop.Row; colStop = stop.Column; for (int rowcell = rowStart; rowcell <= rowStop; rowcell++) { for (int colcell = colStart; colcell <= colStop; colcell++) { I = gridTrack.CellToProj(rowcell, colcell); Point pt = new Point(I); if (polyOut.Features[idxToFill].Covers(pt)) { gridTrack.Value[rowcell, colcell] = 1; } } } }
/// <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(); for (int i = 0; i < input.Features.Count; i++) { randomList.Add(i); } Random rnd = new(); List <int> completed = new(); 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 *= 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); 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(lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows)); if (cancelProgressHandler.Cancel) { return(false); } } } } output.Save(); return(true); }
/// <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); }
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); }
//Convert pixel to point private Coordinate Rc_to_Coor(int i, int j, IRaster ExecuteRaster) { Coordinate coor = ExecuteRaster.CellToProj(i, j); return(coor); }
public bool RasterMath(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] = output.NoDataValue; } else if (val1 == input1.NoDataValue && val2 != input2.NoDataValue) { output.Value[i, j] = output.NoDataValue; } else { output.Value[i, j] = Operation(val1, val2); } 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; }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="poly">The Polygon.</param> /// <param name="output">The Raster.</param> /// <param name="progress">The progress handler.</param> public bool Execute(IFeatureSet poly, int noOfRow, int noOfCol, int selectionIndex, IRaster output, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (poly == null || output == null) { return false; } if (poly.FeatureType != FeatureTypes.Polygon) return false; //double CellSize = poly.Envelope.Width / 255; //int noOfRow = Convert.ToInt32(poly.Envelope.Height / CellSize); //int noOfCol = Convert.ToInt32(poly.Envelope.Width / CellSize); output=Raster.Create(output.Filename,"",noOfCol,noOfRow,1,typeof(int),new string[] { "" }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, poly.Envelope); output.Bounds=bound; output.NoDataValue = -1; int current, previous = 0; double area = 0.0, previousArea = 0.0; double hCellWidth = output.CellWidth / 2; double hCellHeight = output.CellHeight / 2; ICoordinate[] coordinateCell=new Coordinate[4]; int polyIndex = -1; bool cover = false; //IEnvelope env=null; for (int i = 0; i < output.NumRows; i++) { current = Convert.ToInt32(i*100 / output.NumRows); //only update when increment in percentage if (current > previous+5) { cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed"); previous = current; } for (int j = 0; j < output.NumColumns; j++) { polyIndex = -1; area = 0.0; previousArea = 0.0; cover=false; ICoordinate cordinate=null; cordinate = output.CellToProj(i, j); //make the center of cell as point geometry IPoint pt=new Point(cordinate); for(int f=0;f<poly.Features.Count;f++) { if (selectionIndex == 0) { if (poly.Features[f].Covers(pt)) { output.Value[i, j] = f; cover = true; break; } if (cancelProgressHandler.Cancel == true) return false; } else //process area based selection { ICoordinate tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y - hCellHeight); coordinateCell[0] = tempCo; tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y - hCellHeight); coordinateCell[1] = tempCo; tempCo = new Coordinate(cordinate.X + hCellWidth, cordinate.Y + hCellHeight); coordinateCell[2] = tempCo; tempCo = new Coordinate(cordinate.X - hCellWidth, cordinate.Y + hCellHeight); coordinateCell[3] = tempCo; List<ICoordinate> ListCellCordinate = new List<ICoordinate>(); ListCellCordinate = coordinateCell.ToList<ICoordinate>(); IFeature cell = new Feature(FeatureTypes.Polygon, ListCellCordinate); IFeature commonFeature=poly.Features[f].Intersection(cell); if (commonFeature == null) continue; area=commonFeature.Area(); if (area > previousArea) { polyIndex = f; cover = true; previousArea = area; } if (cancelProgressHandler.Cancel == true) return false; } } if (cover == true) { if (selectionIndex == 1) output.Value[i, j] = polyIndex; } else output.Value[i, j] = output.NoDataValue; } } //output.SaveAs(output.Filename); output.Save(); //output.SaveAs(output.Filename); return true; }
/// <summary> /// Executes the Area tool with programatic input /// Ping delete static for external testing /// </summary> /// <param name="input">The input raster</param> /// <param name="output">The output polygon feature set</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 cellsize based on the input extents if (cellSize == 0) cellSize = input.Envelope.Width / 255; //Defines the dimesions and position of the raster int numColumns = Convert.ToInt32(Math.Round(input.Envelope.Width / cellSize)); int numRows = Convert.ToInt32(Math.Round(input.Envelope.Height / cellSize)); output = Raster.Create(output.Filename, "",numColumns, numRows, 1, typeof(double), new[] {""} ); output.CellHeight = cellSize; output.CellWidth = cellSize; output.Xllcenter = input.Envelope.Minimum.X + (cellSize/2); output.Yllcenter = input.Envelope.Minimum.Y + (cellSize/2); //Used to calculate progress int lastUpdate=0; //Populates the KD tree MapWindow.Analysis.Topology.KDTree.KDTree kd = new MapWindow.Analysis.Topology.KDTree.KDTree(2); 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]].Coordinates[0]; while (kd.Search(coord.ToArray()) != null) coord.X = coord.X * 1.000000000000001D; kd.Insert(coord.ToArray(), input.Features[randomList[index]]); completed.Add(randomList[index]); randomList.RemoveAt(index); } System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch(); //Makes sure we don't try to search for more points then exist if (kd.Count < pointCount) pointCount = kd.Count; 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); Double[] pixelCoord = new double[2]; pixelCoord[0] = output.CellToProj(y, x).X; pixelCoord[1] = output.CellToProj(y, x).Y; sw.Start(); object[] result = kd.Nearest(pixelCoord, pointCount); sw.Stop(); //Sets up the IDW numerator and denominator double top = 0; double bottom = 0; foreach (object feat in result) { IFeature featurePt = feat as Feature; if (featurePt == null) continue; double distanceToCell = cellCenter.Distance(featurePt.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("", lastUpdate, "Cell: " + (x * numRows) + " of " + (numColumns * numRows)); if (cancelProgressHandler.Cancel) return false; } } System.Diagnostics.Debug.WriteLine(sw.ElapsedMilliseconds); } output.Save(); return true; }
public bool ExecuteByParam(IFeatureSet input, string zField, double cellSize, string model, int neighborType, int pointCount, double distance, IRaster output, double c, double r) { 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)); progress.Maximum = numColumns * numRows; progress.Value = 0; 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); List <AltitudePoint> points = new List <AltitudePoint>(); if (neighborType == 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); #endregion if (pointCount > 0) { for (int i = 0; i < input.Features.Count; i++) { var featurePt = input.Features[i]; points.Add(new AltitudePoint(featurePt.BasicGeometry.Coordinates[0].X, featurePt.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(featurePt.DataRow[zField]))); } ForRasterData forRasterData = new ForRasterData(points, model); for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { points.Clear(); Coordinate coord = output.CellToProj(y, x); KD_Point kD_Point = new KD_Point(coord.X, coord.Y); List <KD_Point> kdpoints = kDTree.K_Nearest(kD_Point, pointCount); foreach (var p in kdpoints) { points.Add(new AltitudePoint(p.X, p.Y, p.Z)); } forRasterData.ReSetPointList(points); if (!forRasterData.IsPointsOK()) { return(false); } output.Value[y, x] = forRasterData.GetValue(coord.X, coord.Y); progress.Value++; } } } else { for (int i = 0; i < input.Features.Count; i++) { var featurePt = input.Features[i]; points.Add(new AltitudePoint(featurePt.BasicGeometry.Coordinates[0].X, featurePt.BasicGeometry.Coordinates[0].Y, Convert.ToDouble(featurePt.DataRow[zField]))); } ForRasterData forRasterData = new ForRasterData(points, model, c, r); if (!forRasterData.IsPointsOK()) { return(false); } for (int x = 0; x < numColumns; x++) { for (int y = 0; y < numRows; y++) { Coordinate coordinate = output.CellToProj(y, x); output.Value[y, x] = forRasterData.GetValue(coordinate.X, coordinate.Y); progress.Value++; } } } } output.Save(); return(true); }