public static void exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat)   //输出栅格数据
        {
            string            directory        = parth.Substring(0, parth.LastIndexOf("\\"));
            string            name             = parth.Substring(parth.LastIndexOf("\\") + 1);
            IWorkspaceFactory workspaceFac     = new RasterWorkspaceFactoryClass();
            IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2;

            IRasterInfo rasterInfo  = (rasterLayer.Raster as IRawBlocks).RasterInfo;
            IPoint      originPoint = new Point();

            originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y);
            IRasterProps   rasterProps   = rasterLayer.Raster as IRasterProps;
            IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height,
                                                                                rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true) as IRasterDataset2;

            IRaster2 raster2 = rasterDataSet.CreateDefaultRaster() as IRaster2;

            IPnt pntClass = new Pnt();

            pntClass.X = rasterProps.Width;
            pntClass.Y = rasterProps.Height;
            IRasterCursor rasterCursor   = raster2.CreateCursorEx(pntClass);
            IRasterCursor inRasterCursor = (rasterLayer.Raster as IRaster2).CreateCursorEx(pntClass);

            IRasterEdit rasterEdit = raster2 as IRasterEdit;

            if (rasterEdit.CanEdit())
            {
                IPixelBlock3 pixelBlock3   = rasterCursor.PixelBlock as IPixelBlock3;
                IPixelBlock3 inPixelBlock3 = inRasterCursor.PixelBlock as IPixelBlock3;
                System.Array pixels        = (System.Array)rasterMat;
                pixelBlock3.set_PixelData(0, (System.Array)pixels);
                rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3);
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pixelBlock3);
            }
            rasterEdit.Refresh();
            IGeoDataset   inDataset   = rasterLayer.Raster as IGeoDataset;
            IGeoDataset   outDataset  = rasterDataSet as IGeoDataset;
            IExtractionOp op          = new RasterExtractionOpClass();
            var           outDataset1 = op.Raster(outDataset, inDataset);
            var           clipRaster  = (IRaster)outDataset1;
            ISaveAs       pSaveAs     = clipRaster as ISaveAs;

            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterCursor);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(raster2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterDataSet);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterWorkspace2);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(workspaceFac);
            if (File.Exists(parth))
            {
                File.Delete(parth);
            }
            workspaceFac = new RasterWorkspaceFactoryClass();
            IDataset outdataset = pSaveAs.SaveAs(name, workspaceFac.OpenFromFile(directory, 0), "IMAGINE Image");

            System.Runtime.InteropServices.Marshal.ReleaseComObject(outdataset);
            return;
        }
Example #2
0
        private bool writeBlockDataToFile(Point2D ptLeftTop, byte[,] dbData, int[] nSize, IRaster pRaster /*, IRasterEdit rasterEdit*/)
        {
            if (pRaster == null)
            {
                return(false);
            }

            try
            {
                //Create a pixel block using the weight and height of the raster dataset.
                //If the raster dataset is large, a smaller pixel block should be used.
                //Refer to the topic "How to access pixel data using a raster cursor".
                int nWidth  = nSize[0];
                int nHeight = nSize[1];

                IPnt blocksize = new PntClass();
                blocksize.SetCoords(nWidth, nHeight);
                IPixelBlock3 pixelblock = pRaster.CreatePixelBlock(blocksize) as IPixelBlock3;

                //Populate some pixel values to the pixel block.
                System.Array pixels;
                pixels = (System.Array)pixelblock.get_PixelData(0);
                for (int i = 0; i < nWidth; i++)
                {
                    for (int j = 0; j < nHeight; j++)
                    {
                        pixels.SetValue(dbData[i, j], i, j);
                    }
                }

                pixelblock.set_PixelData(0, (System.Array)pixels);

                //Define the location that the upper left corner of the pixel block is to write.
                IPnt upperLeft = new PntClass();
                upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y);

                //Write the pixel block.
                IRasterEdit rasterEdit = (IRasterEdit)pRaster;
                rasterEdit.Write(upperLeft, (IPixelBlock)pixelblock);
                //System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
                rasterEdit.Refresh();

                return(true);
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine("Error: " + ex.Message);
                return(false);
            }

            GC.Collect();
            return(true);
        }
        public static IRasterDataset exportRasterData(string parth, IRasterLayer rasterLayer, float[,] rasterMat)
        {
            string directory = parth.Substring(0, parth.LastIndexOf("\\"));
            string name      = parth.Substring(parth.LastIndexOf("\\") + 1);

            IWorkspaceFactory workspaceFac     = new RasterWorkspaceFactoryClass();
            IRasterWorkspace2 rasterWorkspace2 = workspaceFac.OpenFromFile(directory, 0) as IRasterWorkspace2;

            IRasterInfo rasterInfo  = (rasterLayer.Raster as IRawBlocks).RasterInfo;
            IPoint      originPoint = new Point();

            originPoint.PutCoords(rasterInfo.Origin.X, rasterInfo.Origin.Y - (rasterLayer.Raster as IRasterProps).Height * (rasterLayer.Raster as IRasterProps).MeanCellSize().Y);
            IRasterProps   rasterProps   = rasterLayer.Raster as IRasterProps;
            IRasterDataset rasterDataSet = rasterWorkspace2.CreateRasterDataset(name, "IMAGINE Image", originPoint, rasterProps.Width, rasterProps.Height, rasterProps.MeanCellSize().X, rasterProps.MeanCellSize().Y, 1, rstPixelType.PT_FLOAT, rasterProps.SpatialReference, true);
            IRaster2       raster2       = rasterDataSet.CreateDefaultRaster() as IRaster2;
            IPnt           pntClass      = new Pnt();

            pntClass.X = rasterProps.Width;
            pntClass.Y = rasterProps.Height;

            IRasterCursor rasterCursor = raster2.CreateCursorEx(pntClass);
            IRasterEdit   rasterEdit   = raster2 as IRasterEdit;

            if (rasterEdit.CanEdit())
            {
                IRasterBandCollection bands       = rasterDataSet as IRasterBandCollection;
                IPixelBlock3          pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;
                System.Array          pixels      = (System.Array)pixelBlock3.get_PixelData(0);
                for (int i = 0; i < rasterProps.Width; i++)
                {
                    for (int j = 0; j < rasterProps.Height; j++)
                    {
                        pixels.SetValue(Convert.ToSingle(rasterMat[j, i]), i, j);
                    }
                }
                pixelBlock3.set_PixelData(0, (System.Array)pixels);
                rasterEdit.Write(rasterCursor.TopLeft, (IPixelBlock)pixelBlock3);
            }
            (raster2 as IRasterProps).NoDataValue = 0f;
            rasterEdit.Refresh();
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);
            return(rasterDataSet);
        }
Example #4
0
        public IRasterDataset TinToRaster_new(ITinAdvanced pTin, esriRasterizationType eRastConvType, String sDir, String sName, rstPixelType ePixelType, Double cellsize, IEnvelope pExtent, bool bPerm)
        {
            IPoint pOrigin = pExtent.LowerLeft;

            //pOrigin.X = pOrigin.X - (cellsize * 0.5);
            //pOrigin.Y = pOrigin.Y - (cellsize * 0.5);
            pOrigin.X = pOrigin.X;
            pOrigin.Y = pOrigin.Y;
            int nCol, nRow;

            nCol = (int)Math.Round(pExtent.Width / cellsize);
            nRow = (int)Math.Round(pExtent.Height / cellsize);
            IGeoDataset        pGDS = pTin as IGeoDataset;
            ISpatialReference2 pSR  = pGDS.SpatialReference as ISpatialReference2;
            //这个pOrigin为栅格左下角
            IWorkspaceFactory pworkspaceFactory = new RasterWorkspaceFactory();
            IRasterWorkspace2 rasterws          = pworkspaceFactory.OpenFromFile(sDir, 0) as IRasterWorkspace2;
            IPoint            originpoint       = pOrigin;

            //用于计算的 float型的栅格数据
            IRasterDataset demdataset = rasterws.CreateRasterDataset(sName, "TIFF", originpoint, nCol, nRow,
                                                                     cellsize, cellsize, 1, rstPixelType.PT_DOUBLE, null, true);

            IRasterDataset pRDS = demdataset;

            //IRawPixels pRawPixels = GetRawPixels(pRDS, 0);
            IRaster pRaster    = pRDS.CreateDefaultRaster();
            IPnt    pBlockSize = new DblPnt();

            //nCol = 50;
            //nRow = 50;
            pBlockSize.X = nCol;
            pBlockSize.Y = nRow;
            IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize);
            //IPixelBlock pPixelBlock = pRawPixels.CreatePixelBlock(pBlockSize);
            IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3;

            //object val = pPixelBlock.get_SafeArray(0);
            ITinSurface pTinSurf = pTin as ITinSurface;
            // IRasterProps pRasterProps = pRawPixels as IRasterProps;
            IRasterProps pRasterProps = pRaster as IRasterProps;
            object       nodata;

            //pOrigin.X = pOrigin.X + (cellsize * 0.5);
            //pOrigin.Y = pOrigin.Y + (cellsize * nRow) - (cellsize * 0.5);
            pOrigin.X = pOrigin.X;
            pOrigin.Y = pOrigin.Y + (cellsize * nRow);
            nodata    = pRasterProps.NoDataValue;
            IGeoDatabaseBridge2 pbridge2 = (IGeoDatabaseBridge2) new GeoDatabaseHelperClass();

            //这个pOrigin为栅格左上角
            //pbridge2.QueryPixelBlock(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, esriRasterizationType.esriElevationAsRaster, nodata, ref val);
            //if (pTin.ProcessCancelled)
            //    return null;
            //val.GetType();
            CalPixelArray(pTinSurf, pOrigin.X, pOrigin.Y, cellsize, cellsize, ref pPixelBlock3);
            IPnt pOffset = new DblPnt();

            pOffset.X = 0;
            pOffset.Y = 0;
            //pPixelBlock3.set_PixelData(0, val);
            //pRawPixels.Write(pOffset, (IPixelBlock)pPixelBlock3);//写入硬盘
            IRasterEdit prasteredit = pRaster as IRasterEdit;

            prasteredit.Write(pOffset, (IPixelBlock)pPixelBlock3);
            //pRDS = OpenOutputRasterDataset(sDir, sName);

            //IPixelBlock pb = pRaster.CreatePixelBlock(pBlockSize);
            //pRaster.Read(pOffset,pb);

            // ISaveAs pSaveas = pRasterProps as ISaveAs2;
            // pSaveas.SaveAs(sDir + "\\" + sName, null, "TIFF");

            prasteredit.Refresh();


            return(pRDS);
        }
        public void UnderInit()
        {
            //接口转换
            IRaster2 raster2 = m_raster as IRaster2;
            //获取栅格的属性
            IRasterProps pRasterProps = raster2 as IRasterProps;
            //获取栅格的高度和宽度
            int Height = pRasterProps.Height;
            int Width  = pRasterProps.Width;
            //获取像元的大小
            double cellsizex = pRasterProps.MeanCellSize().X;
            double cellsizey = pRasterProps.MeanCellSize().Y;
            //创建工作空间,存储NDVI计算结果
            IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass();
            IWorkspace        pWs          = pRasterWsFac.OpenFromFile(@"F:/RDB", 0);
            IRasterWorkspace2 pRasterWs;

            pRasterWs = pWs as IRasterWorkspace2;
            //设置原点与原栅格相同
            IPoint origin = new PointClass();

            origin.PutCoords(pRasterProps.Extent.XMin, pRasterProps.Extent.YMin);
            //定义空间参考系为未知参考系
            ISpatialReference sr = new UnknownCoordinateSystemClass();
            //创建栅格
            IRasterDataset2 resultDataset = pRasterWs.CreateRasterDataset("NDVI.tif", "TIFF", origin, Width, Height, cellsizex, cellsizey, 1, rstPixelType.PT_DOUBLE, sr) as IRasterDataset2;
            //对创建的栅格创建栅格指针
            IRaster       resultRaster       = resultDataset.CreateFullRaster();
            IRasterCursor resultRasterCursor = ((IRaster2)resultRaster).CreateCursorEx(null);
            //对原始栅格创建栅格指针
            IRasterCursor rasterCursor = raster2.CreateCursorEx(null);
            //创建两个像素块,用以同时遍历两个栅格
            IPixelBlock3 resultPixelBlock = null;
            IPixelBlock3 tempPixelBlock   = null;
            //创建IRasterEidt以便对结果栅格进行修改,填入计算结果
            IRasterEdit resultRasterEdit = resultRaster as IRasterEdit;
            //初始化像素块宽度与高度
            long blockWidth  = 0;
            long blockHeight = 0;

            do
            {
                //对两个像素块进行更新
                resultPixelBlock = resultRasterCursor.PixelBlock as IPixelBlock3;
                tempPixelBlock   = rasterCursor.PixelBlock as IPixelBlock3;
                //获取原始栅格中近红外波段以及红波段的数据
                System.Array pixels3 = (System.Array)tempPixelBlock.get_PixelData(VisibleBandID);
                System.Array pixels4 = (System.Array)tempPixelBlock.get_PixelData(InfraredBandID);
                //获取结果栅格像素块的高度和宽度,并以此进行遍历
                blockHeight = resultPixelBlock.Height;
                blockWidth  = resultPixelBlock.Width;
                //获取结果栅格像素块中第一波段的值
                System.Array resultPixels = (System.Array)resultPixelBlock.get_PixelData(0);
                //根据NDVI公式,将计算结果写入到结果栅格像素块中
                for (int i = 0; i < blockHeight; i++)
                {
                    for (int j = 0; j < blockWidth; j++)
                    {
                        double up   = double.Parse(pixels4.GetValue(j, i).ToString()) - double.Parse(pixels3.GetValue(j, i).ToString());
                        double down = double.Parse(pixels4.GetValue(j, i).ToString()) + double.Parse(pixels3.GetValue(j, i).ToString());
                        if (down != 0)
                        {
                            resultPixels.SetValue((up / down), j, i);
                        }
                        else
                        {
                            resultPixels.SetValue((0.0), j, i);
                        }
                    }
                }
                //将结算结果设置到结果栅格图像对应的像素块中,根据其位置进行更新后刷新
                resultPixelBlock.set_PixelData(0, (System.Array)resultPixels);
                resultRasterEdit.Write(resultRasterCursor.TopLeft, (IPixelBlock)resultPixelBlock);
                resultRasterEdit.Refresh();
            } while (resultRasterCursor.Next() == true && rasterCursor.Next() == true);//遍历完一块像素块之后遍历下一块,直到栅格遍历结束。
            //将结果栅格存入到成员变量m_raster中
            m_raster = resultRaster;

            //我在这里无法删除这个文件怎么办!!!!!!!!!
            //System.IO.File.Delete("F:/RDB/NDVI.tif");
        }
Example #6
0
        public void ChangeRasterValue(IRasterDataset2 pRasterDatset, double dbScale, double dbOffset)
        {
            try
            {
                IRaster2 pRaster2 = pRasterDatset.CreateFullRaster() as IRaster2;

                IPnt pPntBlock = new PntClass();

                pPntBlock.X = 128;
                pPntBlock.Y = 128;

                IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(pPntBlock);
                IRasterEdit   pRasterEdit   = pRaster2 as IRasterEdit;

                if (pRasterEdit.CanEdit())
                {
                    IRasterBandCollection pBands       = pRasterDatset as IRasterBandCollection;
                    IPixelBlock3          pPixelblock3 = null;
                    int          pBlockwidth           = 0;
                    int          pBlockheight          = 0;
                    System.Array pixels;
                    IPnt         pPnt = null;
                    object       pValue;
                    long         pBandCount = pBands.Count;

                    //获取Nodata
                    IRasterProps pRasterPro = pRaster2 as IRasterProps;
                    object       pNodata    = pRasterPro.NoDataValue;
                    //double dbNoData = Convert.ToDouble(((double[])pNodata)[0]);
                    double dbNoData = getNoDataValue(pNodata);

                    do
                    {
                        pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3;
                        pBlockwidth  = pPixelblock3.Width;
                        pBlockheight = pPixelblock3.Height;

                        for (int k = 0; k < pBandCount; k++)
                        {
                            pixels = (System.Array)pPixelblock3.get_PixelData(k);
                            for (int i = 0; i < pBlockwidth; i++)
                            {
                                for (int j = 0; j < pBlockheight; j++)
                                {
                                    pValue = pixels.GetValue(i, j);
                                    double ob = Convert.ToDouble(pValue);
                                    if (ob != dbNoData)
                                    {
                                        ob *= dbScale;  //翻转
                                        ob += dbOffset; //Z方向偏移
                                    }

                                    IRasterProps pRP = pRaster2 as IRasterProps;
                                    if (pRP.PixelType == rstPixelType.PT_CHAR)
                                    {
                                        pixels.SetValue(Convert.ToChar(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_UCHAR)
                                    {
                                        pixels.SetValue(Convert.ToByte(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_FLOAT)
                                    {
                                        pixels.SetValue(Convert.ToSingle(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_DOUBLE)
                                    {
                                        pixels.SetValue(Convert.ToDouble(ob), i, j);
                                    }
                                    else if (pRP.PixelType == rstPixelType.PT_ULONG)
                                    {
                                        pixels.SetValue(Convert.ToInt32(ob), i, j);
                                    }
                                    else
                                    {
                                        ;
                                    }
                                }
                            }
                            pPixelblock3.set_PixelData(k, pixels);

                            System.Array textPixel = null;
                            textPixel = (System.Array)pPixelblock3.get_PixelData(k);
                        }

                        pPnt = pRasterCursor.TopLeft;
                        pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3);
                    }while (pRasterCursor.Next());

                    //改变了Z值,重新统计下直方图
                    //IRasterDataset2 prd = pRaster2 as IRasterDataset2;
                    IRasterDatasetEdit3 pRedtit = pRasterDatset as IRasterDatasetEdit3;
                    pRedtit.DeleteStats();//This method is avaliable only on raster datasets in File and ArcSDE geodatabases.
                    pRedtit.ComputeStatisticsHistogram(1, 1, null, true);

                    pRasterEdit.Refresh();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit);
                }
            }
            catch (System.Exception ex)
            {
            }
        }
Example #7
0
        //采用另一种方法实现互换XY,不会改变影像的分辨率
        public bool NorthEastToEastNorth(IRasterLayer pRasterLayer, string szFilename)//坐标系x,y变换
        {
            if (pRasterLayer == null || szFilename == null)
            {
                return(false);
            }

            try
            {
                ITransformationOp          dstTrans = new RasterTransformationOpClass();
                IRasterAnalysisEnvironment pDstAnalysisEnvironment = dstTrans as IRasterAnalysisEnvironment;
                if (pDstAnalysisEnvironment == null)
                {
                    return(false);
                }

                //设置分辨率
                IRaster2     pRaster2       = pRasterLayer.Raster as IRaster2;
                IRasterProps pProps         = pRaster2 as IRasterProps;
                double       dbCellSizeX    = pProps.MeanCellSize().X;
                double       dbCellSizeY    = pProps.MeanCellSize().Y;
                double       dbCellSizeMean = (dbCellSizeX + dbCellSizeY) / 2;
                //pDstAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSizeMean);

                //定义原始数据集和目标数据集
                IGeoDataset pSrcGeoDataset = pRasterLayer.Raster as IGeoDataset;
                IGeoDataset pDstGeoDataset = null;
                IGeoDataset pTmpGeoDataset = null;

                //顺时针旋转90度
                IPoint pt = new PointClass();
                pt.X           = 0;
                pt.Y           = 0;
                pTmpGeoDataset = dstTrans.Rotate(pSrcGeoDataset, esriGeoAnalysisResampleEnum.esriGeoAnalysisResampleCubic, 90, pt);
                //pDstGeoDataset = pTmpGeoDataset;

                //水平旋转
                pSrcGeoDataset = dstTrans.Flip(pTmpGeoDataset);

                //由于翻转是以图像中心为界,所以要加上偏移量
                IEnvelope pExtent   = pSrcGeoDataset.Extent;
                double    dbCenterY = (pExtent.UpperLeft.Y + pExtent.LowerRight.Y) / 2;
                double    dbDeltaX  = 0;
                double    dbDeltaY  = -dbCenterY * 2;
                //pDstGeoDataset = dstTrans.Flip(pTmpGeoDataset);
                pDstGeoDataset = dstTrans.Shift(pSrcGeoDataset, dbDeltaX, dbDeltaY, null);
                if (pDstGeoDataset == null)
                {
                    return(false);
                }

                IRasterLayer pLayer = new RasterLayerClass();
                pLayer.CreateFromDataset(pDstGeoDataset as IRasterDataset);


                IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace        inmemWor         = workspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szFilename), 0);
                ISaveAs2          sa = pDstGeoDataset as ISaveAs2;
                //IRaster2 pR2 = ((IRasterDataset3)pDstGeoDataset).CreateDefaultRaster() as IRaster2;
                IRaster2    pR2 = pLayer.Raster as IRaster2;
                IRasterEdit pRe = pR2 as IRasterEdit;

                //pRe.Refresh();
                // sa = ((IRasterDataset3)pDstGeoDataset).CreateDefaultRaster() as ISaveAs2;
                sa = pRe as ISaveAs2;
                if (sa != null)
                {
                    sa.SaveAs(System.IO.Path.GetFileName(szFilename), inmemWor, "TIFF");
                    //sa.SaveAsRasterDataset()
                    pRe.Refresh();
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pRe);
                    (pDstGeoDataset as IRasterDataset3).Refresh();
                }

                IRasterEdit pRasterEdit = pRaster2 as IRasterEdit;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit);
                return(true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
Example #8
0
        //分析的主要实现函数
        private IRasterLayer Analyze(IRasterLayer pRasterLayer)
        {
            IRaster      pRaster     = pRasterLayer.Raster;
            IRasterProps rasterProps = (IRasterProps)pRaster;

            //设置栅格数据起始点
            IPnt pBlockSize = new Pnt();

            pBlockSize.SetCoords(rasterProps.Width, rasterProps.Height);

            //选取整个范围
            IPixelBlock pPixelBlock = pRaster.CreatePixelBlock(pBlockSize);

            //左上点坐标
            IPnt tlp = new Pnt();

            tlp.SetCoords(0, 0);

            //读入栅格
            IRasterBandCollection pRasterBands = pRaster as IRasterBandCollection;
            IRasterBand           pRasterBand  = pRasterBands.Item(0);
            IRawPixels            pRawRixels   = pRasterBands.Item(0) as IRawPixels;

            pRawRixels.Read(tlp, pPixelBlock);

            //将PixBlock的值组成数组
            Array pSafeArray = pPixelBlock.get_SafeArray(0) as Array;

            //Array转数组
            double[,] myDoubleArr = new double[pSafeArray.GetLength(0), pSafeArray.GetLength(1)];
            for (int i = 0; i < myDoubleArr.GetLength(0); i++)
            {
                for (int j = 0; j < myDoubleArr.GetLength(1); j++)
                {
                    myDoubleArr[i, j] = Convert.ToDouble(pSafeArray.GetValue(i, j));
                }
            }

            for (int i = 0; i < myDoubleArr.GetLength(0); i++)
            {
                for (int j = 0; j < myDoubleArr.GetLength(1); j++)
                {
                    if (myDoubleArr[i, j] == 255)
                    {
                        myDoubleArr[i, j] = 0;
                    }
                }
            }
            double[,] ZeroArray = GetArray(myDoubleArr, Convert.ToInt32(textBox4.Text));
            double[,] OArray    = SumArray(ZeroArray, Convert.ToInt32(textBox4.Text));
            double[,] LastArray = ReturnLastArray(OArray, Convert.ToInt32(textBox4.Text));
            pPixelBlock.set_SafeArray(0, LastArray);

            //StreamWriter sw = File.AppendText(@"E:\GIS底层实验\WorkSpace\result\arrry.txt");
            //for (int y = 0; y < rasterProps.Height; y++)
            //{
            //    for (int x = 0; x < rasterProps.Width; x++)
            //    {
            //        //int value = Convert.ToInt32(pSafeArray.GetValue(x, y));
            //        Byte value = Convert.ToByte(pSafeArray.GetValue(x, y));
            //        string TxtCon = ("X:" + Convert.ToString(x) + "," + "Y:" + Convert.ToString(y) + "," + "Value" + pSafeArray.GetValue(x, y) + "\n");
            //        sw.Write(TxtCon);
            //    }
            //}
            //sw.Flush();
            //sw.Close();

            // 编辑raster,将更新的值写入raster中
            IRasterEdit rasterEdit = pRaster as IRasterEdit;

            rasterEdit.Write(tlp, pPixelBlock);
            rasterEdit.Refresh();
            return(pRasterLayer);
        }
        public void underInit()
        {
            IRaster2              raster2     = m_raster as IRaster2;
            IRasterDataset        rstDataset  = raster2.RasterDataset;
            IRasterBandCollection rstBandColl = rstDataset as IRasterBandCollection;

            if (rstBandColl.Count > 1)
            {
                MessageBox.Show("暂不支持多波段的滤波计算", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            IRasterProps pRasterProps = raster2 as IRasterProps;
            int          Height       = pRasterProps.Height;
            int          Width        = pRasterProps.Width;
            double       cellsizex    = pRasterProps.MeanCellSize().X;

            double            cellsizey        = pRasterProps.MeanCellSize().Y;
            rstPixelType      pixelType        = pRasterProps.PixelType;
            ISpatialReference spatialReference = pRasterProps.SpatialReference;
            //MessageBox.Show(spatialReference.Name.ToString());
            IWorkspaceFactory pRasterWsFac = new RasterWorkspaceFactoryClass();
            IWorkspace        pWs          = pRasterWsFac.OpenFromFile(@"D://RDB", 0);
            IRasterWorkspace2 pRasterWs;

            pRasterWs = pWs as IRasterWorkspace2;
            IPoint origin = new PointClass();

            origin.PutCoords(pRasterProps.Extent.XMin, pRasterProps.Extent.YMin);
            //RasterWorkspace rasterWorkspace = (RasterWorkspace)workspace;
            ISpatialReference sr                 = new UnknownCoordinateSystemClass();
            IRasterDataset2   resultDataset      = pRasterWs.CreateRasterDataset("raster" + "_" + cmb_FliterMethod.SelectedItem.ToString() + ".tif", "TIFF", origin, Width, Height, cellsizex, cellsizey, 1, rstPixelType.PT_DOUBLE, sr) as IRasterDataset2;
            IRaster           resultRaster       = resultDataset.CreateFullRaster();
            IRasterCursor     resultRasterCursor = ((IRaster2)resultRaster).CreateCursorEx(null);

            IRasterDataset2 rasterDataset = raster2.RasterDataset as IRasterDataset2;
            IRaster2        raster        = rasterDataset.CreateFullRaster() as IRaster2;
            IRasterCursor   rasterCursor  = raster.CreateCursorEx(null);

            IPixelBlock3 resultPixelBlock = null;
            IPixelBlock3 tempPixelBlock   = null;
            IRasterEdit  resultRasterEdit = resultRaster as IRasterEdit;

            long blockWidth  = 0;
            long blockHeight = 0;

            // System.Array pixels;
            double[,] kernal = new double[3, 3] {
                { 0, 0, 0 },
                { 0, 1, 0 },
                { 0, 0, 0 }
            };
            switch (cmb_FliterMethod.SelectedItem.ToString())
            {
            case "LineDetectionHorizontal":
                kernal = new double[3, 3] {
                    { -1, -1, -1 },
                    { 2, 2, 2 },
                    { -1, -1, -1 }
                };
                break;

            case "LineDetectionVertical":
                kernal = new double[3, 3] {
                    { -1, 2, -1 },
                    { -1, 2, -1 },
                    { -1, 2, -1 }
                };
                break;

            case "Laplacian3x3":
                kernal = new double[3, 3] {
                    { 0, -1, 0 },
                    { -1, 4, -1 },
                    { 0, -1, 0 }
                };
                break;

            case "Smoothing3x3":
                kernal = new double[3, 3] {
                    { 1, 2, 1 },
                    { 2, 4, 2 },
                    { 1, 2, 1 }
                };
                break;

            case "Sharpening3x3":
                kernal = new double[3, 3] {
                    { -1, -1, -1 },
                    { -1, 9, -1 },
                    { -1, -1, -1 }
                };
                break;
            }
            do
            {
                resultPixelBlock = resultRasterCursor.PixelBlock as IPixelBlock3;
                tempPixelBlock   = rasterCursor.PixelBlock as IPixelBlock3;

                System.Array pixels = (System.Array)tempPixelBlock.get_PixelData(0);
                //MessageBox.Show(pixels3.GetValue(0, 0).GetType().ToString());
                blockHeight = resultPixelBlock.Height;
                blockWidth  = resultPixelBlock.Width;
                System.Array resultPixels = (System.Array)resultPixelBlock.get_PixelData(0);
                //MessageBox.Show(resultPixels.GetValue(0, 0).GetType().ToString());
                for (int i = 0; i < blockHeight; i++)
                {
                    for (int j = 0; j < blockWidth; j++)
                    {
                        double sum = 0;
                        for (int ki = -1; ki <= 1; ki++)
                        {
                            for (int kj = -1; kj <= 1; kj++)
                            {
                                long   idxi = (i + ki) < 0 ? 0 : i + ki >= blockHeight ? blockHeight - 1 : (i + ki);
                                long   idxj = (j + kj) < 0 ? 0 : j + kj >= blockWidth ? blockWidth - 1 : (j + kj);
                                double raw  = double.Parse(pixels.GetValue(idxj, idxi).ToString());
                                sum += raw * kernal[ki + 1, kj + 1];
                            }
                        }
                        resultPixels.SetValue(sum, j, i);
                    }
                }
                resultPixelBlock.set_PixelData(0, (System.Array)resultPixels);
                resultRasterEdit.Write(resultRasterCursor.TopLeft, (IPixelBlock)resultPixelBlock);
                resultRasterEdit.Refresh();
            } while (resultRasterCursor.Next() == true && rasterCursor.Next() == true);
            IRasterDataset pRasterDs = pRasterWs.OpenRasterDataset("raster" + "_" + cmb_FliterMethod.SelectedItem.ToString() + ".tif");
            IRaster        praster   = ((IRasterDataset2)pRasterDs).CreateFullRaster();

            //IRasterLayer resLayer = new RasterLayerClass();
            //resLayer.CreateFromRaster(praster);
            m_raster = praster;
        }
        public bool SetRegionToNoDataValue()
        {
            try
            {
                if (m_pSrcRaster == null || m_pClipPolygon == null || double.IsNaN(m_dbNoDataValue))
                {
                    return(false);
                }

                IGeoDataset   pSrcGeoDataset      = m_pSrcRaster as IGeoDataset;
                IExtractionOp pRasterExtractionOp = new RasterExtractionOpClass();
                IRasterProps  pSrcRasterProps     = m_pSrcRaster as IRasterProps;
                double        dbCellSize          = (pSrcRasterProps.MeanCellSize().X + pSrcRasterProps.MeanCellSize().Y) / 2;

                //设置范围和分辨率
                IRasterAnalysisEnvironment pRasterAnalysisEnv = pRasterExtractionOp as IRasterAnalysisEnvironment;
                pRasterAnalysisEnv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, dbCellSize);
                pRasterAnalysisEnv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, m_pClipPolygon.Envelope, Type.Missing);
                //pRasterAnalysisEnv.OutSpatialReference = (m_pSrcRaster as IRasterProps).SpatialReference;

                //保留区域外的值,区域内的设置为原始栅格的无效值
                IGeoDataset pDstGeoDataset = pRasterExtractionOp.Rectangle(pSrcGeoDataset, m_pClipPolygon.Envelope, true);

                //逐点判断像素是否在区域内,在区域内则改变为设置值,否则不变
                IRelationalOperator pRelationalOp = m_pClipPolygon as IRelationalOperator;
                if (pDstGeoDataset is IRaster)
                {
                    //得到原始栅格的对象,用于修改
                    IRaster2        pSrcRaster2        = m_pSrcRaster as IRaster2;
                    IRasterDataset2 pSrcRasterDataset2 = pSrcRaster2.RasterDataset as IRasterDataset2;
                    IRaster         pTmpRaster         = pSrcRasterDataset2.CreateFullRaster();
                    IRasterEdit     pSrcEdit           = pTmpRaster as IRasterEdit;
                    //得到图层NoDataValue
                    IRasterProps rasterProps = pSrcRaster2 as IRasterProps;
                    double       noData      = ClsGDBDataCommon.getNoDataValue(rasterProps.NoDataValue);

                    //得到输出的栅格
                    IRaster2      pDstRaster2      = pDstGeoDataset as IRaster2;
                    IRasterProps  pDstRasterProps  = pDstRaster2 as IRasterProps;
                    IRasterCursor pDstRasterCursor = pDstRaster2.CreateCursorEx(null);
                    //pDstRasterCursor.Reset();

                    do
                    {
                        //得到当前处理的块
                        IPixelBlock3 pixelBlock3 = pDstRasterCursor.PixelBlock as IPixelBlock3;
                        int          nWidth      = pixelBlock3.Width;
                        int          nHeight     = pixelBlock3.Height;
                        IPnt         ptLeftTop   = pDstRasterCursor.TopLeft;

                        //block值转数组时,NoData转换时有时为NoData,有时为栅格中的最小值
                        System.Array array = pixelBlock3.get_PixelData(0) as System.Array;

                        //逐点判断: 判断像素是否在区域内,在区域内则改变为设置值,否则不变
                        for (int i = 0; i < nWidth; i++)
                        {
                            for (int j = 0; j < nHeight; j++)
                            {
                                double dbX = double.NaN, dbY = double.NaN;

                                //得到当前像素点的地图坐标
                                int nCurrentX = Convert.ToInt32(ptLeftTop.X + i);
                                int nCurrentY = Convert.ToInt32(ptLeftTop.Y + j);
                                pDstRaster2.PixelToMap(nCurrentX, nCurrentY, out dbX, out dbY);
                                IPoint ptInMap = new PointClass();
                                ptInMap.X = dbX;
                                ptInMap.Y = dbY;

                                //判断是否在区域内
                                bool bFlag = pRelationalOp.Contains(ptInMap as IGeometry);
                                if (bFlag) //在当前区域内
                                {
                                    object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue);
                                    array.SetValue(oValidValue, i, j);
                                }
                                else
                                {
                                    double v = Convert.ToDouble(array.GetValue(i, j));

                                    if (v == 0 || v < -3.4e15 || v > 3.4e15)
                                    //if (v == 0 || Math.Abs(v -noData) <1e18)
                                    {
                                        int col, row;
                                        pSrcRaster2.MapToPixel(dbX, dbY, out col, out row);
                                        //表示getpixelvalue为null表示nodata
                                        object obj = pSrcRaster2.GetPixelValue(0, col, row);
                                        if (obj == null)
                                        {
                                            object oValidValue = getValidType(pDstRasterProps, m_dbNoDataValue);
                                            array.SetValue(oValidValue, i, j);
                                        }
                                        else
                                        {
                                            array.SetValue(obj, i, j);
                                        }
                                    }
                                }
                            }
                        }
                        pixelBlock3.set_PixelData(0, array);

                        //得到当前区域块在原图中的左上角像素坐标, 直接修改原栅格的数据
                        int    nPixelLeftX = -1, nPixelLeftY = -1;
                        double dbMapLeftTopX = double.NaN, dbMapLeftTopY = double.NaN;
                        pDstRaster2.PixelToMap(Convert.ToInt32(ptLeftTop.X), Convert.ToInt32(ptLeftTop.Y), out dbMapLeftTopX, out dbMapLeftTopY); //得到当前块左上角的地理坐标
                        pSrcRaster2.MapToPixel(dbMapLeftTopX, dbMapLeftTopY, out nPixelLeftX, out nPixelLeftY);

                        IPnt ptPixelLeftTop = new PntClass();
                        ptPixelLeftTop.SetCoords(nPixelLeftX, nPixelLeftY);
                        if (pSrcEdit.CanEdit())
                        {
                            pSrcEdit.Write(ptPixelLeftTop, pixelBlock3 as IPixelBlock);
                            //pSrcEdit.Refresh();
                        }
                        else
                        {
                            return(false);
                        }
                    } while (pDstRasterCursor.Next() == true);

                    //更新
                    pSrcEdit.Refresh();
                }
                else
                {
                    return(false);
                }

                return(true);
            }
            catch (System.Exception ex)
            {
                return(false);
            }
        }
Example #11
0
        //逐点算法
        public bool ImageReprojectionRange(IRaster pSrcRaster, out IRaster pDstRaster, ExOriPara exori,
                                           double dbFocus, double fx, double fy, int nImgWidth, int nImgHeight, int nGeoRange)
        {
            pDstRaster = null;

            Pt2i ptSubImgLeftTop = new Pt2i();

            double[,] dbSubDemData = getSubDem(pSrcRaster, exori.pos, nGeoRange, ref ptSubImgLeftTop);
            if (dbSubDemData == null)
            {
                return(false);
            }

            IRasterProps pProps     = pSrcRaster as IRasterProps;
            int          nDemHeight = pProps.Height;
            int          nDemWidth  = pProps.Width;

            IRaster2 pRaster2 = pSrcRaster as IRaster2;

            double dbNoDataValue = getNoDataValue(pProps.NoDataValue);
            //object pNodata = pProps.NoDataValue;
            //double value=((double[])pNodata)[0];
            //double dbNoDataValue =double.Parse((float[]pNodata)[0].ToString());
            //double dbNoDataValue = Convert.ToDouble(((double[]))[0]);
            //object dbNoDataValue = Convert.ToDouble(pProps.NoDataValue.ToString());
            //object nodatavalue = pProps.NoDataValue;
            //Type type=pProps.NoDataValue.GetType();
            //double dbNoDataValue = type.IsArray ? nodatavalue[0] as double : nodatavalue as double;

            //初始步长
            double dbInitialStep = 0;
            int    nGridW        = nDemWidth / 10;
            int    nGridH        = nDemHeight / 10;
            int    nCount        = 0;
            double dbHeightAvg   = 0;

            for (int i = 0; i < 10; i++)
            {
                for (int j = 0; j < 10; j++)
                {
                    double dDemZ  = double.NaN;
                    double dbGeoX = pRaster2.ToMapX(i * nGridW);
                    double dbGeoY = pRaster2.ToMapY(j * nGridH);
                    if (GetGeoZ(pSrcRaster, dbSubDemData, ptSubImgLeftTop, dbGeoX, dbGeoY, ref dDemZ) && Math.Abs(dDemZ - dbNoDataValue) >= 10e-10)
                    {
                        nCount++;
                        dbHeightAvg += dDemZ;
                    }
                }
            }
            if (nCount != 0)
            {
                dbHeightAvg /= nCount;
            }
            else
            {
                return(false);
            }

            double dbCurCameraZ = 0;

            //IRaster2 pRaster2 = pSrcRaster as IRaster2;
            //int nCameraImgX = pRaster2.ToPixelColumn(exori.pos.X);//dXCumulate - pDem.m_PtOrigin.X) / dXRdem;
            //int nCameraImgY = pRaster2.ToPixelRow(exori.pos.Y); // (dYCumulate - pDem.m_PtOrigin.Y) / dYRdem;

            //if (nCameraImgY >= 0 || nCameraImgY < nDemHeight || nCameraImgX >= 0 || nCameraImgX < nDemWidth)
            //{
            if (GetGeoZ(pSrcRaster, dbSubDemData, ptSubImgLeftTop, exori.pos.X, exori.pos.Y, ref dbCurCameraZ) && Math.Abs(dbCurCameraZ - dbNoDataValue) >= 10e-10)
            {
                dbHeightAvg = dbCurCameraZ;
            }
            //}
            dbInitialStep = Math.Abs(dbHeightAvg - exori.pos.Z) / 2;


            Point2D ptLeftTop = new Point2D(0, 0);

            double[] dbResolution = new double[2];
            dbResolution[0] = pProps.MeanCellSize().X;
            dbResolution[1] = pProps.MeanCellSize().Y;

            int[] nSize = new int[2];
            nSize[0] = nDemWidth;
            nSize[1] = nDemHeight;

            //pDstRaster = CreateRaster(ptLeftTop, dbResolution, nSize);
            //pDstRaster = createRasterWithoutData(ptLeftTop, dbResolution[0], nSize, "testOutput.tif");

            // byte[,] dbData = new byte[nDemWidth, nDemHeight];

            //double demGrayVal=double.NaN;
            //Pt3d demXYZ;
            //byte byteGray;
            //byte bt = (byte)255;

            //Pt2d pt;
            Matrix matA, matB;

            matA = new Matrix(2, 2);
            matB = new Matrix(2, 1);
            Matrix matR;

            matR = new Matrix(3, 3);

            //Matrix matX;

            double[] a = new double[4];
            double[] b = new double[2];

            OPK2RMat(exori.ori, ref matR);    //求解相关系数

            double a1 = matR.getNum(0, 0);
            double a2 = matR.getNum(0, 1);
            double a3 = matR.getNum(0, 2);

            double b1 = matR.getNum(1, 0);
            double b2 = matR.getNum(1, 1);
            double b3 = matR.getNum(1, 2);

            double c1 = matR.getNum(2, 0);
            double c2 = matR.getNum(2, 1);
            double c3 = matR.getNum(2, 2);

            double[] dbCoef = new double[] { a1, a2, a3, b1, b2, b3, c1, c2, c3 };

            //double X, Y, Z, Z1;
            // Z = 0.0;

            //double dthreshold = 0.01;

            //初始化数组
            //int[,] dbData = new int[nDemWidth, nDemHeight];
            //for (int i = 0; i < nDemWidth; i++)
            //{
            //    for (int j = 0; j < nDemHeight; j++)
            //    {
            //        dbData[i, j] = 0;
            //    }
            //}



            try
            {
                //生成RASTER
                Point2D pt2dTopLeft = new Point2D();
                pt2dTopLeft.X = pProps.Extent.UpperLeft.X;
                pt2dTopLeft.Y = pProps.Extent.UpperLeft.Y;
                pDstRaster    = CreateRaster(pt2dTopLeft, dbResolution, nSize);
                if (pDstRaster == null)
                {
                    return(false);
                }

                //得到数组
                IPnt pBlockSize = new DblPntClass();
                pBlockSize.X = nDemWidth;
                pBlockSize.Y = nDemHeight;

                IPnt pntLeftTop = new DblPntClass();
                pntLeftTop.SetCoords(ptLeftTop.X, ptLeftTop.Y);

                IPixelBlock  pPixelBlock  = pDstRaster.CreatePixelBlock(pBlockSize);
                IPixelBlock3 pPixelBlock3 = pPixelBlock as IPixelBlock3;
                pDstRaster.Read(pntLeftTop, pPixelBlock);

                System.Array pixels;
                pixels = (System.Array)pPixelBlock3.get_PixelData(0);

                //初始化
                object oValue = getValidType(pDstRaster as IRasterProps, 0);
                for (int i = 0; i < nDemHeight; i++)
                {
                    for (int j = 0; j < nDemWidth; j++)
                    {
                        pixels.SetValue(oValue, j, i);
                    }
                }

                //逐像素判断是否可见
                IRaster2 pSrcRaster2 = pSrcRaster as IRaster2;
                oValue = getValidType(pDstRaster as IRasterProps, 255);
                for (int i = 0; i < nImgHeight; i++)
                {
                    for (int j = 0; j < nImgWidth; j++)
                    {
                        Point2D ptCurrent = null;
                        if (getPixelIsCoverd(pSrcRaster, dbSubDemData, ptSubImgLeftTop, j, i, out ptCurrent, exori, dbCoef, dbFocus, fx, fy, dbInitialStep))
                        {
                            int nCol = int.MaxValue, nRow = int.MaxValue;
                            pSrcRaster2.MapToPixel(ptCurrent.X, ptCurrent.Y, out nCol, out nRow);
                            if (nCol >= nDemWidth || nCol < 0 || nRow < 0 || nRow >= nDemHeight)
                            {
                                continue;
                            }

                            pixels.SetValue(oValue, nCol, nRow);
                            //pixels[nCol, nRow] = 255;
                        }
                    }
                }
                pPixelBlock3.set_PixelData(0, (System.Array)pixels);

                //修改数据
                IRasterEdit pRasterEdit = pDstRaster as IRasterEdit;
                pRasterEdit.Write(pntLeftTop, pPixelBlock);
                pRasterEdit.Refresh();
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }

            return(true);
        }