public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; DateTime startTime = DateTime.Now; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster; //stamping filter LinearFilter filter = Cip.Filters.LinearFilter.Stamping(); raster = filter.ProcessRaster(rOriginal, worker); //VectorHSI hsi; int intensity; byte g; //convert to gray image and increase lightness for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { intensity = Cip.Foundations.ColorspaceHelper.RGB2GRAYI(raster[i, j]); intensity += 128; g = VectorRgb.ClampByte(intensity); raster[i, j] = new VectorRgb(g, g, g); } worker.ReportProgress((int)(100f * j / height), DateTime.Now - startTime); } return raster; }
/// <summary> /// Image processing with linear matrix filter. /// </summary> public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; // define radius of filter by X int radiusX = kernel.GetLength(0) / 2; // define radius of filter by Y int radiusY = kernel.GetLength(1) / 2; //define width and height of image int width = rOriginal.Width; int height = rOriginal.Height; //create result raster Raster raster = new Raster(width, height); float r, g, b; byte R,G,B; VectorRgb rgb; int rk, rl; //save time of beginning processing DateTime startTime = DateTime.Now; //processing for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { r = g = b = 0; for (int l = -radiusY; l <= radiusY; l++) for (int k = -radiusX; k <= radiusX; k++) if ((i + k) >= 0 && (i + k) < width && (j + l) < height && (j + l) >= 0) { rgb = rOriginal[i + k, j + l]; rk = k + radiusX; rl = l + radiusY; r += rgb.R * kernel[rk, rl]; g += rgb.G * kernel[rk, rl]; b += rgb.B * kernel[rk, rl]; } R = VectorRgb.ClampByte(r); G = VectorRgb.ClampByte(g); B = VectorRgb.ClampByte(b); raster[i, j] = new VectorRgb(R, G, B); } worker.ReportProgress((int)(100f * j / height), DateTime.Now - startTime); } //fill bound of raster /*for (int i = 0; i < width; i++) { raster[i, 0] = rOriginal[i, 0]; raster[i, height - 1] = rOriginal[i, height - 1]; } for (int j = 0; j < height; j++) { raster[0, j] = rOriginal[0, j]; raster[width - 1, j] = rOriginal[width - 1, j]; }*/ return raster; }
public cipFormLightnessContrast(Image image, Raster source) { InitializeComponent(); CipSize size = new CipSize(image.Size); CipSize newSize = Resample.SizeAdaptHeight(size, 200); Resample resampleFIlter = new Resample(newSize, CipInterpolationMode.BicubicSpline); raster = resampleFIlter.ProcessWithoutWorker(source); this.ThumbnailBitmap = raster.ToBitmap(); this.pBoxPreview.Image = this.ThumbnailBitmap; thread = new Thread(new ThreadStart(this.ReDraw)); thread.Priority = ThreadPriority.Normal; }
public void ClipRasterWithPolygonTest() { var shapeFilePath = Path.Combine("Data", "elbe_watershed1.shp"); var rasterFilePath = Path.Combine("Data", "kriging.bgd" ); var resultFilePath = Path.Combine("Data", "clipResult.bgd" ); var lClipPolygon = Shapefile.OpenFile(shapeFilePath); var lGridToClip = Raster.OpenFile(rasterFilePath, false); var lGridAfterClip = new Raster {Filename = resultFilePath}; ClipRaster.ClipRasterWithPolygon(lClipPolygon.Features[0], lGridToClip, lGridAfterClip.Filename); var ras2 = Raster.Open(lGridAfterClip.Filename); Assert.AreEqual(lGridToClip.NoDataValue, ras2.NoDataValue); }
private void RenderFlags(Raster scanFlags, Raster target) { var source = scanFlags.Pixels; var destinataion = target.Pixels; var stride = target.Stride; for (int y = 0; y < target.Height; y++) { int row = stride * y; for (int x = 0; x < target.Width; x++) { destinataion[row + x] = (byte)(source[row + x] * 128); } } }
public cipFormSmoothing(Image image, Raster source, System.Globalization.CultureInfo selectedCulture) { Thread.CurrentThread.CurrentUICulture = selectedCulture; InitializeComponent(); CipSize size = new CipSize(image.Size); CipSize newSize = Resample.SizeAdaptHeight(size, 200); Resample resampleFIlter = new Resample(newSize, CipInterpolationMode.BicubicSpline); raster = resampleFIlter.ProcessWithoutWorker(source); this.ThumbnailBitmap = raster.ToBitmap(); this.pBoxPreview.Image = this.ThumbnailBitmap; thread = new Thread(new ThreadStart(this.ReDraw)); thread.Priority = ThreadPriority.Normal; }
public cipFormHistogram(Image image,Raster source) { InitializeComponent(); level = trackBarThreshold.Value / 1000f; textBoxLevel.Text = Convert.ToString(this.level); CipSize size = new CipSize(image.Size); CipSize newSize = Resample.SizeAdaptHeight(size, 200); Resample resampleFIlter = new Resample(newSize, CipInterpolationMode.BicubicSpline); raster = resampleFIlter.ProcessWithoutWorker(source); this.ThumbnailBitmap = raster.ToBitmap(); this.pBoxPreview.Image = this.ThumbnailBitmap; thread = new Thread(new ThreadStart(this.ReDraw)); thread.Priority = ThreadPriority.Normal; }
private void BtnAddDataClick(object sender, EventArgs e) { ///////////////////////////////// //Replace with something that uses the default data provider SaveFileDialog sfd = new SaveFileDialog(); sfd.OverwritePrompt = true; sfd.Filter = "BGD| *.bgd"; if (sfd.ShowDialog() != DialogResult.OK) return; IRaster raster = new Raster(); raster.Filename = sfd.FileName; //This inserts the new featureset into the list textBox1.Text = Path.GetFileNameWithoutExtension(raster.Filename); Param.Value = raster; base.Status = ToolStatus.Ok; LightTipText = ModelingMessageStrings.FeaturesetValid; }
public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; byte r, g, b, rr, gg, bb; VectorRgb c; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height, Color.Black); DateTime startTime = DateTime.Now; //processing for (int i = 0; i < width; i++) { //moving by columns for (int j = 0; j < height; j++) { r = g = b = 0; rr = gg = bb = 255; for (int k = i - (n - 1) / 2; k <= i + (n - 1) / 2; k++) { for (int l = j - (n - 1) / 2; l <= j + (n - 1) / 2; l++) { if (k >= 0 && k < width && l < height && l >= 0) { c = rOriginal[k, l]; if (c.R > r) r = c.R; if (c.G > g) g = c.G; if (c.B > b) b = c.B; if (c.R < rr) rr = c.R; if (c.G < gg) gg = c.G; if (c.B < bb) bb = c.B; } } } raster[i, j].R = (byte)(255 - Math.Abs(r - rr)); raster[i, j].G = (byte)(255 - Math.Abs(g - gg)); raster[i, j].B = (byte)(255 - Math.Abs(b - bb)); } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
public void ClipRasterWithPolygonTest() { var shapeFilePath = FileTools.PathToTestFile(@"Shapefiles\elbe_watershed1\elbe_watershed1.shp"); var rasterFilePath = FileTools.PathToTestFile(@"Rasters\kriging.bgd"); var resultFilePath = FileTools.GetTempFileName(".bgd"); try { var lClipPolygon = Shapefile.OpenFile(shapeFilePath); var lGridToClip = Raster.OpenFile(rasterFilePath, false); var lGridAfterClip = new Raster { Filename = resultFilePath }; ClipRaster.ClipRasterWithPolygon(lClipPolygon.Features[0], lGridToClip, lGridAfterClip.Filename); var ras2 = Raster.Open(lGridAfterClip.Filename); Assert.AreEqual(lGridToClip.NoDataValue, ras2.NoDataValue); } finally { File.Delete(resultFilePath); } }
public void RasterMath_OutputHasSameBounds() { // Prepare input raster const double xllcorner = 3267132.224761; const double yllcorner = 5326939.203029; const int ncols = 39; const int nrows = 57; const double cellsize = 500; const double x2 = xllcorner + (cellsize * ncols); const double y2 = yllcorner + (cellsize * nrows); var myExtent = new Extent(xllcorner, yllcorner, x2, y2); var source = new Raster<int>(nrows, ncols) { Bounds = new RasterBounds(nrows, ncols, myExtent), NoDataValue = -9999 }; var mRow = source.Bounds.NumRows; var mCol = source.Bounds.NumColumns; var i = 0; for (var row = 0; row < mRow; row++) { for (var col = 0; col < mCol; col++) { source.Value[row, col] = i++; } } var target = new RasterMultiply(); IRaster outRaster = new Raster {Filename = FileTools.GetTempFileName(".bgd")}; target.Execute(source, source, outRaster, new MockProgressHandler()); outRaster = Raster.Open(outRaster.Filename); File.Delete(outRaster.Filename); Assert.AreEqual(source.NumColumns, outRaster.NumColumns); Assert.AreEqual(source.NumRows, outRaster.NumRows); Assert.AreEqual(source.Bounds.Extent, outRaster.Bounds.Extent); }
public void Rasterize(string text, int size, Raster raster, bool toFlags = false) { var flags = new Raster(raster.Width, raster.Height, raster.Stride, raster.Resolution); // int fx = 64; int fy = 0; foreach (var character in text) { var glyph = _typeface.Lookup(character); SetScanFlags(glyph, flags, fx, fy, size, 0, 70); fx += _typeface.GetAdvanceWidth(character); } if (toFlags) { RenderFlags(flags, raster); } else { RenderScanlines(flags, raster); } }
public void Execute() { string[] options = new string[1]; IRaster DirectionRaster = Raster.CreateRaster("Direction" + ".bgd", null, ExecuteRaster.NumColumns, ExecuteRaster.NumRows, 1, ExecuteRaster.DataType, options); DirectionRaster.Bounds = ExecuteRaster.Bounds; DirectionRaster.NoDataValue = ExecuteRaster.NoDataValue; DirectionRaster.Projection = ExecuteRaster.Projection; IRaster LabelRaster = Raster.CreateRaster("Label" + ".bgd", null, ExecuteRaster.NumColumns, ExecuteRaster.NumRows, 1, ExecuteRaster.DataType, options); LabelRaster.Bounds = ExecuteRaster.Bounds; LabelRaster.NoDataValue = ExecuteRaster.NoDataValue; LabelRaster.Projection = ExecuteRaster.Projection; try { FlowDir_Thread fd_thread = new FlowDir_Thread(DirectionRaster, LabelRaster, ExecuteRaster); Thread thread1 = new Thread(new ThreadStart(fd_thread.Pos_start)); thread1.Start(); Thread thread2 = new Thread(new ThreadStart(fd_thread.Rev_start)); thread2.Start(); } catch (Exception e) { MessageBox.Show(e.Message, "Admin", MessageBoxButtons.OK, MessageBoxIcon.Error); } MainMap.Layers.Add(DirectionRaster); int LayerNum = MainMap.Layers.Count; string FileName = Path.GetFileName(SavePath); MainMap.Layers[LayerNum - 1].LegendText = FileName; MainMap.Refresh(); DirectionRaster.SaveAs(SavePath); MessageBox.Show("Completed program.", "Admin", MessageBoxButtons.OK, MessageBoxIcon.Information); }
private async void Initialize() { // Create a new map MyMapView.Map = new Map(BasemapStyle.ArcGISLightGray); // Get the full path string geoPackagePath = GetGeoPackagePath(); try { // Open the GeoPackage GeoPackage myGeoPackage = await GeoPackage.OpenAsync(geoPackagePath); // Read the raster images and get the first one Raster gpkgRaster = myGeoPackage.GeoPackageRasters.FirstOrDefault(); // Make sure an image was found in the package if (gpkgRaster == null) { return; } // Create a layer to show the raster RasterLayer newLayer = new RasterLayer(gpkgRaster); await newLayer.LoadAsync(); // Set the viewpoint await MyMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent)); // Add the image as a raster layer to the map (with default symbology) MyMapView.Map.OperationalLayers.Add(newLayer); } catch (Exception e) { await new MessageDialog(e.ToString(), "Error").ShowAsync(); } }
/// <summary> /// Get a number of chunks from the actual rasters /// NOTE: for now a chunk goes across the whole extent to make the math easier /// </summary> /// <returns></returns> public void GetChunk(List <T[]> data) { for (int idx = 0; idx < _inputRasters.Count; idx++) { Raster rRa = _inputRasters[idx]; // Reset everything first so we don't get any data bleed // NOTE: if this is slow we can revisit data[idx].Fill(inNodataVals[idx]); ExtentRectangle _interSectRect = rRa.Extent.Intersect(ChunkExtent); // Make sure there's some data to read, otherwise return the filled nodata values from above if (_interSectRect.Rows > 0 && _interSectRect.Cols > 0) { T[] _buffer = new T[_interSectRect.Rows * _interSectRect.Cols]; // Find the offset between the intersection and rRa int[] offrRa = _interSectRect.GetTopCornerTranslationRowCol(rRa.Extent); #if DEBUG tmr_rasterread.Start(); num_reads++; #endif _inputRasters[idx].Read(offrRa[1], offrRa[0], _interSectRect.Cols, _interSectRect.Rows, _buffer); #if DEBUG tmr_rasterread.Stop(); #endif // Find the offset between the intersection and the chunkwindow int[] offChunk = _interSectRect.GetTopCornerTranslationRowCol(ChunkExtent); data[idx].Plunk(_buffer, ChunkExtent.Rows, ChunkExtent.Cols, _interSectRect.Rows, _interSectRect.Cols, offChunk[0], offChunk[1]); } } }
private async void Initialize() { // Create a new map. _myMapView.Map = new Map(Basemap.CreateLightGrayCanvas()); // Get the GeoPackage path. string geoPackagePath = DataManager.GetDataFolder("68ec42517cdd439e81b036210483e8e7", "AuroraCO.gpkg"); try { // Open the GeoPackage. GeoPackage geoPackage = await GeoPackage.OpenAsync(geoPackagePath); // Read the raster images and get the first one. Raster gpkgRaster = geoPackage.GeoPackageRasters.FirstOrDefault(); // Make sure an image was found in the package. if (gpkgRaster == null) { return; } // Create a layer to show the raster. RasterLayer newLayer = new RasterLayer(gpkgRaster); await newLayer.LoadAsync(); // Set the viewpoint. await _myMapView.SetViewpointAsync(new Viewpoint(newLayer.FullExtent)); // Add the image as a raster layer to the map (with default symbology). _myMapView.Map.OperationalLayers.Add(newLayer); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
public void SlopeIsWorking() { var raster = Raster.Open(Path.Combine(Common.AbsolutePath("Data"), "kriging.bgd")); var actual = Slope.GetSlope(raster, 1, true, null); try { Assert.IsNotNull(actual); Assert.AreEqual(raster.Extent, actual.Extent); Assert.AreEqual(raster.NumColumns, actual.NumColumns); Assert.AreEqual(raster.NumRows, actual.NumRows); Assert.AreEqual(raster.CellHeight, actual.CellHeight); Assert.AreEqual(raster.CellWidth, actual.CellWidth); // Test that some output values are non zeros and non NoData var existsSomeValidValues = false; for (int i = 0; i < raster.NumRows; i++) { for (int j = 0; j < raster.NumColumns; j++) { if (raster.Value[i, j] != 0 && raster.Value[i, j] != raster.NoDataValue) { existsSomeValidValues = true; goto finCycle; } } } finCycle: Assert.IsTrue(existsSomeValidValues); } finally { File.Delete(actual.Filename); } }
private async void Initialize() { // Create a map with a streets basemap. Map myMap = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); try { // Create and load a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Once the layer is loaded, enable the button to apply a new renderer. _applyRendererButton.Enabled = true; // Create a viewpoint with the raster's full extent. Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent); // Set the initial viewpoint for the map. myMap.InitialViewpoint = fullRasterExtent; // Add the layer to the map. myMap.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = myMap; } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
private bool BinRaster <T>(Raster <T> source, Raster <T> result, ICancelProgressHandler progressHandler) where T : IEquatable <T>, IComparable <T> { ProgressMeter pm = new ProgressMeter(progressHandler, "Calculating values", source.NumRows); for (int row = 0; row < source.NumRows; row++) { for (int col = 0; col < source.NumColumns; col++) { double value = (double)Convert.ChangeType(source.Data[row][col], typeof(double)); int sign = Math.Sign(value); value = (value - BaseValue) / BinSize; value = Math.Floor(value); value = BinSize * value + sign * BinSize / 2; result.Data[row][col] = (T)Convert.ChangeType(value, typeof(T)); } pm.Next(); if (progressHandler.Cancel) { return(false); } } return(true); }
private async void Initialize() { // Define a new map with Wgs84 Spatial Reference. var map = new Map(BasemapType.Oceans, latitude: -34.1, longitude: 18.6, levelOfDetail: 9); // Get the file name for the raster. string filepath = DataManager.GetDataFolder("b5f977c78ec74b3a8857ca86d1d9b318", "SA_EVI_8Day_03May20.tif"); // Load the raster file. var raster = new Raster(filepath); // Initialize the raster layer. _rasterLayer = new RasterLayer(raster); // Add the raster layer to the map. map.OperationalLayers.Add(_rasterLayer); // Add map to the map view. MyMapView.Map = map; try { // Wait for the layer to load. await _rasterLayer.LoadAsync(); // Set the viewpoint. await MyMapView.SetViewpointGeometryAsync(_rasterLayer.FullExtent); } catch (Exception ex) { await Application.Current.MainPage.DisplayAlert(ex.GetType().Name, ex.Message, "OK"); } // Listen for mouse movement to start the identify operation. MyMapView.GeoViewTapped += MapTapped; }
public static IRasterRenderer CreateContinuousRenderer(Raster gRaster, IColorRamp pColorRamp, bool bInvert = false) { try { gRaster.ComputeStatistics(); Dictionary <string, decimal> stats = gRaster.GetStatistics(); double rMin = (double)stats["min"]; double rMax = (double)stats["max"]; RasterStretchColorRampRenderer stretchRenderer = new RasterStretchColorRampRenderer(); IRasterRenderer rasterRenderer = (IRasterRenderer)stretchRenderer; IRasterDataset rasterDataset = ArcMapUtilities.GetRasterDataset(gRaster); IRaster raster = rasterDataset.CreateDefaultRaster(); rasterRenderer.Raster = raster; IRasterRendererColorRamp pRenderColorRamp = (IRasterRendererColorRamp)rasterRenderer; pRenderColorRamp.ColorRamp = pColorRamp; int iRound = GetMagnitude(rMin); stretchRenderer.LabelHigh = Math.Round(rMax, Math.Abs(iRound)).ToString(); stretchRenderer.LabelLow = Math.Round(rMin, Math.Abs(iRound)).ToString(); if (bInvert) { IRasterStretch2 pStretch = (IRasterStretch2)stretchRenderer; pStretch.Invert = true; } rasterRenderer.Update(); return(rasterRenderer); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine(ex.Message); return(null); } }
/// <summary> /// Encodes and writes raster data as a 1-bit bitmap. /// </summary> /// <param name="raster"> /// the source raster data </param> private void Write1(Raster raster) { int bytesPerLine = GetBytesPerLine1(raster.getWidth()); byte[] line = new byte[bytesPerLine]; for (int y = raster.getHeight() - 1; y >= 0; y--) { for (int i = 0; i < bytesPerLine; i++) { line[i] = 0; } for (int x = 0; x < raster.getWidth(); x++) { int bi = x / 8; int i = x % 8; int index = raster.getSample(x, y, 0); line[bi] = SetBit(line[bi], i, index); } writer.Write(line); } }
private static void GeneratingMeshes(Raster <MyVertex, MyProjectedVertex> render) { render.ClearRT(float4(0, 0, 0.2f, 1)); // clear with color dark blue. var primitive = CreateModel(); /// Convert to a wireframe to render. Right now only lines can be rasterized. primitive = primitive.ConvertTo(Topology.Lines); #region viewing and projecting float4x4 viewMatrix = Transforms.LookAtLH(float3(2, 1f, 4), float3(0, 0, 0), float3(0, 1, 0)); float4x4 projectionMatrix = Transforms.PerspectiveFovLH(pi_over_4, render.RenderTarget.Height / (float)render.RenderTarget.Width, 0.01f, 20); // Define a vertex shader that projects a vertex into the NDC. render.VertexShader = v => { float4 hPosition = float4(v.Position, 1); hPosition = mul(hPosition, viewMatrix); hPosition = mul(hPosition, projectionMatrix); return(new MyProjectedVertex { Homogeneous = hPosition }); }; // Define a pixel shader that colors using a constant value render.PixelShader = p => { return(float4(p.Homogeneous.x / 1024.0f, p.Homogeneous.y / 512.0f, 1, 1)); }; #endregion // Draw the mesh. render.DrawMesh(primitive); }
public void PointDensityTest() { Raster rDEM = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"PointDensity\GrandCanyon\R02_DEM_Meters_2004_05.img"))); Vector rPtDensity = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"PointDensity\GrandCanyon\R2_HybridData_2004_05.shp"))); Raster rDEM2 = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"PointDensity\SulpherCreek\2006Feb_DEM.img"))); Vector rPtDensity2 = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"PointDensity\SulpherCreek\feb06_all_points.shp"))); // Make sure we can handle null points Vector rNullPoint = new Vector(new FileInfo(DirHelpers.GetTestVectorPath(@"Null_Point.shp"))); using (ITempDir tmp = TempDir.Create()) { Raster circleOut = new Raster(rDEM, new FileInfo(Path.Combine(tmp.Name, "GCPointDensityCircleTest.tif"))); PointDensity circletest = new PointDensity(rDEM, rPtDensity, circleOut, RasterOperators.KernelShapes.Circle, 4.0m); circletest.RunWithOutput(); Raster sqOut = new Raster(rDEM, new FileInfo(Path.Combine(tmp.Name, "GCPointDensitySquareTest.tif"))); PointDensity squaretest = new PointDensity(rDEM, rPtDensity, sqOut, RasterOperators.KernelShapes.Square, 4.0m); squaretest.RunWithOutput(); Raster circleOut2 = new Raster(rDEM2, new FileInfo(Path.Combine(tmp.Name, "SulpherPointDensityCircleTest2.tif"))); PointDensity circletest2 = new PointDensity(rDEM2, rPtDensity2, circleOut2, RasterOperators.KernelShapes.Circle, 4.0m); circletest2.RunWithOutput(); Raster sqOut2 = new Raster(rDEM2, new FileInfo(Path.Combine(tmp.Name, "SulpherPointDensitySquareTest2.tif"))); PointDensity squaretest2 = new PointDensity(rDEM2, rPtDensity2, sqOut2, RasterOperators.KernelShapes.Square, 4.0m); squaretest2.RunWithOutput(); Raster nullPt = new Raster(rDEM2, new FileInfo(Path.Combine(tmp.Name, "NullPointTest.tif"))); PointDensity nullPtTest = new PointDensity(rDEM2, rNullPoint, nullPt, RasterOperators.KernelShapes.Square, 4.0m); nullPtTest.RunWithOutput(); Debug.WriteLine("done"); } }
private void btnOpenRaster_Click(object sender, RoutedEventArgs e) { OpenFileDialog dialog = new OpenFileDialog(); dialog.Filter = "TIFF File (.tif)|*.tif"; if (dialog.ShowDialog() == true) { string path = dialog.FileName; if (path == null || path == "") { return; } //mapControl.SetRaster(path); //Stream imageStreamSource = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read); //TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default); //BitmapSource bitmapSource = decoder.Frames[0]; //byte[] buffer = new WriteableBitmap(bitmapSource).ToByteArray(); ras = new Raster(); ras.ReadRaster(path); mapControl.SetRaster(ras.bmp); mapControl.Pan(); } }
private async void Initialize() { // Initialize the GUI controls appearance RendererTypes.Items.Add("Min Max"); RendererTypes.Items.Add("Percent Clip"); RendererTypes.Items.Add("Standard Deviation"); RendererTypes.SelectedIndex = 0; // Add an imagery basemap MyMapView.Map = new Map(Basemap.CreateImagery()); // Get the file name string filepath = GetRasterPath(); // Load the raster file Raster myRasterFile = new Raster(filepath); // Create the layer RasterLayer myRasterLayer = new RasterLayer(myRasterFile); // Add the layer to the map MyMapView.Map.OperationalLayers.Add(myRasterLayer); try { // Wait for the layer to load await myRasterLayer.LoadAsync(); // Set the viewpoint await MyMapView.SetViewpointGeometryAsync(myRasterLayer.FullExtent); } catch (Exception e) { await new MessageDialog(e.ToString(), "Error").ShowAsync(); } }
private async void Initialize() { // Create a map with a streets basemap. Map myMap = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); try { // Create a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); await _rasterLayer.LoadAsync(); // Set the initial viewpoint for the map to the raster's full extent. myMap.InitialViewpoint = new Viewpoint(_rasterLayer.FullExtent); // Add the layer to the map. myMap.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. _myMapView.Map = myMap; // Create the settings view controllers. _minMaxController = new MinMaxSettingsController(_rasterLayer); _percentClipController = new PercentClipSettingsController(_rasterLayer); _stdDevController = new StandardDeviationSettingsController(_rasterLayer); } catch (Exception e) { new UIAlertView("Error", e.ToString(), (IUIAlertViewDelegate)null, "OK", null).Show(); } }
public IFeatures FetchTiles(BoundingBox boundingBox, double resolution) { Extent extent = new Extent(boundingBox.Min.X, boundingBox.Min.Y, boundingBox.Max.X, boundingBox.Max.Y); int level = BruTile.Utilities.GetNearestLevel(source.Schema.Resolutions, resolution); IList<TileInfo> tiles = source.Schema.GetTilesInView(extent, level); ICollection<WaitHandle> waitHandles = new List<WaitHandle>(); foreach (TileInfo info in tiles) { if (bitmaps.Find(info.Index) != null) continue; if (queue.Contains(info.Index)) continue; AutoResetEvent waitHandle = new AutoResetEvent(false); waitHandles.Add(waitHandle); queue.Add(info.Index); Thread thread = new Thread(GetTileOnThread); thread.Start(new object[] { source.Provider, info, bitmaps, waitHandle }); //!!!ThreadPool.QueueUserWorkItem(GetTileOnThread, new object[] { source.Provider, info, bitmaps, waitHandle }); } //foreach (WaitHandle handle in waitHandles) // handle.WaitOne(); IFeatures features = new Features(); foreach (TileInfo info in tiles) { byte[] bitmap = bitmaps.Find(info.Index); if (bitmap == null) continue; IRaster raster = new Raster(bitmap, new BoundingBox(info.Extent.MinX, info.Extent.MinY, info.Extent.MaxX, info.Extent.MaxY)); IFeature feature = features.New(); feature.Geometry = raster; features.Add(feature); } return features; }
/// <summary> /// Get Equalized Histogram of Intensity /// </summary> /// <param name="r">original raster</param> /// <returns>array with normalized intensity</returns> public static float[] GetHistogramNormalized(Raster raster) { int width = raster.Width; int height = raster.Height; int iNumberOfPixels = width * height; int L = 256; int[] aHistogram; float[] aHistogramNormalized = new float[L]; aHistogram = GetHistogram(raster); //calculates intensity for (int k = 0; k < L; k++) for (int j = 0; j <= k; j++) aHistogramNormalized[k] += (float)aHistogram[j] / iNumberOfPixels; return aHistogramNormalized; }
public void RasterizedVectorTest() { Raster rOld = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\2005DecDEM.tif"))); Raster rNew = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\2006FebDEM.tif"))); Raster rOldErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\ErrorSurfaces\Constant01\Constant01.tif"))); Raster rNewErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\ErrorSurfaces\Constant02\Constant02.tif"))); Raster rDoD = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\Analyses\CD\GCD0001\raw.tif"))); Raster rThresh = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\Analyses\CD\GCD0001\thresh.tif"))); // And now the budget seg case Vector vPolyMask = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_SimpleGCDMask.shp"))); UnitGroup ug = new UnitGroup(VolumeUnit.CubicMeter, AreaUnit.SquareMeter, LengthUnit.Meter, LengthUnit.Meter); List <string> times = new List <string> { }; var watch = Stopwatch.StartNew(); using (ITempDir tmp = TempDir.Create()) { Raster rPropErr = RasterOperators.RootSumSquares(rOldErr, rNewErr, new FileInfo(Path.Combine(tmp.Name, "PropErr.tif"))); FileInfo fiPolyMaskCopy = new FileInfo(Path.Combine(tmp.Name, "Sulphur_SimpleGCDMask.shp")); vPolyMask.Copy(fiPolyMaskCopy); Vector vPolyMaskCopy = new Vector(fiPolyMaskCopy); watch.Restart(); Dictionary <string, Histogram> binRasterV = RasterOperators.BinRaster(rDoD, 100, vPolyMaskCopy, "Method", null, false); times.Add(string.Format("BinRaster, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, Histogram> binRasterR = RasterOperators.BinRaster(rDoD, 100, vPolyMaskCopy, "Method", null, true); times.Add(string.Format("BinRaster, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); foreach (KeyValuePair <string, Histogram> kvp in binRasterV) { Assert.IsTrue(kvp.Value.Equals(binRasterR[kvp.Key])); } watch.Restart(); Dictionary <string, DoDStats> statsPropV = RasterOperators.GetStatsPropagated(rDoD, rPropErr, vPolyMaskCopy, "Method", ug, null, false); times.Add(string.Format("GetStatsPropagated, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsPropR = RasterOperators.GetStatsPropagated(rDoD, rPropErr, vPolyMaskCopy, "Method", ug, null, true); times.Add(string.Format("GetStatsPropagated, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); foreach (KeyValuePair <string, DoDStats> kvp in statsPropV) { Assert.IsTrue(kvp.Value.Equals(statsPropR[kvp.Key])); } watch.Restart(); Dictionary <string, DoDStats> minlodV = RasterOperators.GetStatsMinLoD(rDoD, 0.2m, vPolyMaskCopy, "Method", ug, null, false); times.Add(string.Format("GetStatsMinLoD, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> minlodR = RasterOperators.GetStatsMinLoD(rDoD, 0.2m, vPolyMaskCopy, "Method", ug, null, true); times.Add(string.Format("GetStatsMinLoD, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); foreach (KeyValuePair <string, DoDStats> kvp in minlodV) { Assert.IsTrue(kvp.Value.Equals(minlodR[kvp.Key])); } watch.Restart(); Dictionary <string, DoDStats> statsprobV = RasterOperators.GetStatsProbalistic(rDoD, rThresh, rPropErr, vPolyMaskCopy, "Method", ug, null, false); times.Add(string.Format("GetStatsProbalistic, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsprobR = RasterOperators.GetStatsProbalistic(rDoD, rThresh, rPropErr, vPolyMaskCopy, "Method", ug, null, true); times.Add(string.Format("GetStatsProbalistic, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); foreach (KeyValuePair <string, DoDStats> kvp in statsprobV) { Assert.IsTrue(kvp.Value.Equals(statsprobR[kvp.Key])); } Dictionary <string, ErrorRasterProperties> props = new Dictionary <string, ErrorRasterProperties> { { "LiDAR", new ErrorRasterProperties(0.1m) }, { "Total Station", new ErrorRasterProperties(0.2m) } }; watch.Restart(); Raster errorV = RasterOperators.CreateErrorRaster(rDoD, vPolyMaskCopy, "Method", props, new FileInfo(Path.Combine(tmp.Name, "MultiMethodErrorV.tif")), null, false); times.Add(string.Format("CreateErrorRaster, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Raster errorR = RasterOperators.CreateErrorRaster(rDoD, vPolyMaskCopy, "Method", props, new FileInfo(Path.Combine(tmp.Name, "MultiMethodErrorR.tif")), null, true); times.Add(string.Format("CreateErrorRaster, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); RasterTests.RasterCompare(errorV, errorR); foreach (string line in times) { Debug.WriteLine(line); } vPolyMaskCopy.UnloadDS(); } }
public static async Task <TableStatisticsResult> GetRasterStats(Uri rasterUri, string field) { // parse the uri for the folder and file string strFileName = null; string strFolderPath = null; if (rasterUri.IsFile) { strFileName = System.IO.Path.GetFileName(rasterUri.LocalPath); strFolderPath = System.IO.Path.GetDirectoryName(rasterUri.LocalPath); } RasterDataset rDataset = null; await QueuedTask.Run(() => { // Opens a file geodatabase. This will open the geodatabase if the folder exists and contains a valid geodatabase. using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(new Uri(strFolderPath)))) { // Use the geodatabase. try { rDataset = geodatabase.OpenDataset <RasterDataset>(strFileName); } catch (GeodatabaseTableException e) { Module1.Current.ModuleLogManager.LogError(nameof(GetRasterStats), "Unable to open raster " + strFileName); Module1.Current.ModuleLogManager.LogError(nameof(GetRasterStats), "Exception: " + e.Message); return; } } }); TableStatisticsResult tableStatisticsResult = null; if (rDataset != null) { await QueuedTask.Run(() => { Raster raster = rDataset.CreateRaster(new int[] { 0 }); if (raster != null) { var table = raster.GetAttributeTable(); if (table != null) { Field statField = table.GetDefinition().GetFields().First(x => x.Name.Equals(field)); StatisticsDescription statisticsDescription = new StatisticsDescription(statField, new List <StatisticsFunction>() { StatisticsFunction.Min, StatisticsFunction.Max }); TableStatisticsDescription tableStatisticsDescription = new TableStatisticsDescription(new List <StatisticsDescription>() { statisticsDescription }); IReadOnlyList <TableStatisticsResult> statResult = table.CalculateStatistics(tableStatisticsDescription); tableStatisticsResult = statResult[0]; } } }); } return(tableStatisticsResult); }
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 ex) { Logger.Log(LogLevel.Error, "Could not convert double to int (ExportMap size)", ex); return(false); } var uri = new Uri(GetRequestUrl(viewport.Extent, width, height)); var webRequest = (HttpWebRequest)WebRequest.Create(uri); if (Credentials == null) { webRequest.UseDefaultCredentials = true; } else { webRequest.Credentials = Credentials; } try { var myWebResponse = webRequest.GetSyncResponse(_timeOut); using (var dataStream = myWebResponse.GetResponseStream()) { try { var bytes = BruTile.Utilities.ReadFully(dataStream); raster = new Raster(new MemoryStream(bytes), viewport.Extent); } catch (Exception ex) { Logger.Log(LogLevel.Error, ex.Message, ex); return(false); } } return(true); } catch (WebException ex) { Logger.Log(LogLevel.Warning, ex.Message, ex); if (!ContinueOnError) { throw (new RenderException( "There was a problem connecting to the ArcGISImage server", ex)); } Debug.WriteLine("There was a problem connecting to the WMS server: " + ex.Message); } catch (Exception ex) { if (!ContinueOnError) { throw (new RenderException("There was a problem while attempting to request the WMS", ex)); } Debug.WriteLine("There was a problem while attempting to request the WMS" + ex.Message); } return(false); }
/// <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 != 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(string.Empty, 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; }
private void UpdateRendererButton_Clicked(object sender, EventArgs e) { try { // Define the RasterLayer that will be used to display in the map. RasterLayer rasterLayerForDisplayInMap; // Define the ColorRamp that will be used by the BlendRenderer. ColorRamp colorRamp; // Get the user choice for the ColorRamps. string selection = Enum.GetNames(typeof(PresetColorRampType))[_colorRampsPicker.SelectedSegment]; // Based on ColorRamp type chosen by the user, create a different // RasterLayer and define the appropriate ColorRamp option. if (selection == "None") { // The user chose not to use a specific ColorRamp, therefore // need to create a RasterLayer based on general imagery (i.e. Shasta.tif) // for display in the map and use null for the ColorRamp as one of the // parameters in the BlendRenderer constructor. // Load the raster file using a path on disk. Raster rasterImagery = new Raster(DataManager.GetDataFolder("7c4c679ab06a4df19dc497f577f111bd", "raster-file", "Shasta.tif")); // Create the raster layer from the raster. rasterLayerForDisplayInMap = new RasterLayer(rasterImagery); // Set up the ColorRamp as being null. colorRamp = null; } else { // The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight), // therefore create a RasterLayer based on an imagery with elevation // (i.e. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp // based on the user choice, translated into an Enumeration, as one of the parameters // in the BlendRenderer constructor. // Load the raster file using a path on disk. Raster rasterElevation = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif")); // Create the raster layer from the raster. rasterLayerForDisplayInMap = new RasterLayer(rasterElevation); // Create a ColorRamp based on the user choice, translated into an Enumeration. PresetColorRampType myPresetColorRampType = (PresetColorRampType)Enum.Parse(typeof(PresetColorRampType), selection); colorRamp = ColorRamp.Create(myPresetColorRampType, 256); } // Define the parameters used by the BlendRenderer constructor. Raster rasterForMakingBlendRenderer = new Raster(DataManager.GetDataFolder("caeef9aa78534760b07158bb8e068462", "Shasta_Elevation.tif")); IEnumerable <double> myOutputMinValues = new List <double> { 9 }; IEnumerable <double> myOutputMaxValues = new List <double> { 255 }; IEnumerable <double> mySourceMinValues = new List <double>(); IEnumerable <double> mySourceMaxValues = new List <double>(); IEnumerable <double> myNoDataValues = new List <double>(); IEnumerable <double> myGammas = new List <double>(); // Get the user choice for the SlopeType. string slopeSelection = Enum.GetNames(typeof(SlopeType))[_slopeTypesPicker.SelectedSegment]; SlopeType mySlopeType = (SlopeType)Enum.Parse(typeof(SlopeType), slopeSelection); rasterLayerForDisplayInMap.Renderer = new BlendRenderer( rasterForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source. myOutputMinValues, // outputMinValues - Output stretch values, one for each band. myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band. mySourceMinValues, // sourceMinValues - Input stretch values, one for each band. mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band. myNoDataValues, // noDataValues - NoData values, one for each band. myGammas, // gammas - Gamma adjustment. colorRamp, // colorRamp - ColorRamp object to use, could be null. _altitudeSlider.Value, // altitude - Altitude angle of the light source. _azimuthSlider.Value, // azimuth - Azimuth angle of the light source, measured clockwise from north. 1, // zfactor - Factor to convert z unit to x,y units, default is 1. mySlopeType, // slopeType - Slope Type. 1, // pixelSizeFactor - Pixel size factor, default is 1. 1, // pixelSizePower - Pixel size power value, default is 1. 8); // outputBitDepth - Output bit depth, default is 8-bit. // Set the new base map to be the RasterLayer with the BlendRenderer applied. _map.Basemap = new Basemap(rasterLayerForDisplayInMap); } catch (Exception ex) { Console.WriteLine(ex); } }
/// <summary> /// Function that apply bloom filter to raster. /// </summary> /// <param name="rOriginal">Original raster.</param> /// <param name="worker">Background worker.</param> /// <returns>Modifyed raster.</returns> public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height); DateTime startTime = DateTime.Now; byte threshold = (byte)(this.lightThreshold * 255); VectorRgb color; //bright pass for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = rOriginal[i, j]; if (color.R > threshold || color.G > threshold || color.B > threshold) raster[i, j] = color; else raster[i, j] = new VectorRgb(0, 0, 0); } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } //blur SmoothingFilter filterSmoothing = new SmoothingFilter(ColorSpaceMode.RGB, this.blurRadius); raster = filterSmoothing.ProcessRaster(raster, worker); //processing (mixing original raster with blured light raster) for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = raster[i, j] * this.bloomBlendFactor; raster[i, j] = rOriginal[i, j] + color; } worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
/// <summary> /// Processing resample without Background Worker. /// </summary> /// <param name="rOriginal"></param> /// <returns></returns> public override Raster ProcessWithoutWorker(Raster rOriginal) { if (newx == 0 || newy == 0) return null; if (rOriginal.Width == newx && rOriginal.Height == newy) return new Raster(rOriginal);//copy float xScale, yScale, fX, fY; int widthOriginal = rOriginal.Width; int heightOriginal = rOriginal.Height; xScale = (float)widthOriginal / (float)newx; yScale = (float)heightOriginal / (float)newy; Raster newImage = new Raster(newx, newy); switch (this.mode) { #region nearest pixel case Cip.Transformations.CipInterpolationMode.NearestPixel: { // nearest pixel for (int y = 0; y < newy; y++) { fY = y * yScale; for (int x = 0; x < newx; x++) { fX = x * xScale; newImage[x, y] = rOriginal[(int)fX, (int)fY]; } } break; } #endregion nearest pixel #region bicubic spline interpolation case Cip.Transformations.CipInterpolationMode.BicubicSpline: { // bicubic interpolation by Blake L. Carlson <blake-carlson(at)uiowa(dot)edu float f_x, f_y, a, b, r1, r2; byte rr, gg, bb; int i_x, i_y, xx, yy; VectorRgb rgb; for (int y = 0; y < newy; y++) { f_y = (float)y * yScale - 0.5f; i_y = (int)Math.Floor(f_y); a = f_y - (float)Math.Floor(f_y); for (int x = 0; x < newx; x++) { f_x = (float)x * xScale - 0.5f; i_x = (int)Math.Floor(f_x); b = f_x - (float)Math.Floor(f_x); rr = gg = bb = 0; for (int m = -1; m < 3; m++) { r1 = CipInterpolationFunctions.KernelBSpline((float)m - a); yy = i_y + m; if (yy < 0) yy = 0; if (yy >= rOriginal.Height) yy = rOriginal.Height - 1; for (int n = -1; n < 3; n++) { r2 = r1 * CipInterpolationFunctions.KernelBSpline(b - (float)n); xx = i_x + n; if (xx < 0) xx = 0; if (xx >= rOriginal.Width) xx = rOriginal.Width - 1; rgb = rOriginal[xx, yy]; rr += (byte)(rgb.R * r2); gg += (byte)(rgb.G * r2); bb += (byte)(rgb.B * r2); }//end for n }//end for m newImage[x, y] = new VectorRgb(rr, gg, bb); }//end for x }//end for y break; } #endregion bicubic spline interpolation #region bilinear interpolation case Cip.Transformations.CipInterpolationMode.Bilinear: { // bilinear interpolation double fraction_x, fraction_y, one_minus_x, one_minus_y; int ceil_x, ceil_y, floor_x, floor_y; VectorRgb c1 = new VectorRgb(); VectorRgb c2 = new VectorRgb(); VectorRgb c3 = new VectorRgb(); VectorRgb c4 = new VectorRgb(); byte red, green, blue; byte b1, b2; for (int x = 0; x < newx; ++x) for (int y = 0; y < newy; ++y) { // Setup floor_x = (int)Math.Floor(x * xScale); floor_y = (int)Math.Floor(y * yScale); ceil_x = floor_x + 1; if (ceil_x >= widthOriginal) ceil_x = floor_x; ceil_y = floor_y + 1; if (ceil_y >= heightOriginal) ceil_y = floor_y; fraction_x = x * xScale - floor_x; fraction_y = y * yScale - floor_y; one_minus_x = 1.0f - fraction_x; one_minus_y = 1.0f - fraction_y; c1 = rOriginal[floor_x, floor_y]; c2 = rOriginal[ceil_x, floor_y]; c3 = rOriginal[floor_x, ceil_y]; c4 = rOriginal[ceil_x, ceil_y]; // Blue b1 = (byte)(one_minus_x * c1.B + fraction_x * c2.B); b2 = (byte)(one_minus_x * c3.B + fraction_x * c4.B); blue = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); // Green b1 = (byte)(one_minus_x * c1.G + fraction_x * c2.G); b2 = (byte)(one_minus_x * c3.G + fraction_x * c4.G); green = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); // Red b1 = (byte)(one_minus_x * c1.R + fraction_x * c2.R); b2 = (byte)(one_minus_x * c3.R + fraction_x * c4.R); red = (byte)(one_minus_y * (double)(b1) + fraction_y * (double)(b2)); newImage[x, y] = new VectorRgb(red, green, blue); } break; } #endregion bilinear interpolation default:// bilinear interpolation { // nearest pixel for (int y = 0; y < newy; y++) { fY = y * yScale; for (int x = 0; x < newx; x++) { fX = x * xScale; newImage[x, y] = rOriginal[(int)fX, (int)fY]; } } break; } }//end switch return newImage; }
private void cutColourPicBox_Click(object sender, EventArgs e) { this.clSelectedColour = Cip.CipTools.SelectColour(); Raster rastColour = new Raster(this.cutColourPicBox.Width, this.cutColourPicBox.Height, this.clSelectedColour); rastColour.ShowFilter(this.cutColourPicBox); }
protected internal override TextureType GetTextureType(Raster.Image image) { TextureType result; if (image is Raster.Bgra) result = TextureType.Rgba; else if (image is Raster.Bgr) result = TextureType.Rgb; else result = TextureType.Monochrome; return result; }
private void picBoxModifyed_MouseUp(object sender, MouseEventArgs e) { this.IsPictureHolded = false; //Under Construction, problem with stretch image, that less than pictureBox! if (this.picBoxModifyed.SizeMode == PictureBoxSizeMode.Normal) { Point location = e.Location; if (this.checkBoxPipette.Checked) { this.clSelectedColour = ((Bitmap)this.picBoxModifyed.Image).GetPixel(location.X, location.Y); Cip.CipTools.ShowPixelComponents(this.clSelectedColour, this.textBoxH, this.textBoxS, this.textBoxI, this.textBoxR, this.textBoxG, this.textBoxB); Raster rastColour = new Raster(this.cutColourPicBox.Width, this.cutColourPicBox.Height, this.clSelectedColour); rastColour.ShowFilter(this.cutColourPicBox); } if (this.checkBoxMoving.Checked) { } } }
/// <summary> /// Image processing with linear matrix filter. /// Without backgroundworker. /// </summary> public override Raster ProcessWithoutWorker(Raster rOriginal) { // define radius of filter by X int radiusX = kernel.GetLength(0) / 2; // define radius of filter by Y int radiusY = kernel.GetLength(1) / 2; //define width and height of image int width = rOriginal.Width; int height = rOriginal.Height; //create result raster Raster raster = new Raster(width, height); float r, g, b; byte R, G, B; VectorRgb rgb; int rk, rl; //processing for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { r = g = b = 0; for (int l = -radiusY; l <= radiusY; l++) for (int k = -radiusX; k <= radiusX; k++) if ((i + k) >= 0 && (i + k) < width && (j + l) < height && (j + l) >= 0) { rgb = rOriginal[i + k, j + l]; rk = k + radiusX; rl = l + radiusY; r += rgb.R * kernel[rk, rl]; g += rgb.G * kernel[rk, rl]; b += rgb.B * kernel[rk, rl]; } R = VectorRgb.ClampByte(r); G = VectorRgb.ClampByte(g); B = VectorRgb.ClampByte(b); raster[i, j] = new VectorRgb(R, G, B); } } //fill bound of raster /*for (int i = 0; i < width; i++) { raster[i, 0] = rOriginal[i, 0]; raster[i, height - 1] = rOriginal[i, height - 1]; } for (int j = 0; j < height; j++) { raster[0, j] = rOriginal[0, j]; raster[width - 1, j] = rOriginal[width - 1, j]; }*/ return raster; }
/// <summary> /// Executes the Erase Opaeration tool programaticaly /// Ping Yang deleted static for external testing 01/2010 /// </summary> /// <param name="input">The input raster</param> /// <param name="oldValue">The original double value representing no-data</param> /// <param name="newValue">The new double value representing no-data</param> /// <param name="output">The output raster</param> /// <param name="cancelProgressHandler">The progress handler</param> /// <returns></returns> public bool Execute(IRaster input, double oldValue, double newValue, IRaster output, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (input == null || newValue == 0 || output == null) { return(false); } Extent envelope = input.Bounds.Extent; int noOfCol = input.NumColumns; int noOfRow = input.NumRows; int previous = 0; Type dataType = input.DataType; // create output raster output = Raster.CreateRaster( output.Filename, string.Empty, noOfCol, noOfRow, 1, dataType, new[] { string.Empty }); RasterBounds bound = new RasterBounds(noOfRow, noOfCol, envelope); output.Bounds = bound; output.NoDataValue = newValue; // Loop throug every cell int max = output.Bounds.NumRows + 1; for (int i = 0; i < output.Bounds.NumRows; i++) { for (int j = 0; j < output.Bounds.NumColumns; j++) { if (input.Value[i, j] == oldValue) { output.Value[i, j] = newValue; } else { output.Value[i, j] = input.Value[i, j]; } 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); }
public override Raster ProcessRaster(Raster rOriginal, System.ComponentModel.BackgroundWorker worker) { worker.WorkerReportsProgress = true; int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height); DateTime startTime = DateTime.Now; //processing for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) raster[i, j] = sepiacolor * VectorRgb.Dot(rOriginal[i, j], luminance); worker.ReportProgress((int)(100f * i / width), DateTime.Now - startTime); } return raster; }
/// <summary> /// Writes the integer row array to the output raster. The square distance is /// converted to a normal distance. Unknown distance is converted to 'no data' value /// </summary> /// <param name="output"></param> /// <param name="rowNumber"></param> /// <param name="rowArray"></param> private static void WriteOutputRow(Raster<int> output, int rowNumber, int[] rowArray) { int noDataVal = (int)output.NoDataValue; for (int col = 0; col < rowArray.Length; col++) { int val = rowArray[col]; if (val == int.MaxValue) { output.Data[rowNumber][col] = noDataVal; } else { output.Data[rowNumber][col] = (int)Math.Sqrt(val); } } }
/// <summary> /// Paint Histogram. /// </summary> /// <param name="r">Raster object.</param> /// <param name="picBox">Picture box</param> /// <param name="color">Color.</param> /// <param name="text">text that painted on picture box</param> public static void PaintHistogram(Raster r, PictureBox picBox, Color color, string text) { Font font = new Font("Arial", 8, FontStyle.Bold); Rectangle rectangleOld = picBox.ClientRectangle; int intensityLevels = 256; //width should be as number if (rectangleOld.Width == intensityLevels) { int width = r.Width; int height = r.Height; int[] histogramOld; //calculates histogram. histogramOld = GetHistogram(r); //calculates maximum number of pixels that have definite level of intensity. int Maximum = CipMath.Maximum(histogramOld); //Graphics Old image Bitmap image = new Bitmap(256, rectangleOld.Height); Graphics graphicsOld = Graphics.FromImage(image); { SolidBrush brush = new SolidBrush(Color.White); graphicsOld.FillRectangle(brush, rectangleOld); Pen pen = new Pen(color, 1); double norm; int y2; for (int i = 0; i < intensityLevels; i++) { norm = (double)histogramOld[i] / Maximum; y2 = Convert.ToInt32(norm * rectangleOld.Height); graphicsOld.DrawLine(pen, i, rectangleOld.Height, i, rectangleOld.Height - y2); } //painting text using (LinearGradientBrush brushStr = new LinearGradientBrush(rectangleOld, Color.FromArgb(130, 255, 0, 0), Color.FromArgb(255, 0, 0, 255), LinearGradientMode.BackwardDiagonal)) { graphicsOld.DrawString(text, font, brushStr, rectangleOld); } } picBox.Image = image; } else MessageBox.Show("Width of PictureBox should be 256 or 258"); }
private async void Initialize() { // Create new map with the streets basemap Map myMap = new Map(Basemap.CreateStreets()); // Create a Uri to the image service raster Uri myUri = new Uri("https://sampleserver6.arcgisonline.com/arcgis/rest/services/NLCDLandCover2001/ImageServer"); // Create new image service raster from the Uri ImageServiceRaster myImageServiceRaster = new ImageServiceRaster(myUri); try { // Load the image service raster await myImageServiceRaster.LoadAsync(); // NOTE: This is the ASCII text for actual raw JSON string: // ======================================================== //{ // "raster_function_arguments": // { // "z_factor":{"double":25.0,"type":"Raster_function_variable"}, // "slope_type":{"raster_slope_type":"none","type":"Raster_function_variable"}, // "azimuth":{"double":315,"type":"Raster_function_variable"}, // "altitude":{"double":45,"type":"Raster_function_variable"}, // "type":"Raster_function_arguments", // "raster":{"name":"raster","is_raster":true,"type":"Raster_function_variable"}, // "nbits":{"int":8,"type":"Raster_function_variable"} // }, // "raster_function":{"type":"Hillshade_function"}, // "type":"Raster_function_template" //} // Define the JSON string needed for the raster function string theJSON_String = @"{ ""raster_function_arguments"": { ""z_factor"":{ ""double"":25.0,""type"":""Raster_function_variable""}, ""slope_type"":{ ""raster_slope_type"":""none"",""type"":""Raster_function_variable""}, ""azimuth"":{ ""double"":315,""type"":""Raster_function_variable""}, ""altitude"":{ ""double"":45,""type"":""Raster_function_variable""}, ""type"":""Raster_function_arguments"", ""raster"":{ ""name"":""raster"",""is_raster"":true,""type"":""Raster_function_variable""}, ""nbits"":{ ""int"":8,""type"":""Raster_function_variable""} }, ""raster_function"":{ ""type"":""Hillshade_function""}, ""type"":""Raster_function_template"" }"; // Create a raster function from the JSON string using the static/Shared method called: RasterFunction.FromJson(json as String) RasterFunction myRasterFunction = RasterFunction.FromJson(theJSON_String); // NOTE: Depending on your platform/device, you could have alternatively created the raster function via a JSON string that is contained in a // file on disk (ex: hillshade_simplified.json) via the constructor: Esri.ArcGISRuntime.Rasters.RasterFunction(path as String) // Get the raster function arguments RasterFunctionArguments myRasterFunctionArguments = myRasterFunction.Arguments; // Get the list of names from the raster function arguments IReadOnlyList <string> myRasterNames = myRasterFunctionArguments.GetRasterNames(); // Apply the first raster name and image service raster in the raster function arguments myRasterFunctionArguments.SetRaster(myRasterNames[0], myImageServiceRaster); // Create a new raster based on the raster function Raster myRaster = new Raster(myRasterFunction); // Create a new raster layer from the raster RasterLayer myRasterLayer = new RasterLayer(myRaster); // Add the raster layer to the maps layer collection myMap.Basemap.BaseLayers.Add(myRasterLayer); // Assign the map to the map view _myMapView.Map = myMap; // Get the service information (aka. metadata) about the image service raster ArcGISImageServiceInfo myArcGISImageServiceInfo = myImageServiceRaster.ServiceInfo; // Zoom the map to the extent of the image service raster (which also the extent of the raster layer) await _myMapView.SetViewpointGeometryAsync(myArcGISImageServiceInfo.FullExtent); // NOTE: The sample zooms to the extent of the ImageServiceRaster. Currently the ArcGIS Runtime does not // support zooming a RasterLayer out beyond 4 times it's published level of detail. The sample uses // MapView.SetViewpointCenterAsync() method to ensure the image shows when the app starts. You can see // the effect of the image service not showing when you zoom out to the full extent of the image and beyond. } catch (Exception e) { new AlertDialog.Builder(this).SetMessage(e.ToString()).SetTitle("Error").Show(); } }
private void Draw(string text, int size) { var raster = new Raster(_raster.PixelWidth, _raster.PixelHeight, _raster.PixelWidth, 72); var r = new Rasterizer(_typeface); if (DrawRaster) { r.Rasterize(text, size, raster, _toFlags); } _raster.WritePixels(Bounds(_raster), raster.Pixels, raster.Stride, 0); if (DrawOutline) { Segments = r.GetAllSegments(text, size, raster.Resolution).ToList(); } else { Segments = Enumerable.Empty<Segment>().ToList(); } }
/// <summary> /// Processing without background worker. /// </summary> public override Raster ProcessWithoutWorker(Raster rOriginal) { int width = rOriginal.Width; int height = rOriginal.Height; Raster raster = new Raster(width, height); byte threshold = (byte)(this.lightThreshold * 255); VectorRgb color; //bright pass for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = rOriginal[i, j]; if (color.R > threshold || color.G > threshold || color.B > threshold) raster[i, j] = color; else raster[i, j] = new VectorRgb(0, 0, 0); } } //blur SmoothingFilter filterSmoothing = new SmoothingFilter(ColorSpaceMode.RGB, this.blurRadius); raster = filterSmoothing.ProcessWithoutWorker(raster); //processing (mixing original raster with blured light raster) for (int i = 0; i < width; i++) { for (int j = 0; j < height; j++) { color = raster[i, j] * this.bloomBlendFactor; raster[i, j] = rOriginal[i, j] + color; } } return raster; }
public override Raster ProcessWithoutWorker(Raster rOriginal) { throw new NotImplementedException(); }
/// <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.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; }
/// <summary> /// Histogram calculating. /// </summary> /// <param name="r">Raster object.</param> /// <returns>Histogram array.</returns> public static int[] GetHistogram(Raster raster) { int width = raster.Width; int height = raster.Height; int[] aHistogram = new int[256]; int iIntensity; //calculates histogram for (int j = 0; j < height; j++) for (int i = 0; i < width; i++) { iIntensity = ColorspaceHelper.RGB2GRAYI(raster[i, j]); aHistogram[iIntensity]++; } return aHistogram; }
/// <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="extent">Force the raster to this specified extent.</param> /// <param name="cellSize">The double extent of the cell.</param> /// <param name="fieldName">The integer field index of the file.</param> /// <param name="outputFileName">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, Extent extent, double cellSize, string fieldName, string outputFileName, string driverCode, string[] options, IProgressHandler progressHandler) { Extent env = extent; if (cellSize == 0) { if (env.Width < env.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) { h = 8000; } Bitmap bmp = new(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(new Rectangle(0, 0, w, h), env, g); switch (fs.FeatureType) { case FeatureType.Polygon: { MapPolygonLayer mpl = new(fs); PolygonScheme ps = new(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; // first draw the normal colors and then the selection colors on top mpl.DrawRegions(args, new List <Extent> { env }, false); mpl.DrawRegions(args, new List <Extent> { env }, true); } break; case FeatureType.Line: { MapLineLayer mpl = new(fs); LineScheme ps = new(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; // first draw the normal colors and then the selection colors on top mpl.DrawRegions(args, new List <Extent> { env }, false); mpl.DrawRegions(args, new List <Extent> { env }, true); } break; default: { MapPointLayer mpl = new(fs); PointScheme ps = new(); colorTable = ps.GenerateUniqueColors(fs, fieldName); mpl.Symbology = ps; // first draw the normal colors and then the selection colors on top mpl.DrawRegions(args, new List <Extent> { env }, false); mpl.DrawRegions(args, new List <Extent> { env }, true); } break; } Type tp = fieldName == "FID" ? typeof(int) : fs.DataTable.Columns[fieldName].DataType; // We will try to convert to double if it is a string if (tp == typeof(string)) { tp = typeof(double); } InRamImageData image = new(bmp, env); ProgressMeter pm = new(progressHandler, "Converting To Raster Cells", h); var output = Raster.Create(outputFileName, driverCode, w, h, 1, tp, options); output.Bounds = new RasterBounds(h, w, env); double noDataValue = output.NoDataValue; if (fieldName != "FID") { // We can't use this method to calculate Max on a non-existent FID field. double dtMax = Convert.ToDouble(fs.DataTable.Compute("Max(" + fieldName + ")", string.Empty)); double dtMin = Convert.ToDouble(fs.DataTable.Compute("Min(" + fieldName + ")", string.Empty)); if (dtMin <= noDataValue && dtMax >= noDataValue) { if (dtMax != GetFieldValue(tp, "MaxValue")) { output.NoDataValue = noDataValue; } else if (dtMin != GetFieldValue(tp, "MinValue")) { output.NoDataValue = noDataValue; } } } List <RcIndex> locations = new(); List <string> failureList = new(); 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(); 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> /// Creates a featureset from the given raster. /// </summary> /// <param name="rst">Raster used for creation.</param> /// <param name="contourType">The contour type used for creation.</param> /// <param name="fieldName">Name of the field that gets added to the featureset to put the level values into.</param> /// <param name="levels">The levels to sort the features into.</param> /// <returns>The featureset that was created from the raster.</returns> public static FeatureSet Execute(Raster rst, ContourType contourType, string fieldName = "Value", double[] levels = null) { double[] lev = levels; noData = rst.NoDataValue; type = contourType; Raster iRst = RasterCheck(rst, lev); string field = fieldName ?? "Value"; double[] x = new double[rst.NumColumns]; double[] y = new double[rst.NumRows]; for (int i = 0; i < rst.NumColumns; i++) { x[i] = rst.Extent.MinX + (rst.CellWidth * i) + (rst.CellWidth / 2); } for (int i = 0; i < rst.NumRows; i++) { y[i] = rst.Extent.MaxY - (rst.CellHeight * i) - (rst.CellHeight / 2); } FeatureSet fs = null; switch (type) { case ContourType.Line: fs = new FeatureSet(FeatureType.Line); fs.DataTable.Columns.Add(field, typeof(double)); if (levels != null) { for (int z = 0; z < levels.Length; z++) { IList <IGeometry> cont = GetContours(ref iRst, x, y, lev[z]); foreach (var g in cont) { var f = (Feature)fs.AddFeature((ILineString)g); f.DataRow[field] = lev[z]; } } } break; case ContourType.Polygon: fs = new FeatureSet(FeatureType.Polygon); fs.DataTable.Columns.Add("Lev", typeof(int)); fs.DataTable.Columns.Add("Label", typeof(string)); Collection <IGeometry> contours = new Collection <IGeometry>(); if (levels != null) { for (int z = 0; z < levels.Length; z++) { IList <IGeometry> cont = GetContours(ref iRst, x, y, lev[z]); foreach (var g in cont) { contours.Add(new LineString(g.Coordinates)); } } Coordinate[] boundary = new Coordinate[5]; boundary[0] = new Coordinate(x[0], y[0]); boundary[1] = new Coordinate(x[0], y[rst.NumRows - 1]); boundary[2] = new Coordinate(x[rst.NumColumns - 1], y[rst.NumRows - 1]); boundary[3] = new Coordinate(x[rst.NumColumns - 1], y[0]); boundary[4] = new Coordinate(x[0], y[0]); contours.Add(new LineString(boundary)); Collection <IGeometry> nodedContours = new Collection <IGeometry>(); IPrecisionModel pm = new PrecisionModel(1000d); GeometryNoder geomNoder = new GeometryNoder(pm); foreach (var c in geomNoder.Node(contours)) { nodedContours.Add(c); } Polygonizer polygonizer = new Polygonizer(); polygonizer.Add(nodedContours); foreach (IPolygon p in polygonizer.GetPolygons().OfType <IPolygon>()) { IPoint pnt = p.InteriorPoint; int c = (int)((pnt.X - iRst.Extent.MinX) / iRst.CellWidth); int r = (int)((iRst.Extent.MaxY - pnt.Y) / iRst.CellHeight); double z = iRst.Value[r, c]; int cls = GetLevel(z, lev); string label = "Undefined"; if (cls == -1) { label = "< " + lev[0]; } else if (cls == lev.Length) { label = "> " + lev[lev.Length - 1]; } else if (cls >= 0 & cls < lev.Length) { label = lev[cls] + " - " + lev[cls + 1]; } IFeature f = fs.AddFeature(p); f.DataRow["Lev"] = cls; f.DataRow["Label"] = label; } } break; } return(fs); }
// This special case is for taking the outputs of a real raster into a fake one. public FakeRaster(Raster rRef) : base(rRef) { _inputgrid = new U[rRef.Extent.Rows, rRef.Extent.Cols]; _outputGrid = new U[rRef.Extent.Rows, rRef.Extent.Cols]; }
/// <summary> /// Gets the contours from the raster. /// </summary> /// <param name="rst">Raster to get the contours from.</param> /// <param name="x">The x values.</param> /// <param name="y">The y values.</param> /// <param name="zlev">Level to get the contours for.</param> /// <returns>The contours that were found.</returns> public static IList <IGeometry> GetContours(ref Raster rst, double[] x, double[] y, double zlev) { List <LineString> lsList = new List <LineString>(); double[] xx = new double[3]; double[] yy = new double[3]; double[] zz = new double[3]; for (int j = 0; j < rst.NumColumns - 1; j++) { bool jpari = (int)(j / 2.0) * 2 == j; for (int i = 0; i < rst.NumRows - 1; i++) { bool ipari = (int)(i / 2.0) * 2 == i; if (jpari == ipari) { xx[0] = x[j]; yy[0] = y[i]; zz[0] = rst.Value[i, j]; xx[1] = x[j]; yy[1] = y[i + 1]; zz[1] = rst.Value[i + 1, j]; xx[2] = x[j + 1]; yy[2] = y[i]; zz[2] = rst.Value[i, j + 1]; Coordinate[] c = Intersect(xx, yy, zz, zlev); if (c != null) { lsList.Add(new LineString(c)); } xx[0] = x[j + 1]; yy[0] = y[i]; zz[0] = rst.Value[i, j + 1]; xx[1] = x[j]; yy[1] = y[i + 1]; zz[1] = rst.Value[i + 1, j]; xx[2] = x[j + 1]; yy[2] = y[i + 1]; zz[2] = rst.Value[i + 1, j + 1]; Coordinate[] c1 = Intersect(xx, yy, zz, zlev); if (c1 != null) { lsList.Add(new LineString(c1)); } } else { xx[0] = x[j]; yy[0] = y[i]; zz[0] = rst.Value[i, j]; xx[1] = x[j]; yy[1] = y[i + 1]; zz[1] = rst.Value[i + 1, j]; xx[2] = x[j + 1]; yy[2] = y[i + 1]; zz[2] = rst.Value[i + 1, j + 1]; Coordinate[] c = Intersect(xx, yy, zz, zlev); if (c != null) { lsList.Add(new LineString(c)); } xx[0] = x[j]; yy[0] = y[i]; zz[0] = rst.Value[i, j]; xx[1] = x[j + 1]; yy[1] = y[i + 1]; zz[1] = rst.Value[i + 1, j + 1]; xx[2] = x[j + 1]; yy[2] = y[i]; zz[2] = rst.Value[i, j + 1]; Coordinate[] c1 = Intersect(xx, yy, zz, zlev); if (c1 != null) { lsList.Add(new LineString(c1)); } } } } LineMerger lm = new LineMerger(); lm.Add(lsList); IList <IGeometry> merged = lm.GetMergedLineStrings(); return(merged); }
private void OnUpdateRendererClicked(object sender, RoutedEventArgs e) { // Define the RasterLayer that will be used to display in the map RasterLayer rasterLayer_ForDisplayInMap; // Define the ColorRamp that will be used by the BlendRenderer ColorRamp myColorRamp; // Based on ColorRamp type chosen by the user, create a different // RasterLayer and define the appropriate ColorRamp option if (ColorRamps.SelectedValue.ToString() == "None") { // The user chose not to use a specific ColorRamp, therefore // need to create a RasterLayer based on general imagery (ie. Shasta.tif) // for display in the map and use null for the ColorRamp as one of the // parameters in the BlendRenderer constructor // Load the raster file using a path on disk Raster raster_Imagery = new Raster(GetRasterPath_Imagery()); // Create the raster layer from the raster rasterLayer_ForDisplayInMap = new RasterLayer(raster_Imagery); // Set up the ColorRamp as being null myColorRamp = null; } else { // The user chose a specific ColorRamp (options: are Elevation, DemScreen, DemLight), // therefore create a RasterLayer based on an imagery with elevation // (ie. Shasta_Elevation.tif) for display in the map. Also create a ColorRamp // based on the user choice, translated into an Enumeration, as one of the parameters // in the BlendRenderer constructor // Load the raster file using a path on disk Raster raster_Elevation = new Raster(GetRasterPath_Elevation()); // Create the raster layer from the raster rasterLayer_ForDisplayInMap = new RasterLayer(raster_Elevation); // Create a ColorRamp based on the user choice, translated into an Enumeration PresetColorRampType myPresetColorRampType = (PresetColorRampType)Enum.Parse(typeof(PresetColorRampType), ColorRamps.SelectedValue.ToString()); myColorRamp = ColorRamp.Create(myPresetColorRampType, 256); } // Define the parameters used by the BlendRenderer constructor Raster raster_ForMakingBlendRenderer = new Raster(GetRasterPath_Elevation()); IEnumerable <double> myOutputMinValues = new List <double> { 9 }; IEnumerable <double> myOutputMaxValues = new List <double> { 255 }; IEnumerable <double> mySourceMinValues = new List <double>(); IEnumerable <double> mySourceMaxValues = new List <double>(); IEnumerable <double> myNoDataValues = new List <double>(); IEnumerable <double> myGammas = new List <double>(); SlopeType mySlopeType = (SlopeType)Enum.Parse(typeof(SlopeType), SlopeTypes.SelectedValue.ToString()); BlendRenderer myBlendRenderer = new BlendRenderer( raster_ForMakingBlendRenderer, // elevationRaster - Raster based on a elevation source myOutputMinValues, // outputMinValues - Output stretch values, one for each band myOutputMaxValues, // outputMaxValues - Output stretch values, one for each band mySourceMinValues, // sourceMinValues - Input stretch values, one for each band mySourceMaxValues, // sourceMaxValues - Input stretch values, one for each band myNoDataValues, // noDataValues - NoData values, one for each band myGammas, // gammas - Gamma adjustment myColorRamp, // colorRamp - ColorRamp object to use, could be null Altitude_Slider.Value, // altitude - Altitude angle of the light source Azimuth_Slider.Value, // azimuth - Azimuth angle of the light source, measured clockwise from north 1, // zfactor - Factor to convert z unit to x,y units, default is 1 mySlopeType, // slopeType - Slope Type 1, // pixelSizeFactor - Pixel size factor, default is 1 1, // pixelSizePower - Pixel size power value, default is 1 8); // outputBitDepth - Output bit depth, default is 8-bi // Set the RasterLayer.Renderer to be the BlendRenderer rasterLayer_ForDisplayInMap.Renderer = myBlendRenderer; // Set the new base map to be the RasterLayer with the BlendRenderer applied MyMapView.Map.Basemap = new Basemap(rasterLayer_ForDisplayInMap); }
/// <summary> /// Executes the slope generation raster. /// </summary> /// <param name="raster">The input altitude raster.</param> /// <param name="inZFactor">The double precision multiplicative scaling factor for elevation values.</param> /// <param name="slopeInPercent">A boolean parameter that clarifies the nature of the slope values. If this is true, the values represent percent slope.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>The output slope raster, or null if the process was unsuccessful.</returns> public static IRaster GetSlope(IRaster raster, double inZFactor, bool slopeInPercent, ICancelProgressHandler cancelProgressHandler) { // Validates the input and output data if (raster == null) { return(null); } int noOfCol = raster.NumColumns; int noOfRow = raster.NumRows; // Create the new raster with the appropriate dimensions var result = Raster.CreateRaster("SlopeRaster.bgd", string.Empty, noOfCol, noOfRow, 1, typeof(double), new[] { string.Empty }); result.NoDataValue = raster.NoDataValue; result.Bounds = raster.Bounds; result.Projection = raster.Projection; ProgressMeter progMeter = null; try { if (cancelProgressHandler != null) { progMeter = new ProgressMeter(cancelProgressHandler, "Calculating Slope", result.NumRows); } // Cache cell size for faster access var cellWidth = raster.CellWidth; var cellHeight = raster.CellHeight; for (int i = 0; i < result.NumRows; i++) { if (cancelProgressHandler != null) { progMeter.Next(); if ((i % 100) == 0) { progMeter.SendProgress(); // HACK: DoEvents messes up the normal flow of your application. Application.DoEvents(); } } for (int j = 0; j < result.NumColumns; j++) { if (i > 0 && i < result.NumRows - 1 && j > 0 && j < result.NumColumns - 1) { double z1 = raster.Value[i - 1, j - 1]; double z2 = raster.Value[i - 1, j]; double z3 = raster.Value[i - 1, j + 1]; double z4 = raster.Value[i, j - 1]; double z5 = raster.Value[i, j + 1]; double z6 = raster.Value[i + 1, j - 1]; double z7 = raster.Value[i + 1, j]; double z8 = raster.Value[i + 1, j + 1]; // 3rd Order Finite Difference slope algorithm double dZdX = inZFactor * ((z3 - z1) + (2 * (z5 - z4)) + (z8 - z6)) / (8 * cellWidth); double dZdY = inZFactor * ((z1 - z6) + (2 * (z2 - z7)) + (z3 - z8)) / (8 * cellHeight); double slope = Math.Atan(Math.Sqrt((dZdX * dZdX) + (dZdY * dZdY))) * (180 / Math.PI); // change to radius and in percentage if (slopeInPercent) { slope = Math.Tan(slope * Math.PI / 180) * 100; } result.Value[i, j] = slope; if (cancelProgressHandler != null && cancelProgressHandler.Cancel) { return(null); } } else { result.Value[i, j] = result.NoDataValue; } if (cancelProgressHandler != null && cancelProgressHandler.Cancel) { return(null); } } } if (result.IsFullyWindowed()) { result.Save(); return(result); } return(null); } finally { if (progMeter != null) { progMeter.Reset(); Application.DoEvents(); } } }
public static async Task <IList <BA_Objects.Interval> > ReadReclassRasterAttribute(Uri gdbUri, string rasterName) { IList <BA_Objects.Interval> lstInterval = new List <BA_Objects.Interval>(); await QueuedTask.Run(() => { using (Geodatabase geodatabase = new Geodatabase(new FileGeodatabaseConnectionPath(gdbUri))) using (RasterDataset rasterDataset = geodatabase.OpenDataset <RasterDataset>(rasterName)) { RasterBandDefinition bandDefinition = rasterDataset.GetBand(0).GetDefinition(); Tuple <double, double> tupleSize = bandDefinition.GetMeanCellSize(); if (Math.Round(tupleSize.Item1, 5) != Math.Round(tupleSize.Item2, 5)) { ArcGIS.Desktop.Framework.Dialogs.MessageBox.Show("The X and Y cell size values are not the same for " + gdbUri.LocalPath + "\\" + rasterName + ". This may cause problems with some BAGIS functions!!", "BAGIS-PRO"); } double cellSize = (tupleSize.Item1 + tupleSize.Item2) / 2; Raster raster = rasterDataset.CreateDefaultRaster(); using (Table rasterTable = raster.GetAttributeTable()) { TableDefinition definition = rasterTable.GetDefinition(); int idxName = definition.FindField(Constants.FIELD_NAME); int idxLowerBound = definition.FindField(Constants.FIELD_LBOUND); int idxUpperBound = definition.FindField(Constants.FIELD_UBOUND); int idxCount = definition.FindField(Constants.FIELD_COUNT); using (RowCursor cursor = rasterTable.Search()) { while (cursor.MoveNext()) { BA_Objects.Interval interval = new BA_Objects.Interval(); Row row = cursor.Current; interval.Value = row[Constants.FIELD_VALUE]; if (idxName > 0) { interval.Name = Convert.ToString(row[idxName]); } else { interval.Name = Constants.VALUE_UNKNOWN; } if (idxUpperBound > 0) { interval.UpperBound = Convert.ToDouble(row[idxUpperBound]); } if (idxLowerBound > 0) { interval.LowerBound = Convert.ToDouble(row[idxLowerBound]); } if (idxCount > 0) { interval.Area = cellSize *Convert.ToInt32(row[idxCount]); } lstInterval.Add(interval); } } } } }); return(lstInterval); }
private async void Initialize() { // Create a map with a streets basemap. Map map = new Map(Basemap.CreateStreets()); // Get the file name for the local raster dataset. string filepath = GetRasterPath(); // Load the raster file Raster rasterFile = new Raster(filepath); // Create a new raster layer to show the image. _rasterLayer = new RasterLayer(rasterFile); try { // Once the layer is loaded, enable the button to apply a new renderer. await _rasterLayer.LoadAsync(); ApplyRgbRendererButton.IsEnabled = true; // Create a viewpoint with the raster's full extent. Viewpoint fullRasterExtent = new Viewpoint(_rasterLayer.FullExtent); // Set the initial viewpoint for the map. map.InitialViewpoint = fullRasterExtent; // Add the layer to the map. map.OperationalLayers.Add(_rasterLayer); // Add the map to the map view. MyMapView.Map = map; // Add available stretch types to the combo box. StretchTypeComboBox.Items.Add("Min Max"); StretchTypeComboBox.Items.Add("Percent Clip"); StretchTypeComboBox.Items.Add("Standard Deviation"); // Select "Min Max" as the stretch type. StretchTypeComboBox.SelectedIndex = 0; // Create a range of values from 0-255. List <int> minMaxValues = Enumerable.Range(0, 256).ToList(); // Fill the min and max red combo boxes with the range and set default values. MinRedComboBox.ItemsSource = minMaxValues; MinRedComboBox.SelectedValue = 0; MaxRedComboBox.ItemsSource = minMaxValues; MaxRedComboBox.SelectedValue = 255; // Fill the min and max green combo boxes with the range and set default values. MinGreenComboBox.ItemsSource = minMaxValues; MinGreenComboBox.SelectedValue = 0; MaxGreenComboBox.ItemsSource = minMaxValues; MaxGreenComboBox.SelectedValue = 255; // Fill the min and max blue combo boxes with the range and set default values. MinBlueComboBox.ItemsSource = minMaxValues; MinBlueComboBox.SelectedValue = 0; MaxBlueComboBox.ItemsSource = minMaxValues; MaxBlueComboBox.SelectedValue = 255; // Fill the standard deviation factor combo box and set a default value. IEnumerable <int> wholeStdDevs = Enumerable.Range(1, 10); List <double> halfStdDevs = wholeStdDevs.Select(i => (double)i / 2).ToList(); StdDeviationFactorComboBox.ItemsSource = halfStdDevs; StdDeviationFactorComboBox.SelectedValue = 2.0; } catch (Exception e) { MessageBox.Show(e.ToString(), "Error"); } }
public void RasterizedVectorComplexTest() { Raster rOld = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\2005DecDEM.tif"))); Raster rNew = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\2006FebDEM.tif"))); Raster rOldErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2005DecDEM\ErrorSurfaces\Constant01\Constant01.tif"))); Raster rNewErr = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\inputs\2006FebDEM\ErrorSurfaces\Constant02\Constant02.tif"))); Raster rDoD = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\Analyses\CD\GCD0001\raw.tif"))); Raster rThresh = new Raster(new FileInfo(DirHelpers.GetTestRootPath(@"VerificationProject\Analyses\CD\GCD0001\thresh.tif"))); // And now the budget seg case Vector vPolyMask = new Vector(new FileInfo(DirHelpers.GetTestRootPath(@"SulphurGCDMASK\Sulphur_ComplexGCDMask.shp"))); UnitGroup ug = new UnitGroup(VolumeUnit.CubicMeter, AreaUnit.SquareMeter, LengthUnit.Meter, LengthUnit.Meter); List <string> times = new List <string> { }; var watch = Stopwatch.StartNew(); using (ITempDir tmp = TempDir.Create()) { FileInfo fiPolyMaskCopy = new FileInfo(Path.Combine(tmp.Name, "Sulphur_ComplexGCDMask.shp")); vPolyMask.Copy(fiPolyMaskCopy); Vector vPolyMaskCopy = new Vector(fiPolyMaskCopy); Raster rPropErr = RasterOperators.RootSumSquares(rOldErr, rNewErr, new FileInfo(Path.Combine(tmp.Name, "PropErr.tif"))); watch.Restart(); Dictionary <string, Histogram> binRasterV = RasterOperators.BinRaster(rDoD, 100, vPolyMaskCopy, "Desc_", null, false); times.Add(string.Format("BinRaster, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, Histogram> binRasterR = RasterOperators.BinRaster(rDoD, 100, vPolyMaskCopy, "Desc_"); times.Add(string.Format("BinRaster, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsPropV = RasterOperators.GetStatsPropagated(rDoD, rPropErr, vPolyMaskCopy, "Desc_", ug, null, false); times.Add(string.Format("GetStatsPropagated, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsPropR = RasterOperators.GetStatsPropagated(rDoD, rPropErr, vPolyMaskCopy, "Desc_", ug); times.Add(string.Format("GetStatsPropagated, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> minlodV = RasterOperators.GetStatsMinLoD(rDoD, 0.2m, vPolyMaskCopy, "Desc_", ug, null, false); times.Add(string.Format("GetStatsMinLoD, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> minlodR = RasterOperators.GetStatsMinLoD(rDoD, 0.2m, vPolyMaskCopy, "Desc_", ug); times.Add(string.Format("GetStatsMinLoD, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsprobV = RasterOperators.GetStatsProbalistic(rDoD, rThresh, rPropErr, vPolyMaskCopy, "Desc_", ug, null, false); times.Add(string.Format("GetStatsProbalistic, Vector, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); watch.Restart(); Dictionary <string, DoDStats> statsprobR = RasterOperators.GetStatsProbalistic(rDoD, rThresh, rPropErr, vPolyMaskCopy, "Desc_", ug); times.Add(string.Format("GetStatsProbalistic, Rasterized, {0}.{1}", watch.Elapsed.Seconds, watch.Elapsed.Milliseconds)); foreach (string line in times) { Debug.WriteLine(line); } } }
private void cutColourPicBox_MouseLeave(object sender, EventArgs e) { Raster rastColour = new Raster(this.cutColourPicBox.Width, this.cutColourPicBox.Height, this.clSelectedColour); rastColour.ShowFilter(this.cutColourPicBox); }