private void btnAddData_Click(object sender, EventArgs e) { ///////////////////////////////// //Replace with something that uses the default data provider System.Windows.Forms.SaveFileDialog sfd = new System.Windows.Forms.SaveFileDialog(); sfd.OverwritePrompt = true; sfd.Filter = "BGD| *.bgd"; if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { IRaster raster = new MapWindow.Data.Raster(); raster.Filename = sfd.FileName; //If the features set is null do nothing the user probably hit cancel if (raster == null) return; //If the feature type is good save it else { //This inserts the new featureset into the list textBox1.Text = System.IO.Path.GetFileNameWithoutExtension(raster.Filename); base.Param.Value = raster; base.Status = ToolStatus.Ok; base.LightTipText = MapWindow.MessageStrings.FeaturesetValid; } } }
/// <summary> /// Finds the average slope in the given polygons. /// </summary> /// <param name="gridIn">The Polygon Raster(Grid file).</param> /// <param name="polyOut">The Polygon shapefile path.</param> /// <param name="progress">The progress handler.</param> public bool Execute(IRaster gridIn, IFeatureSet polyOut, ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (gridIn == null || polyOut == null) { return false; } int maxX, maxY; int current = 0; int previous = 0; double noData, currVal, currTrack; string strTrackPath; IRaster gridTrack = new Raster(); maxX = gridIn.NumRows - 1; maxY = gridIn.NumColumns - 1; noData = gridIn.NoDataValue; //strTrackPath = System.IO.Path.GetDirectoryName(strInRast) + "\\" + System.IO.Path.GetFileNameWithoutExtension(strInRast) + "_track.bgd"; gridTrack = Raster.Create("gridTrack.bgd", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" }); //gridTrack.CreateNew("gridTrack", "", gridIn.NumColumns, gridIn.NumRows, 1, gridIn.DataType, new string[] { "" }); gridTrack.Bounds = gridIn.Bounds; gridTrack.NoDataValue = gridIn.NoDataValue; polyOut.DataTable.Columns.Add("Value", typeof(int)); polyOut.DataTable.Columns.Add("Zone", typeof(string)); polyOut.DataTable.Columns.Add("Area", typeof(double)); polyOut.DataTable.Columns.Add("COMID", typeof(string)); polyOut.DataTable.Columns.Add("AveSlope", typeof(double)); for (int i = 0; i <= maxX; i++) { current = Convert.ToInt32(i * 100 / maxX); //only update when increment in percentage if (current > previous+5) { cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed"); previous = current; } for (int j = 0; j <= maxY; j++) { if (i > 0 && j > 0) { currVal = Convert.ToInt16(gridIn.Value[i, j]); currTrack = Convert.ToInt16(gridTrack.Value[i, j]); if (currVal == gridIn.NoDataValue) { gridTrack.Value[i, j] = 1; if (cancelProgressHandler.Cancel == true) return false; } else { if (currTrack == 1) { } else { formPolyFromCell(gridIn, gridTrack, i, j, polyOut, cancelProgressHandler); if (cancelProgressHandler.Cancel == true) return false; } } } else { gridTrack.Value[i, j] = gridIn.NoDataValue; } } } gridIn.Close(); gridTrack.Close(); polyOut.SaveAs(polyOut.Filename, true); polyOut.Close(); return true; }
/// <summary> /// Creates a new raster with the specified cell size. If the cell size /// is zero, this will default to the shorter of the width or height /// divided by 256. If the cell size produces a raster that is greater /// than 8,000 pixels in either dimension, it will be re-sized to /// create an 8,000 length or width raster. /// </summary> /// <param name="fs">The featureset to convert to a raster</param> /// <param name="cellSize">The double extent of the cell.</param> /// <param name="fieldName">The integer field index of the file.</param> /// <param name="destFilename">The filename of the raster to create</param> /// <param name="driverCode">The optional GDAL driver code to use if using GDAL /// for a format that is not discernable from the file extension. An empty string /// is usually perfectly acceptable here.</param> /// <param name="options">For GDAL rasters, they can be created with optional parameters /// passed in as a string array. In most cases an empty string is perfectly acceptable.</param> /// <param name="progressHandler">An interface for handling the progress messages.</param> /// <returns>Generates a raster from the vectors.</returns> public static IRaster ToRaster(IFeatureSet fs, ref double cellSize, string fieldName, string destFilename, string driverCode, string[] options, IProgressHandler progressHandler) { IEnvelope env = fs.Envelope; if(cellSize == 0) { if(fs.Envelope.Width < fs.Envelope.Height) { cellSize = env.Width/256; } else { cellSize = env.Height/256; } } int w = (int)Math.Ceiling(env.Width/cellSize); if (w > 8000) { w = 8000; cellSize = env.Width/8000; } int h = (int) Math.Ceiling(env.Height/cellSize); if (h > 8000) { cellSize = env.Height/8000; h = 8000; } Bitmap bmp = new Bitmap(w, h); Graphics g = Graphics.FromImage(bmp); g.Clear(Color.Transparent); g.SmoothingMode = SmoothingMode.None; g.TextRenderingHint = TextRenderingHint.SingleBitPerPixel; g.InterpolationMode = InterpolationMode.NearestNeighbor; Hashtable colorTable; MapArgs args = new MapArgs(new Rectangle(0, 0, w, h), env, g); switch (fs.FeatureType) { case FeatureTypes.Polygon: { MapPolygonLayer mpl = new MapPolygonLayer(fs); PolygonScheme ps = new PolygonScheme(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; mpl.DrawRegions(args, new List<IEnvelope> {env}); } break; case FeatureTypes.Line: { MapLineLayer mpl = new MapLineLayer(fs); LineScheme ps = new LineScheme(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; mpl.DrawRegions(args, new List<IEnvelope> { env }); } break; default: { MapPointLayer mpl = new MapPointLayer(fs); PointScheme ps = new PointScheme(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; mpl.DrawRegions(args, new List<IEnvelope> { env }); } break; } Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType; if (tp == typeof(string)) tp = typeof (double); // We will try to convert to double if it is a string Raster output = new Raster(); MWImageData image = new MWImageData(bmp, env); ProgressMeter pm = new ProgressMeter(progressHandler, "Converting To Raster Cells", h); output.CreateNew(destFilename, driverCode, w, h, 1, tp, options); output.Bounds = new RasterBounds(h, w, env); List<RcIndex> locations = new List<RcIndex>(); List<string> failureList = new List<string>(); for (int row = 0; row < h; row++) { for (int col = 0; col < w; col++) { Color c = image.GetColor(row, col); if (c.A == 0) { output.Value[row, col] = output.NoDataValue; } else { if (colorTable.ContainsKey(c) == false) { if (c.A < 125) { output.Value[row, col] = output.NoDataValue; continue; } // Use a color matching distance to pick the closest member object val = GetCellValue(w, h, row, col, image, c, colorTable, locations); output.Value[row, col] = GetDouble(val, failureList); } else { output.Value[row, col] = GetDouble(colorTable[c], failureList); } } } pm.CurrentValue = row; } const int maxIterations = 5; int iteration = 0; while(locations.Count > 0) { List<RcIndex> newLocations = new List<RcIndex>(); foreach (RcIndex location in locations) { object val = GetCellValue(w, h, location.Row, location.Column, image, image.GetColor(location.Row, location.Column), colorTable, newLocations); output.Value[location.Row, location.Column] = GetDouble(val, failureList); } locations = newLocations; iteration++; if(iteration > maxIterations) break; } pm.Reset(); return output; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// </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, IRaster input2, IRaster output, MapWindow.Tools.ICancelProgressHandler cancelProgressHandler) { //Validates the input and output data if (input1 == null || input2 == null || output == null) { return false; } IEnvelope envelope = new Envelope() as IEnvelope; envelope = UnionEnvelope(input1, input2); int noOfCol; int noOfRow; //Figures out which raster has smaller cells IRaster smallestCellRaster; if (input1.CellWidth < input2.CellWidth) smallestCellRaster = input1; else smallestCellRaster = input2; //Given the envelope of the two rasters we calculate the number of columns / rows noOfCol = Convert.ToInt32(Math.Abs(envelope.Width / smallestCellRaster.CellWidth)); noOfRow = Convert.ToInt32(Math.Abs(envelope.Height / smallestCellRaster.CellHeight)); //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 = smallestCellRaster.CellWidth; Temp.CellHeight = smallestCellRaster.CellHeight; Temp.Xllcenter = envelope.Minimum.X + (Temp.CellWidth / 2); Temp.Yllcenter = envelope.Minimum.Y + (Temp.CellHeight / 2); MapWindow.Geometries.ICoordinate I1 = new MapWindow.Geometries.Coordinate() as MapWindow.Geometries.ICoordinate; RcIndex v1 = new RcIndex(); RcIndex v2 = new RcIndex(); double val1; double val2; int previous=0; int current=0; int max = (Temp.Bounds.NumRows + 1); for (int i = 0; i < Temp.Bounds.NumRows; i++) { for (int j = 0; j < Temp.Bounds.NumColumns; j++) { I1 = Temp.CellToProj(i, j); v1 = input1.ProjToCell(I1); 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(I1); 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) { Temp.Value[i, j] = Temp.NoDataValue; } else if (val1 != input1.NoDataValue && val2 == input2.NoDataValue) { Temp.Value[i, j] = val1; } else if (val1 == input1.NoDataValue && val2 != input2.NoDataValue) { Temp.Value[i, j] = val2; } else { Temp.Value[i, j] = val1; } if (cancelProgressHandler.Cancel == true) return false; } current = Convert.ToInt32(Math.Round(i * 100D / max)); //only update when increment in persentage if(current>previous) cancelProgressHandler.Progress("", current, current.ToString() + "% progress completed"); previous = current; } output = Temp; output.Save(); return true; }
/// <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></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 != FeatureTypes.Polygon || outerShpFile.FeatureType != FeatureTypes.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); IPoint pt = new Point(coordin); IFeature point = new Feature(pt); if (!outerShpFile.Features[outerShpIndex].Covers(point)) continue;//not found the point inside. for (int c = 0; c < poly.Features.Count; c++) { if (output.Features[c].Covers(point)) { 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; }
/// <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(); slopeGrid.DataType = ras.DataType; slopeGrid.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.Bounds.Envelope.Intersects(output.Envelope) == false) return false; RcIndex start = slopeGrid.ProjToCell(output.Envelope.Minimum.X, output.Envelope.Maximum.Y); RcIndex stop = slopeGrid.ProjToCell(output.Envelope.Maximum.X, output.Envelope.Minimum.Y); 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("", 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.Covers(pt1) && !tempFeat.Covers(pt2)) && !tempFeat.Covers(pt3)) && !tempFeat.Covers(pt4)) && !tempFeat.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; }