コード例 #1
0
        /// <summary>
        /// 获取马赛克块的颜色。
        /// 该颜色为对应源贴图上像素颜色的平均值。
        /// </summary>
        /// <param name="outputBlock">输出贴图上的马赛克块。</param>
        /// <param name="outputWidth">输出贴图的宽度。</param>
        /// <param name="outputHeight">输出贴图的高度。</param>
        /// <param name="sourceWidth">源贴图的宽度。</param>
        /// <param name="sourceHeight">源贴图的高度。</param>
        /// <param name="sourceColors">源贴图颜色数组。</param>
        /// <returns>颜色值。</returns>
        private static Color GetMosaicBlockColor(PixelBlock outputBlock, int outputWidth, int outputHeight,
                                                 int sourceWidth, int sourceHeight, Color[] sourceColors)
        {
            float factH          = 1.0f * sourceHeight / outputHeight;
            float factW          = 1.0f * sourceWidth / outputWidth;
            int   sourceStartRow = Mathf.FloorToInt(outputBlock.StartRow * factH + 0.0001f);
            int   sourceEndRow   = Mathf.CeilToInt(outputBlock.EndRow * factH - 0.0001f);
            int   sourceStartCol = Mathf.FloorToInt(outputBlock.StartCol * factW + 0.0001f);
            int   sourceEndCol   = Mathf.CeilToInt(outputBlock.EndCol * factW - 0.0001f);

            float r = 0;
            float g = 0;
            float b = 0;
            float a = 0;

            for (int i = sourceStartRow; i <= sourceEndRow; i++)
            {
                for (int j = sourceStartCol; j <= sourceEndCol; j++)
                {
                    int sourceIndex = i * sourceWidth + j;
                    r += sourceColors[sourceIndex].r;
                    g += sourceColors[sourceIndex].g;
                    b += sourceColors[sourceIndex].b;
                    a += sourceColors[sourceIndex].a;
                }
            }

            int number = (sourceEndRow - sourceStartRow + 1) * (sourceEndCol - sourceStartCol + 1);

            return(new Color(r / number, g / number, b / number, a / number));
        }
コード例 #2
0
        /// <summary>
        /// Finds filpped block according to vector in dictionary and saves it in dictionary with vector of movment so it could be easier to find when searching filpped block of that block.
        /// </summary>
        /// <param name="block"></param>
        /// <param name="referentBlock"></param>
        /// <param name="image"></param>
        /// <param name="dictionary"></param>
        /// <returns></returns>
        public static PixelBlock?FindFlippedAndAddToVectorDictionary(this PixelBlock block,
                                                                     PixelBlock referentBlock, Image image, IDictionary <PixelBlock, Vector> dictionary)
        {
            if (!dictionary.ContainsKey(block))
            {
                return(null);
            }
            var vector = dictionary[block];
            var flip   = new Point(block.Position.X + vector.X, block.Position.Y + vector.Y);

            if (referentBlock.IsInSearchWindow(flip, MedicalDiamondSearchSettings.SearchParameterP,
                                               MedicalDiamondSearchSettings.BlockSize, image.Width, image.Height))
            {
                var pixelBlock = image.Blocks[flip];
                if (pixelBlock.Equals(block))
                {
                    return(null);
                }
                if (!dictionary.ContainsKey(pixelBlock))
                {
                    dictionary.Add(pixelBlock, vector);
                }
                return(pixelBlock);
            }
            return(null);
        }
コード例 #3
0
        /// <summary>
        /// Write results to a rester.
        /// </summary>
        /// <param name="raster">DEM raster</param>
        /// <param name="outputDataStore">Output datastore</param>
        /// <param name="result">Elevation map with resuluts</param>
        private void WriteToRaster(Raster raster, FileSystemDatastore outputDataStore, GeoMap result)
        {
            raster.SetNoDataValue(0);
            raster.SetPixelType(RasterPixelType.DOUBLE);
            RasterDataset resultRasterDataset = raster.SaveAs(tmpRasterName, outputDataStore, rasterFormat);

            GarbageHelper.Instance.AddGarbage(Path.Combine(outputFolder, tmpRasterName));
            Raster resultRaster = resultRasterDataset.CreateRaster(new int[1] {
                0
            });

            resultRaster.Refresh();

            if (!resultRaster.CanEdit())
            {
                MessageBox.Show("Cannot write to raster", "Error", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Error);
                return;
            }
            PixelBlock pixelBlock = resultRaster.CreatePixelBlock(resultRaster.GetWidth(), resultRaster.GetHeight());

            resultRaster.Read(0, 0, pixelBlock);
            pixelBlock.Clear(0);
            Array pixel = new double[resultRaster.GetWidth(), resultRaster.GetHeight()];

            pixelBlock.SetPixelData(0, result.Transpose());

            resultRaster.Write(0, 0, pixelBlock);
            resultRaster.Refresh();
            resultRaster.SaveAs(SettingsManager.Instance.CurrentSettings.OutputFilename, outputDataStore, rasterFormat);
        }
コード例 #4
0
    /// <summary>
    /// Creates a new average PixelBlock GameObject where the user points to.
    /// </summary>
    /// <param name="currentRowCol"> The rowcol needed to move and shape this pixelblock </param>
    private void InstantiateNewPixelBlock(Vector2 selectedXZ)
    {
        GameObject newPBGameObj = Instantiate(Resources.Load("Prefabs/AveragePixelBlock"), new Vector3(0, 0, 0), Quaternion.identity) as GameObject;
        PixelBlock newPB        = newPBGameObj.GetComponent <PixelBlock>();

        newPB.gameObject.SetActive(true);
        newPB.Start(); //Note: Have to do this to ensure the lineRenderer is created and the PB is shaped correctly

        averagePixelBlocks.Add(newPBGameObj);
        newPB.MoveShapeDrawFromXZ(selectedXZ.x, selectedXZ.y);
    }
コード例 #5
0
 /// <summary>
 /// Calculates if given block(calculated from point) is inside search window(according to given center block) and if it is inside image.
 /// </summary>
 /// <param name="center"></param>
 /// <param name="pixelBlockPoint"></param>
 /// <param name="parametar"></param>
 /// <param name="blockSize"></param>
 /// <param name="pictureWidth"></param>
 /// <param name="pictureHeight"></param>
 /// <returns></returns>
 public static bool IsInSearchWindow(this PixelBlock center, Point pixelBlockPoint, int parametar, int blockSize, int pictureWidth, int pictureHeight)
 {
     return(pixelBlockPoint.X >= 0 &&
            pixelBlockPoint.X >= center.Position.X - parametar * blockSize &&
            pixelBlockPoint.X <= center.Position.X + parametar * blockSize &&
            pixelBlockPoint.X <= pictureWidth - blockSize &&
            pixelBlockPoint.Y >= 0 &&
            pixelBlockPoint.Y >= center.Position.Y - parametar * blockSize &&
            pixelBlockPoint.Y <= center.Position.Y + parametar * blockSize &&
            pixelBlockPoint.Y <= pictureHeight - blockSize);
 }
コード例 #6
0
 /// <summary>
 /// Diamond Search Algorithm.
 /// </summary>
 /// <param name="referentBlock"></param>
 /// <param name="centerBlock"></param>
 /// <param name="image"></param>
 /// <returns></returns>
 private static Vector CalculateVector(PixelBlock referentBlock, PixelBlock centerBlock, Image image)
 {
     while (true)
     {
         Diamond diamond = new LargeDiamond(referentBlock, centerBlock, image);
         var     mins    = diamond.GetMinimums();
         if (diamond.IsCenterBlock(mins.Minimum))
         {
             diamond = new SmallDiamond(referentBlock, centerBlock, image);
             mins    = diamond.GetMinimums();
             return(new Vector(referentBlock.Position, mins.Minimum.Position));
         }
         centerBlock = mins.Minimum;
     }
 }
コード例 #7
0
        /// <summary>
        /// 为目标贴图上的一个马赛克块填充颜色。
        /// </summary>
        /// <param name="outputBlock"></param>
        /// <param name="outputWidth">输出贴图宽度。</param>
        /// <param name="outputHeight">输出贴图高度。</param>
        /// <param name="outpuColors">输出贴图像素数组。</param>
        /// <param name="sourceWidth">源贴图宽度。</param>
        /// <param name="sourceHeight">源贴图高度。</param>
        /// <param name="sourceColors">源贴图像素数组。</param>
        private static void FillMosaicBlock(PixelBlock outputBlock,
                                            int outputWidth, int outputHeight, ref Color[] outpuColors,
                                            int sourceWidth, int sourceHeight, Color[] sourceColors)
        {
            Color blockColor = GetMosaicBlockColor(outputBlock, outputWidth, outputHeight,
                                                   sourceWidth, sourceHeight, sourceColors);

            for (int i = outputBlock.StartRow; i <= outputBlock.EndRow; i++)
            {
                for (int j = outputBlock.StartCol; j <= outputBlock.EndCol; j++)
                {
                    outpuColors[i * outputWidth + j] = blockColor;
                }
            }
        }
コード例 #8
0
        /// <summary>
        /// Convert the DEM raster to internal elevation map.
        /// </summary>
        /// <param name="raster">DEM raster</param>
        /// <returns>Elevation map</returns>
        private GeoMap CreateElevationMap(Raster raster)
        {
            PixelBlock currentPixelBlock = raster.CreatePixelBlock(raster.GetWidth(), raster.GetHeight());

            raster.Read(0, 0, currentPixelBlock);

            Array pixels = currentPixelBlock.GetPixelData(0, false);

            GeoMap elevationMap             = new GeoMap(raster.GetHeight(), raster.GetWidth());
            Tuple <double, double> cellSize = raster.GetMeanCellSize();

            /*if (Math.Abs(cellSize.Item1-cellSize.Item2) < cellSize.Item1*0.05) {
             *  MessageBox.Show("Cells are not squares. Using X size of cells.", "Rectuangular cells", System.Windows.MessageBoxButton.OK, System.Windows.MessageBoxImage.Information);
             * }*/
            elevationMap.CellSize = cellSize.Item1;
            elevationMap.ImportData(pixels);
            return(elevationMap);
        }
コード例 #9
0
        //--------------------------------------------------
        // 对贴图进行马赛克处理。
        //--------------------------------------------------

        /// <summary>
        /// 对贴图进行马赛克处理。
        /// </summary>
        /// <param name="source">源贴图。</param>
        /// <param name="output">输出贴图。</param>
        /// <param name="mosaicSize">马赛克大小(像素)。</param>
        public static void Mosaics(Texture2D source, ref Texture2D output, int mosaicSize)
        {
            Color[] sourceColors = source.GetPixels();
            var     outputColors = new Color[output.width * output.height];

            mosaicSize = Mathf.Max(mosaicSize, 1);

            int blockCols = Mathf.CeilToInt(1.0f * output.width / mosaicSize - 0.0001f);
            int blockRow  = Mathf.CeilToInt(1.0f * output.height / mosaicSize - 0.0001f);

            for (int i = 0; i < blockRow; i++)
            {
                for (int j = 0; j < blockCols; j++)
                {
                    PixelBlock outputBlock = CreateMosaicBlock(i, j, output.width, output.height, mosaicSize);
                    FillMosaicBlock(outputBlock,
                                    output.width, output.height, ref outputColors, source.width, source.height,
                                    sourceColors);
                }
            }

            output.SetPixels(outputColors);
            output.Apply();
        }
コード例 #10
0
 public MinimumPair(PixelBlock minimum, PixelBlock secondMinimum, double treshold)
 {
     Minimum       = minimum;
     SecondMinimum = secondMinimum;
     Treshold      = treshold;
 }
コード例 #11
0
        /// <summary>
        /// Mask raster pixels based on the rectangle given and save the output in the
        /// current project folder.
        /// </summary>
        /// <param name="geometry">Rectangle to use to mask raster pixels.</param>
        public static async void MaskRaster(Geometry geometry)
        {
            try
            {
                // Check if there is an active map view.
                if (MapView.Active != null)
                {
                    // Get the active map view.
                    var mapView = MapView.Active;
                    // Get the list of selected layers.
                    IReadOnlyList <Layer> selectedLayerList = mapView.GetSelectedLayers();
                    if (selectedLayerList.Count == 0)
                    {
                        // If no layers are selected show a message box with the appropriate message.
                        MessageBox.Show("No Layers selected. Please select one Raster layer.");
                    }
                    else
                    {
                        // Get the most recently selected layer.
                        Layer firstSelectedLayer = mapView.GetSelectedLayers().First();
                        if (firstSelectedLayer is RasterLayer)
                        {
                            // Working with rasters requires the MCT.
                            await QueuedTask.Run(() =>
                            {
                                #region Get the raster dataset from the currently selected layer
                                // Get the raster layer from the selected layer.
                                RasterLayer currentRasterLayer = firstSelectedLayer as RasterLayer;
                                // Get the raster from the current selected raster layer.
                                Raster inputRaster = currentRasterLayer.GetRaster();
                                // Get the basic raster dataset from the raster.
                                BasicRasterDataset basicRasterDataset = inputRaster.GetRasterDataset();
                                if (!(basicRasterDataset is RasterDataset))
                                {
                                    // If the dataset is not a raster dataset, show a message box with the appropriate message.
                                    MessageBox.Show("No Raster Layers selected. Please select one Raster layer.");
                                    return;
                                }
                                // Get the input raster dataset from the basic raster dataset.
                                RasterDataset rasterDataset = basicRasterDataset as RasterDataset;
                                #endregion

                                #region Save a copy of the raster dataset in the project folder and open it
                                // Create a full raster from the input raster dataset.
                                inputRaster = rasterDataset.CreateFullRaster();
                                // Setup the paths and name of the output file and folder inside the project folder.
                                string ouputFolderName = "MaskedOuput";
                                string outputFolder    = Path.Combine(Project.Current.HomeFolderPath, ouputFolderName);;
                                string outputName      = "MaskedRaster.tif";
                                // Delete the output directory if it exists and create it.
                                // Note: You will need write access to the project directory for this sample to work.
                                if (Directory.Exists(outputFolder))
                                {
                                    Directory.Delete(outputFolder, true);
                                }
                                Directory.CreateDirectory(outputFolder);

                                // Create a new file system connection path to open raster datasets using the output folder path.
                                FileSystemConnectionPath outputConnectionPath = new FileSystemConnectionPath(
                                    new System.Uri(outputFolder), FileSystemDatastoreType.Raster);
                                // Create a new file system data store for the connection path created above.
                                FileSystemDatastore outputFileSytemDataStore = new FileSystemDatastore(outputConnectionPath);
                                // Create a new raster storage definition.
                                RasterStorageDef rasterStorageDef = new RasterStorageDef();
                                // Set the pyramid level to 0 meaning no pyramids will be calculated. This is required
                                // because we are going to change the pixels after we save the raster dataset and if the
                                // pyramids are calculated prior to that, the pyramids will be incorrect and will have to
                                // be recalculated.
                                rasterStorageDef.SetPyramidLevel(0);
                                // Save a copy of the raster using the file system data store and the raster storage definition.
                                inputRaster.SaveAs(outputName, outputFileSytemDataStore, "TIFF", rasterStorageDef);

                                // Open the raster dataset you just saved.
                                rasterDataset = OpenRasterDataset(outputFolder, outputName);
                                // Create a full raster from it so we can modify pixels.
                                Raster outputRaster = rasterDataset.CreateFullRaster();
                                #endregion

                                #region Get the Min/Max Row/Column to mask
                                // If the map spatial reference is different from the spatial reference of the input raster,
                                // set the map spatial reference on the input raster. This will ensure the map points are
                                // correctly reprojected to image points.
                                if (mapView.Map.SpatialReference.Name != inputRaster.GetSpatialReference().Name)
                                {
                                    inputRaster.SetSpatialReference(mapView.Map.SpatialReference);
                                }

                                // Use the MapToPixel method of the input raster to get the row and column values for the
                                // points of the rectangle.
                                Tuple <int, int> tlcTuple = inputRaster.MapToPixel(geometry.Extent.XMin, geometry.Extent.YMin);
                                Tuple <int, int> lrcTuple = inputRaster.MapToPixel(geometry.Extent.XMax, geometry.Extent.YMax);

                                int minCol = (int)tlcTuple.Item1;
                                int minRow = (int)tlcTuple.Item2;
                                int maxCol = (int)lrcTuple.Item1;
                                int maxRow = (int)lrcTuple.Item2;

                                // Ensure the min's are less than the max's.
                                if (maxCol < minCol)
                                {
                                    int temp = maxCol;
                                    maxCol   = minCol;
                                    minCol   = temp;
                                }

                                if (maxRow < minRow)
                                {
                                    int temp = maxRow;
                                    maxRow   = minRow;
                                    minRow   = temp;
                                }
                                // Ensure the mins and maxs are within the raster.
                                minCol = (minCol < 0) ? 0 : minCol;
                                minRow = (minRow < 0) ? 0 : minRow;
                                maxCol = (maxCol > outputRaster.GetWidth()) ? outputRaster.GetWidth() : maxCol;
                                maxRow = (maxRow > outputRaster.GetHeight()) ? outputRaster.GetHeight() : maxRow;
                                #endregion

                                #region Mask pixels based on the rectangle drawn by the user
                                // Calculate the width and height of the pixel block to create.
                                int pbWidth  = maxCol - minCol;
                                int pbHeight = maxRow - minRow;
                                // Check to see if the output raster can be edited.
                                if (!outputRaster.CanEdit())
                                {
                                    // If not, show a message box with the appropriate message.
                                    MessageBox.Show("Cannot edit raster :(");
                                    return;
                                }
                                // Create a new pixel block from the output raster of the height and width calculated above.
                                PixelBlock currentPixelBlock = outputRaster.CreatePixelBlock(pbWidth, pbHeight);
                                // Iterate over the bands of the output raster.
                                for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++)
                                {
                                    // For each band, clear the pixel block.
                                    currentPixelBlock.Clear(plane);
                                    //Array noDataMask = currentPixelBlock.GetNoDataMask(plane, true);
                                    //for (int i = 0; i < noDataMask.GetLength(0); i++)
                                    //    noDataMask.SetValue(Convert.ToByte(0), i);
                                    //currentPixelBlock.SetNoDataMask(plane, noDataMask);
                                }
                                // Write the cleared pixel block to the output raster dataset.
                                outputRaster.Write(minCol, minRow, currentPixelBlock);
                                // Refresh the properties of the output raster dataset.
                                outputRaster.Refresh();
                                #endregion

                                // Create a new layer from the masked raster dataset and add it to the map.
                                LayerFactory.Instance.CreateLayer(new Uri(Path.Combine(outputFolder, outputName)),
                                                                  mapView.Map);
                                // Disable the layer representing the original raster dataset.
                                firstSelectedLayer.SetVisibility(false);
                            });
                        }
                        else
                        {
                            // If the selected layer is not a raster layer show a message box with the appropriate message.
                            MessageBox.Show("No Raster layers selected. Please select one Raster layer.");
                        }
                    }
                }
            }
            catch (Exception exc)
            {
                MessageBox.Show("Exception caught in MaskRaster: " + exc.Message);
            }
        }
コード例 #12
0
        /// <summary>
        /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels.
        /// </summary>
        /// <param name="pTlc">Point to start the reading from in the Raster</param>
        /// <param name="pRaster">Reference Raster for the PixelBlock</param>
        /// <param name="pPixelBlock">PixelBlock to be filled in</param>
        public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock)
        {
            try
            {
                // Create a new pixel block to read the input data into.
                // This is done because the pPixelBlock represents the output
                // pixel block which is different from the input. 
                int pBHeight = pPixelBlock.Height;
                int pBWidth = pPixelBlock.Width;
                IPnt pBlockSize = new Pnt();
                pBlockSize.X = pBWidth;
                pBlockSize.Y = pBHeight;
                IPixelBlock inputPixelBlock = new PixelBlock();
                ((IPixelBlock4)inputPixelBlock).Create(myInpNumBands, pBWidth, pBHeight, myInpPixeltype);

                // Call Read method of the Raster Function Helper object to read the input pixels into
                // the inputPixelBlock.
                myFunctionHelper.Read(pTlc, null, pRaster, inputPixelBlock);

                System.Array inpPixelValues1;
                System.Array inpPixelValues2;
                System.Array outPixelValues;
                int index1 = Convert.ToInt16(myBandIndices[0]) - 1; ; // Get NIR band index specified by user.
                int index2 = Convert.ToInt16(myBandIndices[1]) - 1; ; // Get Red Band index specified by user.

                // Get the correct bands from the input.
                IPixelBlock3 ipPixelBlock = (IPixelBlock3)inputPixelBlock;
                inpPixelValues1 = (System.Array)(ipPixelBlock.get_PixelData(index1));
                inpPixelValues2 = (System.Array)(ipPixelBlock.get_PixelData(index2));
                outPixelValues = (System.Array)(((IPixelBlock3)pPixelBlock).get_PixelData(0));
                int i = 0;
                int k = 0;
                double pixelValue = 0.0;
                double nirValue = 0.0;
                double irValue = 0.0;
                // Perform the NDVI computation and store the result in the output pixel block.
                for (i = 0; i < pBHeight; i++)
                {
                    for (k = 0; k < pBWidth; k++)
                    {
                        nirValue = Convert.ToDouble(inpPixelValues1.GetValue(k, i));
                        irValue = Convert.ToDouble(inpPixelValues2.GetValue(k, i));
                        // Check if input is not NoData.
                        if ((Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index1, k, i)) == 1) &&
                            Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index2, k, i)) == 1)
                        {
                            // NDVI[k] = (NIR[k]-Red[k])/(NIR[k]+Red[k]);
                            if ((nirValue + irValue) != 0) // Check for division by 0.
                            {
                                pixelValue = (nirValue - irValue) / (nirValue + irValue);
                                if (pixelValue < -1.0 || pixelValue > 1.0)
                                    pixelValue = 0.0;
                            }
                            else
                                pixelValue = 0.0;
                        }
                        outPixelValues.SetValue((float)(pixelValue), k, i);
                    }
                }
                // Set the output pixel values on the output pixel block.
                ((IPixelBlock3)pPixelBlock).set_PixelData(0, outPixelValues);
                // Copy over the NoData mask from the input and set it on the output.
                ((IPixelBlock3)pPixelBlock).set_NoDataMask(0, ((IPixelBlock3)inputPixelBlock).get_NoDataMask(0));
            }
            catch (Exception exc)
            {
                System.Exception myExc = new System.Exception(
                    "Exception caught in Read method: " + exc.Message, exc);
                throw myExc;
            }
        }
コード例 #13
0
        /// <summary>
        /// Finds filpped block according to given center.
        /// </summary>
        /// <param name="block"></param>
        /// <param name="center"></param>
        /// <returns></returns>
        public static Point FindFlippedBlock(this PixelBlock block, PixelBlock center)
        {
            var vector = new Vector(center.Position, block.Position);

            return(new Point(block.Position.X + vector.X, block.Position.Y + vector.Y));
        }
コード例 #14
0
        /// <summary>
        /// Finds two minimums in a array of pixel blocks and calculates difference between them expressed as percent.
        /// </summary>
        /// <param name="picxelBlocks"></param>
        /// <param name="referentBlock"></param>
        /// <returns></returns>
        public static MinimumPair GetMinimums(this IEnumerable <PixelBlock> picxelBlocks, PixelBlock referentBlock)
        {
            var result = picxelBlocks.Select(d => new { Block = d, Mbd = d.BlockDistortion(referentBlock) }).OrderBy(d => d.Mbd).Take(2).ToList();

            return(result.Count == 1 ?
                   new MinimumPair(result[0].Block, new PixelBlock(), double.MaxValue)
                : new MinimumPair(result[0].Block, result[1].Block, (result[1].Mbd - result[0].Mbd) / result[1].Mbd));
        }
コード例 #15
0
        public async void RasterDatasetSnippets()
        {
            try
            {
                #region Open raster dataset in a folder.
                // Create a FileSystemConnectionPath using the folder path.
                FileSystemConnectionPath connectionPath = new FileSystemConnectionPath(new System.Uri(@"C:\Temp"), FileSystemDatastoreType.Raster);
                // Create a new FileSystemDatastore using the FileSystemConnectionPath.
                FileSystemDatastore dataStore = new FileSystemDatastore(connectionPath);
                // Open the raster dataset.
                RasterDataset fileRasterDataset = dataStore.OpenDataset <RasterDataset>("Sample.tif");
                #endregion

                #region Open raster dataset in a geodatabase.
                // Create a FileGeodatabaseConnectionPath using the path to the gdb. Note: This can be a path to a .sde file.
                FileGeodatabaseConnectionPath geodatabaseConnectionPath = new FileGeodatabaseConnectionPath(new Uri(@"C:\Temp\rasters.gdb"));
                // Create a new Geodatabase object using the FileGeodatabaseConnectionPath.
                Geodatabase geodatabase = new Geodatabase(geodatabaseConnectionPath);
                // Open the raster dataset.
                RasterDataset gdbRasterDataset = geodatabase.OpenDataset <RasterDataset>("sample");
                #endregion

                RasterDataset rasterDataset = fileRasterDataset;
                #region Get the raster dataset definition from a raster dataset.
                await QueuedTask.Run(() =>
                {
                    RasterDatasetDefinition rasterDatasetDefinition = rasterDataset.GetDefinition();
                    rasterDatasetDefinition.GetBandCount();
                });

                #endregion

                {
                    #region Access rows in a raster attribute table.
                    var raster = MapView.Active.Map.GetLayersAsFlattenedList().OfType <RasterLayer>().FirstOrDefault();
                    if (raster != null)
                    {
                        await QueuedTask.Run(() =>
                        {
                            var rasterTbl = raster.GetRaster().GetAttributeTable();
                            var cursor    = rasterTbl.Search();
                            while (cursor.MoveNext())
                            {
                                var row = cursor.Current;
                            }
                        });
                    }
                    #endregion
                }

                {
                    #region Create a raster cursor to iterate through the raster data.
                    await QueuedTask.Run(() =>
                    {
                        // Create a full raster from the raster dataset.
                        ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                        // Calculate size of pixel blocks to process. Use 1000 or height/width of the raster, whichever is smaller.
                        int pixelBlockHeight = raster.GetHeight() > 1000 ? 1000 : raster.GetHeight();
                        int pixelBlockWidth  = raster.GetWidth() > 1000 ? 1000 : raster.GetWidth();

                        // Create the raster cursor using the height and width calculated.
                        RasterCursor rasterCursor = raster.CreateCursor(pixelBlockWidth, pixelBlockHeight);

                        // Use a do-while loop to iterate through the pixel blocks of the raster using the raster cursor.
                        do
                        {
                            // Get the current pixel block from the cursor.
                            using (PixelBlock currentPixelBlock = rasterCursor.Current)
                            {
                                // Do something with the pixel block...
                            }

                            // Once you are done, move to the next pixel block.
                        }         while (rasterCursor.MoveNext());
                    });

                    #endregion
                }

                {
                    #region Read and Write pixels from and to a raster dataset using pixel blocks.
                    await QueuedTask.Run(() =>
                    {
                        // Create a full raster from the raster dataset.
                        ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                        // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller.
                        int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight();
                        int pixelBlockWidth  = raster.GetWidth() > 128 ? 128 : raster.GetWidth();

                        // Create a new (blank) pixel block.
                        PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

                        // Read pixel values from the raster dataset into the pixel block starting from the given top left corner.
                        raster.Read(0, 0, currentPixelBlock);

                        // Do something with the pixel block...

                        // Write the pixel block to the raster dataset starting from the given top left corner.
                        raster.Write(0, 0, currentPixelBlock);
                    });

                    #endregion
                }

                {
                    // Create a full raster from the raster dataset.
                    ArcGIS.Core.Data.Raster.Raster raster = rasterDataset.CreateFullRaster();

                    // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller.
                    int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight();
                    int pixelBlockWidth  = raster.GetWidth() > 128 ? 128 : raster.GetWidth();

                    // Create a new (blank) pixel block.
                    PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

                    #region Process pixels using a pixel block
                    await QueuedTask.Run(() =>
                    {
                        // Read pixel values from the raster dataset into the pixel block starting from the given top left corner.
                        raster.Read(0, 0, currentPixelBlock);

                        // For each plane (band) in the pixel block
                        for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++)
                        {
                            // Get a copy of the array of pixels from the pixel block corresponding to the current plane.
                            Array sourcePixels = currentPixelBlock.GetPixelData(plane, true);
                            // Get the height and width of the pixel block.
                            int pBHeight = currentPixelBlock.GetHeight();
                            int pBWidth  = currentPixelBlock.GetWidth();

                            // Iterate through the pixels in the array.
                            for (int i = 0; i < pBHeight; i++)
                            {
                                for (int j = 0; j < pBWidth; j++)
                                {
                                    // Get the NoData mask value to see if the pixel is a valid pixel.
                                    if (Convert.ToByte(currentPixelBlock.GetNoDataMaskValue(plane, j, i)) == 1)
                                    {
                                        // Get the pixel value from the array and process it (add 5 to the value).
                                        // Note: This is assuming the pixel type is Unisigned 8bit.
                                        int pixelValue = Convert.ToInt16(sourcePixels.GetValue(j, i)) + 5;
                                        // Make sure the pixel value does not go above the range of the pixel type.
                                        pixelValue = pixelValue > 254 ? 254 : pixelValue;
                                        // Set the new pixel value to the array.
                                        // Note: This is assuming the pixel type is Unisigned 8bit.
                                        sourcePixels.SetValue(Convert.ToByte(pixelValue), j, i);
                                    }
                                }
                            }
                            // Set the modified array of pixels back to the pixel block.
                            currentPixelBlock.SetPixelData(plane, sourcePixels);
                        }
                        // Write the pixel block to the raster dataset starting from the given top left corner.
                        raster.Write(0, 0, currentPixelBlock);
                    });

                    #endregion
                    #region Calculate Raster statistics
                    //If a raster dataset has statistics, you can create a raster layer and get these statistics by accessing the colorizer.
                    await QueuedTask.Run(() =>
                    {
                        //Accessing the raster layer
                        var lyr = MapView.Active.Map.GetLayersAsFlattenedList().OfType <BasicRasterLayer>().FirstOrDefault();
                        //Getting the colorizer
                        var colorizer = lyr.GetColorizer() as CIMRasterStretchColorizer;
                        //Accessing the statistics
                        var stats = colorizer.StretchStats;
                        var max   = stats.max;
                        var min   = stats.min;
                    });

                    #endregion
                }
            }
            catch (Exception)
            {
            }
        }
コード例 #16
0
 public Bresenham(PixelBlock target, UInt32 color) : base(target, color)
 {
 }
コード例 #17
0
        private Raster WritePixelValues(Raster raster)
        {
            // Calculate size of pixel block to create. Use 128 or height/width of the raster, whichever is smaller.
            int pixelBlockHeight = raster.GetHeight() > 128 ? 128 : raster.GetHeight();
            int pixelBlockWidth  = raster.GetWidth() > 128 ? 128 : raster.GetWidth();

            // Create a new (blank) pixel block.
            PixelBlock currentPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

            // Read pixel values from the raster dataset into the pixel block starting from the given top left corner.
            raster.Read(0, 0, currentPixelBlock);

            // For each plane (band) in the pixel block
            for (int plane = 0; plane < currentPixelBlock.GetPlaneCount(); plane++)
            {
                // Get a copy of the array of pixels from the pixel block corresponding to the current plane.
                Array sourcePixels = currentPixelBlock.GetPixelData(plane, true);

                // Get the height and width of the pixel block.
                int pBHeight = currentPixelBlock.GetHeight();
                int pBWidth  = currentPixelBlock.GetWidth();

                // Iterate through the pixels in the array.
                for (int i = 0; i < pBHeight; i++)
                {
                    for (int j = 0; j < pBWidth; j++)
                    {
                        // Get the pixel value from the array and process it
                        //  (add 5 to the value and add the value x2).
                        // Note: This is assuming the pixel type is Unisigned 8bit.
                        int pixelValue = Convert.ToInt16(sourcePixels.GetValue(j, i)) + 5 + i * 2;

                        // Make sure the pixel value does not go above the range of the pixel type.
                        pixelValue = pixelValue > 254 ? 254 : pixelValue;

                        // Set the new pixel value to the array.
                        // Note: This is assuming the pixel type is Unisigned 8bit.
                        sourcePixels.SetValue(Convert.ToByte(pixelValue), j, i);
                    }
                }

                // Set the modified array of pixels back to the pixel block.
                currentPixelBlock.SetPixelData(plane, sourcePixels);

                // Check pixel blocks.
                Array testPixels_cp = currentPixelBlock.GetPixelData(0, true);
                Array testPixels_rf = currentPixelBlock.GetPixelData(0, false);
            }

            // Write the pixel block to the raster dataset starting from the given top left corner.
            raster.Write(0, 0, currentPixelBlock);

            // Check raster.
            int        pixelValueTest  = Convert.ToInt16(raster.GetPixelValue(0, 0, 1));
            PixelBlock checkPixelBlock = raster.CreatePixelBlock(pixelBlockWidth, pixelBlockHeight);

            raster.Read(0, 0, checkPixelBlock);
            Array testSourcePixels_cp = checkPixelBlock.GetPixelData(0, true);
            Array testSourcePixels_rf = checkPixelBlock.GetPixelData(0, false);

            return(raster);
        }
コード例 #18
0
        /// <summary>
        /// Medical Diamond Search Algorithm
        /// </summary>
        /// <param name="referentBlock"></param>
        /// <param name="centerBlock"></param>
        /// <param name="image"></param>
        /// <returns></returns>
        private static Vector CalculateVector(PixelBlock referentBlock, PixelBlock centerBlock, Image image)
        {
            var diamond = new LargeDiamond(referentBlock, centerBlock, image);
            var mins    = diamond.GetMinimums();

            //If first and second minimum are same as referent block return first of them.
            if (double.IsNaN(mins.Treshold))
            {
                return(new Vector(referentBlock.Position, mins.Minimum.Position));
            }

            if (mins.Treshold > _treshold)
            {
                if (diamond.IsCenterBlock(mins.Minimum))
                {
                    return(new Vector(referentBlock.Position, new SmallDiamond(referentBlock, diamond.CenterBlock, image).GetMinimums().Minimum.Position));
                }
                var flippedPoint = mins.Minimum.FindFlippedBlock(centerBlock);
                if (referentBlock.IsInSearchWindow(flippedPoint, MedicalDiamondSearchSettings.SearchParameterP,
                                                   MedicalDiamondSearchSettings.BlockSize, image.Width, image.Height))
                {
                    var flippedBlock = image.Blocks[flippedPoint];
                    return(flippedBlock.BlockDistortion(referentBlock) < mins.Minimum.BlockDistortion(referentBlock)
                        ? new Vector(referentBlock.Position, flippedPoint)
                        : new Vector(referentBlock.Position, mins.Minimum.Position));
                }
            }

            #region Get flipped position of minimums
            var dict = new Dictionary <PixelBlock, Vector>();
            var list = new List <PixelBlock>
            {
                mins.Minimum, mins.SecondMinimum
            };

            var firstAddValue =
                mins.Minimum.FindFlippedAndAddToVectorDictionary(centerBlock, referentBlock, image, dict);
            if (firstAddValue.HasValue)
            {
                list.Add(firstAddValue.Value);
            }

            var secondAddValue = mins.SecondMinimum.FindFlippedAndAddToVectorDictionary(centerBlock, referentBlock, image, dict);
            if (secondAddValue.HasValue)
            {
                list.Add(secondAddValue.Value);
            }
            #endregion


            for (int i = 0; i < 3; i++)
            {
                mins = list.GetMinimums(referentBlock);
                if (mins.Treshold > _treshold)
                {
                    return(new Vector(referentBlock.Position, mins.Minimum.Position));
                }
                list = new List <PixelBlock>
                {
                    mins.Minimum, mins.SecondMinimum
                };
                firstAddValue =
                    mins.Minimum.FindFlippedAndAddToVectorDictionary(referentBlock, image, dict);
                if (firstAddValue.HasValue)
                {
                    list.Add(firstAddValue.Value);
                }

                secondAddValue = mins.SecondMinimum.FindFlippedAndAddToVectorDictionary(referentBlock, image, dict);
                if (secondAddValue.HasValue)
                {
                    list.Add(secondAddValue.Value);
                }
            }
            _treshold += 0.05;
            return(new Vector(referentBlock.Position, mins.Minimum.Position));
        }
        /// <summary>
        /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels.
        /// </summary>
        /// <param name="pTlc">Point to start the reading from in the Raster</param>
        /// <param name="pRaster">Reference Raster for the PixelBlock</param>
        /// <param name="pPixelBlock">PixelBlock to be filled in</param>
        public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock)
        {
            try
            {
                // Create a new pixel block to read the input data into.
                // This is done because the pPixelBlock represents the output
                // pixel block which is different from the input.
                int  pBHeight   = pPixelBlock.Height;
                int  pBWidth    = pPixelBlock.Width;
                IPnt pBlockSize = new Pnt();
                pBlockSize.X = pBWidth;
                pBlockSize.Y = pBHeight;
                IPixelBlock inputPixelBlock = new PixelBlock();
                ((IPixelBlock4)inputPixelBlock).Create(myInpNumBands, pBWidth, pBHeight, myInpPixeltype);

                // Call Read method of the Raster Function Helper object to read the input pixels into
                // the inputPixelBlock.
                myFunctionHelper.Read(pTlc, null, pRaster, inputPixelBlock);

                System.Array inpPixelValues1;
                System.Array inpPixelValues2;
                System.Array outPixelValues;
                int          index1 = Convert.ToInt16(myBandIndices[0]) - 1;; // Get NIR band index specified by user.
                int          index2 = Convert.ToInt16(myBandIndices[1]) - 1;; // Get Red Band index specified by user.

                // Get the correct bands from the input.
                IPixelBlock3 ipPixelBlock = (IPixelBlock3)inputPixelBlock;
                inpPixelValues1 = (System.Array)(ipPixelBlock.get_PixelData(index1));
                inpPixelValues2 = (System.Array)(ipPixelBlock.get_PixelData(index2));
                outPixelValues  = (System.Array)(((IPixelBlock3)pPixelBlock).get_PixelData(0));
                int    i          = 0;
                int    k          = 0;
                double pixelValue = 0.0;
                double nirValue   = 0.0;
                double irValue    = 0.0;
                // Perform the NDVI computation and store the result in the output pixel block.
                for (i = 0; i < pBHeight; i++)
                {
                    for (k = 0; k < pBWidth; k++)
                    {
                        nirValue = Convert.ToDouble(inpPixelValues1.GetValue(k, i));
                        irValue  = Convert.ToDouble(inpPixelValues2.GetValue(k, i));
                        // Check if input is not NoData.
                        if ((Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index1, k, i)) == 1) &&
                            Convert.ToByte(ipPixelBlock.GetNoDataMaskVal(index2, k, i)) == 1)
                        {
                            // NDVI[k] = (NIR[k]-Red[k])/(NIR[k]+Red[k]);
                            if ((nirValue + irValue) != 0) // Check for division by 0.
                            {
                                pixelValue = (nirValue - irValue) / (nirValue + irValue);
                                if (pixelValue < -1.0 || pixelValue > 1.0)
                                {
                                    pixelValue = 0.0;
                                }
                            }
                            else
                            {
                                pixelValue = 0.0;
                            }
                        }
                        outPixelValues.SetValue((float)(pixelValue), k, i);
                    }
                }
                // Set the output pixel values on the output pixel block.
                ((IPixelBlock3)pPixelBlock).set_PixelData(0, outPixelValues);
                // Copy over the NoData mask from the input and set it on the output.
                ((IPixelBlock3)pPixelBlock).set_NoDataMask(0, ((IPixelBlock3)inputPixelBlock).get_NoDataMask(0));
            }
            catch (Exception exc)
            {
                System.Exception myExc = new System.Exception(
                    "Exception caught in Read method: " + exc.Message, exc);
                throw myExc;
            }
        }