コード例 #1
0
        //public IFeatureClass createPolygons3()
        //{
        //    createFeatureClass();

        //}
        public IFeatureClass createPolygons2()
        {
            createFeatureClass();
            IRasterProps           rsProp   = (IRasterProps)inputRaster;
            int                    bndCnt   = ((IRasterBandCollection)inputRaster).Count;
            IPnt                   rsPnt    = rsProp.MeanCellSize();
            double                 cellArea = rsPnt.X * rsPnt.Y;
            double                 tCells   = minArea / cellArea;
            IFunctionRasterDataset sDset    = rsUtil.createMeanShiftFuction(inputRaster, (int)tCells);

            FunctionRasters.meanShiftFunctionDataset rFunc = (FunctionRasters.meanShiftFunctionDataset)sDset.Function;
            IRaster2               rs2   = (IRaster2)rsUtil.createRaster(sDset);
            IRasterCursor          rsCur = rs2.CreateCursorEx(null);
            IRasterDomainExtractor dExt  = new RasterDomainExtractorClass();

            do
            {
                IPixelBlock            pb     = rsCur.PixelBlock;
                IFunctionRasterDataset pbDset = rsUtil.PixelBlockToRaster(pb, rsCur.TopLeft, sDset);
                IRaster rs          = rsUtil.createRaster(pbDset);
                int     numClusters = rFunc.NumClusters;
                for (int c = 0; c < numClusters; c++)
                {
                    IFunctionRasterDataset fd  = rsUtil.calcEqualFunction(pbDset, c);
                    IFunctionRasterDataset fd2 = rsUtil.setNullValue(fd, 0);
                    IPolygon polys             = dExt.ExtractDomain(rsUtil.createRaster(fd2), true);
                }
            } while (rsCur.Next() == true);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rsCur);



            return(outftr);
        }
コード例 #2
0
        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;
        }
コード例 #3
0
ファイル: Program.cs プロジェクト: wblong/RasterOperation
        /// <summary>
        /// 栅格操作修改栅格的值
        /// </summary>
        /// <param name="pRasterDataset2"></param>
        public static void ChangeRasterValue(IRasterDataset2 pRasterDataset2)
        {
            //设置读取栅格的大小
            IRaster2 pRaster2  = pRasterDataset2.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       = pRasterDataset2 as IRasterBandCollection;
                IPixelBlock3          pPixelblock3 = null;
                int          pBlockwidth           = 0;
                int          pBlockheight          = 0;
                System.Array pixels;
                object       pValue;
                long         pBandCount = pBands.Count;
                //
                IRasterProps pRasterProps = pRaster2 as IRasterProps;
                object       nodata       = pRasterProps.NoDataValue;
                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);
                                int value = Convert.ToInt32(pValue);
                                if (Convert.ToInt32(pValue) != 3)
                                {
                                    pixels.SetValue(Convert.ToByte(0), i, j);
                                }
                            }
                        }
                        pPixelblock3.set_PixelData(k, pixels);
                    }
                    pPntBlock = pRasterCursor.TopLeft;
                    pRasterEdit.Write(pPntBlock, (IPixelBlock)pPixelblock3);
                } while (pRasterCursor.Next());
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit);
            }
        }
コード例 #4
0
        //标注提取的未扩展的湿地对象的代表性点
        public static void labelObjPoint(IGeoDataset pGeodataset, int objVal, string errstring)
        {
            IRaster           pRaster      = pGeodataset as IRaster;
            IRaster2          pRaster2     = pRaster as IRaster2;
            IRasterProps      pRasterProps = pRaster as IRasterProps;
            ISpatialReference pSR          = pGeodataset.SpatialReference;
            //获取图层的行列值
            int height = pRasterProps.Height;
            int width  = pRasterProps.Width;

            //定义并初始化数组,用于存储栅格内的所有像元值
            double[,] PixelVal = new double[height, width];
            //这是像素块大小
            IPnt blocksize = new PntClass();

            blocksize.SetCoords(256, 256);
            IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(blocksize);

            //存储像素块的行列值、像素值
            System.Array pixels;
            IPixelBlock3 pPixelBlock3;

            do
            {
                int xunit = (int)pRasterCursor.TopLeft.X;
                int yunit = (int)pRasterCursor.TopLeft.Y;
                pPixelBlock3 = pRasterCursor.PixelBlock as IPixelBlock3;
                pixels       = (Array)pPixelBlock3.get_PixelData(0);
                for (int i = 0; i < pPixelBlock3.Height; i++)
                {
                    for (int j = 0; j < pPixelBlock3.Width; j++)
                    {
                        PixelVal[yunit + i, xunit + j] = Convert.ToDouble(pixels.GetValue(j, i));
                        if (PixelVal[yunit + i, xunit + j] == objVal)
                        {
                            IPoint pPoint = new PointClass();
                            pPoint.SpatialReference = pSR;
                            pPoint.X = pRaster2.ToMapX(xunit + j);
                            pPoint.Y = pRaster2.ToMapY(yunit + i);
                            ChkMarkPoint.insertChkPoint("cglc_chkmark", pPoint as IGeometry, errstring);
                            //MessageBox.Show("Neighborhood Relation Checking Complete...");
                            return;
                        }
                    }
                }
            } while (pRasterCursor.Next());
        }
コード例 #5
0
        private static Dictionary <string, double> getStrataProportion(IFunctionRasterDataset strataRaster, rasterUtil rsUtil)
        {
            IRaster2 rs2 = (IRaster2)rsUtil.createRaster(strataRaster);
            Dictionary <string, double> outDic = new Dictionary <string, double>();
            IRasterCursor rsCur = rs2.CreateCursorEx(null);
            //Console.WriteLine(((IRasterProps)rs2).Height.ToString() + ((IRasterProps)rs2).Height.ToString());
            int n = 0;

            do
            {
                IPixelBlock pb = rsCur.PixelBlock;
                //Console.WriteLine("PixelBLock w_h = " + pb.Width.ToString() + "_" + pb.Height.ToString());
                for (int r = 0; r < pb.Height; r++)
                {
                    for (int c = 0; c < pb.Width; c++)
                    {
                        object vlObj = pb.GetVal(0, c, r);
                        if (vlObj != null)
                        {
                            string vl = vlObj.ToString();
                            double vlCnt;
                            if (outDic.TryGetValue(vl, out vlCnt))
                            {
                                outDic[vl] = vlCnt + 1;
                            }
                            else
                            {
                                outDic.Add(vl, 1);
                            }
                            n += 1;
                        }
                        else
                        {
                            //Console.WriteLine("VL Null");
                        }
                    }
                }
            } while (rsCur.Next() == true);
            //Console.WriteLine("OutDic Count = " + outDic.Count.ToString());
            System.Runtime.InteropServices.Marshal.ReleaseComObject(rsCur);
            foreach (string s in outDic.Keys.ToArray())
            {
                double vl = outDic[s];
                outDic[s] = vl / n;
            }
            return(outDic);
        }
コード例 #6
0
        private void getRasterMatrix()
        {
            n = 0;
            List <double[]>       inputMatrixLst = new List <double[]>();
            IRaster2              rs2            = (IRaster2)InRaster;
            IRasterBandCollection rsbc           = (IRasterBandCollection)rs2;
            IRasterProps          rsp            = (IRasterProps)rs2;
            //System.Array nDataVlArr = (System.Array)rsp.NoDataValue;
            IRasterCursor rsCur = rs2.CreateCursorEx(null);
            IPixelBlock   pb    = null;
            Random        rand  = new Random();

            do
            {
                pb = rsCur.PixelBlock;
                for (int r = 0; r < pb.Height; r++)
                {
                    for (int c = 0; c < pb.Width; c++)
                    {
                        object vlObj = pb.GetVal(0, c, r);
                        if (vlObj == null)
                        {
                            continue;
                        }
                        else
                        {
                            if (rand.NextDouble() <= prop)
                            {
                                double[] vlBandArr = new double[rsbc.Count];
                                double   vl        = System.Convert.ToDouble(vlObj);
                                vlBandArr[0] = vl;
                                for (int p = 1; p < pb.Planes; p++)
                                {
                                    vlObj = pb.GetVal(p, c, r);
                                    vl    = System.Convert.ToDouble(vlObj);

                                    vlBandArr[p] = vl;
                                }
                                inputMatrixLst.Add(vlBandArr);
                                n++;
                            }
                        }
                    }
                }
            } while (rsCur.Next() == true);
            inputMatrix = inputMatrixLst.ToArray();
        }
コード例 #7
0
        private void getRasterMatrix()
        {
            n = 0;
            List <double[]>       inputMatrixLst = new List <double[]>();
            IRaster2              rs2            = (IRaster2)InRaster;
            IRasterBandCollection rsbc           = (IRasterBandCollection)rs2;
            IRasterProps          rsp            = (IRasterProps)rs2;

            System.Array  nDataVlArr = (System.Array)rsp.NoDataValue;
            IRasterCursor rsCur      = rs2.CreateCursorEx(null);
            IPixelBlock   pb         = null;

            System.Array[] pbArrs = new System.Array[rsbc.Count];
            Random         rand   = new Random();

            do
            {
                pb = rsCur.PixelBlock;
                for (int i = 0; i < pb.Planes; i++)
                {
                    pbArrs[i] = (System.Array)pb.get_SafeArray(i);
                }
                for (int r = 0; r < pb.Height; r++)
                {
                    for (int c = 0; c < pb.Width; c++)
                    {
                        if (rand.NextDouble() <= prop)
                        {
                            double[] vlBandArr = new double[rsbc.Count];
                            for (int p = 0; p < pb.Planes; p++)
                            {
                                System.Array pbArr = pbArrs[p];
                                double       vl    = System.Convert.ToDouble(pbArr.GetValue(c, r));
                                if (rasterUtil.isNullData(vl, nDataVlArr.GetValue(p)))
                                {
                                    vl = 0;
                                }
                                vlBandArr[p] = vl;
                            }
                            inputMatrixLst.Add(vlBandArr);
                            n++;
                        }
                    }
                }
            } while (rsCur.Next() == true);
            inputMatrix = inputMatrixLst.ToArray();
        }
コード例 #8
0
        public void CalRasterAtt(IRaster2 pRaster2, ref double dmax, ref double dmin)
        {
            double pixelmax = -999999999; //记录栅格回的最大值
            double pixermin = 999999999;  //记录栅格灰度最小值

            object obj    = null;
            double dPixel = 0.0;

            int nWidth  = 0;
            int nHeight = 0;

            System.Array  pixels;
            IPixelBlock3  pixelBlock3  = null;
            IRasterCursor rasterCursor = pRaster2.CreateCursorEx(null);//null时为128*128

            do
            {
                pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;
                nWidth      = pixelBlock3.Width;
                nHeight     = pixelBlock3.Height;
                pixels      = (System.Array)pixelBlock3.get_PixelData(0);
                for (int i = 0; i < nWidth; i++)
                {
                    for (int j = 0; j < nHeight; j++)
                    {
                        obj = pixels.GetValue(i, j);
                        double ob = Convert.ToDouble(obj);
                        if (ob > -99999 && ob < 99999)
                        {
                            dPixel = Convert.ToDouble(obj);
                            if (dPixel >= pixelmax)
                            {
                                pixelmax = dPixel;
                            }
                            if (dPixel <= pixermin)
                            {
                                pixermin = dPixel;
                            }
                        }
                    }
                }
            } while (rasterCursor.Next() == true);

            dmax = pixelmax;
            dmin = pixermin;
        }
コード例 #9
0
        public static bool disJointRelation(IGeoDataset pGeodataset, int disjointVal)
        {
            IRaster      pRaster      = pGeodataset as IRaster;
            IRaster2     pRaster2     = pRaster as IRaster2;
            IRasterProps pRasterProps = pRaster as IRasterProps;
            //获取图层的行列值
            int height = pRasterProps.Height;
            int width  = pRasterProps.Width;

            //定义并初始化数组,用于存储栅格内的所有像元值
            double[,] PixelVal = new double[height, width];
            //这是像素块大小
            IPnt blocksize = new PntClass();

            blocksize.SetCoords(256, 256);
            IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(blocksize);

            //存储像素块的行列值、像素值
            System.Array pixels;
            IPixelBlock3 pPixelBlock3;
            bool         disjoint = true;

            do
            {
                int xunit = (int)pRasterCursor.TopLeft.X;
                int yunit = (int)pRasterCursor.TopLeft.Y;
                pPixelBlock3 = pRasterCursor.PixelBlock as IPixelBlock3;
                pixels       = (Array)pPixelBlock3.get_PixelData(0);
                for (int i = 0; i < pPixelBlock3.Height; i++)
                {
                    for (int j = 0; j < pPixelBlock3.Width; j++)
                    {
                        PixelVal[yunit + i, xunit + j] = Convert.ToDouble(pixels.GetValue(j, i));
                        if (PixelVal[yunit + i, xunit + j] == disjointVal)
                        {
                            disjoint = false; //判断此幅数据是否满足邻近性
                            break;
                        }
                    }
                }
            } while (pRasterCursor.Next());
            return(disjoint);
        }
コード例 #10
0
        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);
        }
コード例 #11
0
        /// <summary>
        /// 读取指定块处的像元值到数组.
        /// </summary>
        /// <param name="pRasterDS">The p raster ds.</param>
        /// <param name="pBlockSize0">左上角点.</param>
        /// <param name="pBlockSize1">块大小.</param>
        /// <returns>System.Single[].</returns>
        public static float[,] ReadFloat(IRasterDataset2 pRasterDS, IPnt pBlockSize0, IPnt pBlockSize1)
        {
            try
            {
                //IRaster pRaster = thisRasterLayer.Raster;
                IRaster      pRaster  = pRasterDS.CreateFullRaster();
                IRaster2     pRaster2 = (IRaster2)pRaster;
                IRasterProps pRSp     = (IRasterProps)pRaster;

                IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize1).PixelBlock;

                pRaster.Read(pBlockSize0, pixelBlock);
                IPixelBlock3 block2 = (IPixelBlock3)pixelBlock;
                return((float[, ])block2.get_PixelData(0));
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("读取影像失败!\n" + ex.Message);
                return(null);
            }
        }
コード例 #12
0
        public static void ReplacePixel(IRasterDataset2 irasterDataset2_0)
        {
            IRaster2 raster2  = irasterDataset2_0.CreateFullRaster() as IRaster2;
            IPnt     pntClass = new Pnt()
            {
                X = 128,
                Y = 128
            };

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

            if (rasterEdit.CanEdit())
            {
                long         count       = (long)(irasterDataset2_0 as IRasterBandCollection).Count;
                IRasterProps rasterProp  = raster2 as IRasterProps;
                object       noDataValue = rasterProp.NoDataValue;
                rasterProp.NoDataValue = 255;
                (rasterProp as ISaveAs).SaveAs("j:\\image1.tif", null, "TIFF");
                Marshal.ReleaseComObject(rasterEdit);
            }
        }
コード例 #13
0
        /// <summary>
        /// 一次读取整幅影像像元值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="pRasterDS">The p raster ds.</param>
        /// <returns>T[].</returns>
        public static T[,] ReadPixelValue <T>(IRasterDataset2 pRasterDS)
        {
            try
            {
                //IRaster pRaster = thisRasterLayer.Raster;
                IRaster      pRaster    = pRasterDS.CreateFullRaster();
                IRaster2     pRaster2   = (IRaster2)pRaster;
                IRasterProps pRSp       = (IRasterProps)pRaster;
                IPnt         pBlockSize = new PntClass();
                pBlockSize.SetCoords((float)pRSp.Width, (float)pRSp.Height);
                IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize).PixelBlock;
                pBlockSize.SetCoords(0.0, 0.0);
                pRaster.Read(pBlockSize, pixelBlock);
                IPixelBlock3 block2 = (IPixelBlock3)pixelBlock;

                return((T[, ])block2.get_PixelData(0));;
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show("读取分类影像失败!\n" + ex.Message);
                return(null);
            }
        }
コード例 #14
0
        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);
            }
        }
コード例 #15
0
        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");
        }
コード例 #16
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)
            {
            }
        }
コード例 #17
0
        public double[,] Class_GetPixelValue(IRasterLayer pRasterLayer1)
        {
            //IRasterLayer pOut;

            IRaster      pRaster      = pRasterLayer1.Raster;
            IRaster2     pRaster2     = pRaster as IRaster2;
            IRasterProps pRasterProps = pRaster as IRasterProps;

            //获取图层的行列值
            int Height = pRasterProps.Height;
            int Width  = pRasterProps.Width;

            //定义并初始化数组,用于存储栅格内所有像员像素值
            double[,] PixelValue = new double[Height, Width];
            //thisRasterLayer = pRasterLayer1;

            System.Array pixels;

            //定义RasterCursor初始化,参数设为null,内部自动设置PixelBlock大小
            IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(null);

            //用于存储PixelBlock的长宽
            long blockwidth  = 0;
            long blockheight = 0;

            IPixelBlock3 pPixelBlock3;

            try
            {
                do
                {
                    //获取Cursor的左上角坐标
                    int left = (int)pRasterCursor.TopLeft.X;
                    int top  = (int)pRasterCursor.TopLeft.Y;

                    pPixelBlock3 = pRasterCursor.PixelBlock as IPixelBlock3;

                    blockheight = pPixelBlock3.Height;
                    blockwidth  = pPixelBlock3.Width;
                    //pPixelBlock3.Mask(255);

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

                    //指定平面的像素的数组
                    //获取该Cursor的PixelBlock中像素的值
                    for (int i = 0; i < blockheight; i++)
                    {
                        for (int j = 0; j < blockwidth; j++)
                        {
                            //一定要注意,pixels中的数组排序为[Width,Height]

                            PixelValue[top + i, left + j] = Convert.ToDouble(pixels.GetValue(j, i));
                        }
                    }
                }while (pRasterCursor.Next() == true);
                //MessageBox.Show("完成遍历!");
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return(PixelValue);
        }
コード例 #18
0
        private void btn_2e_Click(object sender, EventArgs e)
        {
            ILayer        pLayer       = new FeatureLayerClass();
            IFeatureClass featureClass = GetFeatureClass(@"D:\a_gis工程设计实践课\china\墓穴地shp\grave.shp");
            IGeoDataset   geo          = featureClass as IGeoDataset;

            object extend = geo.Extent;
            object o      = null;
            IFeatureClassDescriptor feades = new FeatureClassDescriptorClass();

            feades.Create(featureClass, null, "area");
            IRasterRadius rasterrad = new RasterRadiusClass();

            rasterrad.SetVariable(12, ref o);
            object                     dCell     = 0.014800000;//可以根据不同的点图层进行设置
            IInterpolationOp           interpla  = new RasterInterpolationOpClass();
            IRasterAnalysisEnvironment rasanaenv = interpla as IRasterAnalysisEnvironment;

            rasanaenv.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref dCell);
            rasanaenv.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extend, ref o);
            IGeoDataset  g_GeoDS_Raster  = interpla.IDW((IGeoDataset)feades, 2, rasterrad, ref o);
            IRaster      pOutRsater      = (IRaster)g_GeoDS_Raster;
            IRasterLayer pOutRasterlayer = new RasterLayerClass();

            pOutRasterlayer.CreateFromRaster(pOutRsater);
            pOutRasterlayer.Name = "两个因素都考虑";

            //IRaster raster = pOutRasterlayer.Raster;
            IRaster2 raster2 = (IRaster2)pOutRsater;
            // 指定像素块大小
            IPnt pntBlock = new PntClass();

            pntBlock.X = 1280;
            pntBlock.Y = 1280;
            //创建一个光标以给定像素块大小
            //定义RasterCursor初始化,参数设为null,内部自动设置PixelBlock大小
            //IRasterCursor pRasterCursor = pRaster2.CreateCursorEx(null);
            IRasterCursor rasterCursor = raster2.CreateCursorEx(null);
            //控制像素块级别的编辑操作
            IRasterEdit rasterEdit = raster2 as IRasterEdit;

            if (rasterEdit.CanEdit())
            {
                //得到一段光栅带
                IRasterBandCollection bandCollection = (IRasterBandCollection)pOutRsater;
                System.Array          pixels;
                IPnt   pnt = null;
                object value;
                int    bandCount = bandCollection.Count;
                //创建像素块
                IPixelBlock3 pixelBlock3 = null;
                int          blockWidth  = 0;
                int          blockHeight = 0;
                double       temp        = 0;
                do
                {
                    pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;
                    blockWidth  = pixelBlock3.Width;
                    blockHeight = pixelBlock3.Height;
                    for (int k = 0; k < bandCount; k++)
                    {
                        //指定平面的像素的数组
                        pixels = (System.Array)pixelBlock3.get_PixelData(k);

                        for (int i = 0; i < blockWidth; i++)
                        {
                            for (int j = 0; j < blockHeight; j++)
                            {
                                //value = pixels.GetValue(i, j);

                                ////if (Convert.ToInt32(value) == 0)
                                //{
                                //设置像素的颜色值
                                temp = PixelValue1[i, j] + PixelValue2[i, j];
                                pixels.SetValue((int)temp, i, j);
                                //}
                            }
                        }
                        pixelBlock3.set_PixelData(k, pixels);
                    }
                    pnt = rasterCursor.TopLeft;
                    rasterEdit.Write(pnt, (IPixelBlock)pixelBlock3);
                }while (rasterCursor.Next());
                System.Runtime.InteropServices.Marshal.ReleaseComObject(rasterEdit);



                //渲染
                IRasterClassifyColorRampRenderer pRClassRend = new RasterClassifyColorRampRendererClass();
                IRasterRenderer pRRend = pRClassRend as IRasterRenderer;

                IRaster pRaster = pOutRasterlayer.Raster;
                IRasterBandCollection pRBandCol = pRaster as IRasterBandCollection;
                IRasterBand           pRBand    = pRBandCol.Item(0);
                if (pRBand.Histogram == null)
                {
                    pRBand.ComputeStatsAndHist();
                }
                pRRend.Raster          = pRaster;
                pRClassRend.ClassCount = 10;
                pRRend.Update();

                IRgbColor pFromColor = new RgbColorClass();
                pFromColor.Red   = 135;//天蓝色
                pFromColor.Green = 206;
                pFromColor.Blue  = 235;
                IRgbColor pToColor = new RgbColorClass();
                pToColor.Red   = 124;//草坪绿
                pToColor.Green = 252;
                pToColor.Blue  = 0;

                IAlgorithmicColorRamp colorRamp = new AlgorithmicColorRampClass();
                colorRamp.Size      = 10;
                colorRamp.FromColor = pFromColor;
                colorRamp.ToColor   = pToColor;
                bool createColorRamp;
                colorRamp.CreateRamp(out createColorRamp);

                IFillSymbol fillSymbol = new SimpleFillSymbolClass();

                for (int i = 0; i < pRClassRend.ClassCount; i++)
                {
                    fillSymbol.Color = colorRamp.get_Color(i);
                    pRClassRend.set_Symbol(i, fillSymbol as ISymbol);
                    pRClassRend.set_Label(i, pRClassRend.get_Break(i).ToString("0.00"));
                }
                pOutRasterlayer.Renderer = pRRend;
                this.axMapControl1.AddLayer(pOutRasterlayer);
            }
        }
コード例 #19
0
        private void buildRaster()
        {
            n = 0;
            IRaster2              rs2        = (IRaster2)InRaster;
            IRasterProps          rsP        = (IRasterProps)rs2;
            int                   tCells     = rsP.Width * rsP.Height;
            double                selectProp = System.Convert.ToDouble(MaxSampleSize) / System.Convert.ToDouble(tCells);
            IRasterBandCollection rsbc       = (IRasterBandCollection)rs2;
            IRasterCursor         rsCur      = rs2.CreateCursorEx(null);
            IPixelBlock           pb         = null;
            Random                rn         = new Random();

            double[] vlBandArr = new double[rsbc.Count];
            do
            {
                pb = rsCur.PixelBlock;
                int w = pb.Width;
                int h = pb.Height;
                tCells = w * h;
                int nCells = (int)(tCells * selectProp);
                if (nCells == 0)
                {
                    nCells = 1;
                }
                for (int z = 0; z < nCells; z++)
                {
                    int  cellloc = rn.Next(1, tCells);
                    int  r       = ((cellloc - 1) / w);
                    int  c       = (cellloc - (r * w)) - 1;
                    bool chVl    = true;
                    for (int p = 0; p < pb.Planes; p++)
                    {
                        object vlobj = pb.GetVal(p, c, r);
                        if (vlobj == null)
                        {
                            chVl = false;
                            break;
                        }

                        vlBandArr[p] = System.Convert.ToDouble(vlobj);
                    }
                    if (chVl)
                    {
                        for (int v = 0; v < vlBandArr.Length; v++)
                        {
                            sumClms[v]     += vlBandArr[v];
                            sumCross[v, v] += Math.Pow(vlBandArr[v], 2);
                            for (int j = 0 + v + 1; j < vlBandArr.Length; j++)
                            {
                                double vl1 = vlBandArr[v];
                                double vl2 = vlBandArr[j];
                                double p12 = vl1 * vl2;
                                sumCross[v, j] += p12;
                                sumCross[j, v] += p12;
                            }
                        }
                        n++;
                    }
                    else
                    {
                        continue;
                    }
                }
            } while (rsCur.Next() == true);
            int sampN = n;

            for (int i = 0; i < sumClms.Length; i++)
            {
                double var = (sumCross[i, i] / (sampN)) - (Math.Pow(sumClms[i], 2) / Math.Pow((sampN), 2));
                cov[i, i] = var;
                double sVl = sumClms[i] / sampN;
                for (int j = 0 + i + 1; j < sumClms.Length; j++)
                {
                    double vl1 = (sumCross[i, j] / (sampN));
                    double vl2 = (sVl * (sumClms[j] / (sampN)));
                    double p12 = vl1 - vl2;
                    cov[i, j] = p12;
                    cov[j, i] = p12;
                }
            }
        }
コード例 #20
0
        //IRasterStatistics rasterStatic;
        private void SetRasterSymbol(IRasterLayer rasterLayer)
        {
            //获取选择的序号
            int index = sBC.SelectedIndex;
            ISymbologyStyleClass symbologyStyleClass = axSymbologyControl1.GetStyleClass(esriSymbologyStyleClass.esriStyleClassColorRamps);
            IStyleGalleryItem    mStyleGalleryItem   = symbologyStyleClass.GetItem(index);
            //获取选择的符号
            IColorRamp select = (IColorRamp)mStyleGalleryItem.Item;
            IRasterStretchColorRampRenderer rasterStretchColorRampRenderer = new RasterStretchColorRampRendererClass();
            IRasterRenderer rasterRenderer = rasterStretchColorRampRenderer as IRasterRenderer;

            rasterRenderer.Raster = (rasterLayer).Raster;

            if (checkBox1.Checked == true)
            {
                //修改像元值 线性拉伸
                IRaster2 pRaster2  = rasterLayer.Raster 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 = rasterLayer 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;
                    do
                    {
                        pPixelblock3 = pRasterCursor.PixelBlock as IPixelBlock3;
                        pBlockwidth  = pPixelblock3.Width;
                        pBlockheight = pPixelblock3.Height;

                        //   for (int k = 0; k < pBandCount; k++)

                        //IRasterBandCollection bandCollection;
                        //IRasterLayer irasterLayer = rasterLayer;
                        //IRaster2 raster = rasterLayer.Raster as IRaster2;
                        //IRasterDataset rd = raster.RasterDataset;
                        //bandCollection = rd as IRasterBandCollection;
                        //IEnumRasterBand enumband = bandCollection.Bands;
                        //IRasterBand rasterBand = enumband.Next();
                        //rasterStatic = null;
                        //if (rasterBand != null && rasterBand.Statistics != null)
                        //{
                        //    rasterStatic = rasterBand.Statistics;
                        //}


                        int pixelmax, pixelmin;


                        {
                            pixels   = (System.Array)pPixelblock3.get_PixelData(0);
                            pixelmax = Convert.ToInt32(pixels.GetValue(0, 0));
                            pixelmin = pixelmax;

                            for (int i = 0; i < pBlockwidth; i++)
                            {
                                for (int j = 0; j < pBlockheight; j++)
                                {
                                    pValue = pixels.GetValue(i, j);


                                    {
                                        // pixels.SetValue(Convert.ToByte(Convert.ToInt32(pValue) * strscale), i, j);
                                        if (Convert.ToInt32(pValue) > pixelmax)
                                        {
                                            pixelmax = Convert.ToInt32(pValue);
                                        }
                                        if (Convert.ToInt32(pValue) < pixelmin)
                                        {
                                            pixelmin = Convert.ToInt32(pValue);
                                        }
                                    }
                                }
                            }
                            double strscale = ((double)pixelmax - (double)pixelmin) / 255.0;

                            for (int i = 0; i < pBlockwidth; i++)
                            {
                                for (int j = 0; j < pBlockheight; j++)
                                {
                                    pValue = pixels.GetValue(i, j);


                                    {
                                        pixels.SetValue(Convert.ToByte((Convert.ToInt32(pValue) - pixelmin) / (strscale)), i, j);
                                    }
                                }
                            }


                            pPixelblock3.set_PixelData(0, pixels);
                        }
                        pPnt = pRasterCursor.TopLeft;
                        pRasterEdit.Write(pPnt, (IPixelBlock)pPixelblock3);
                    }while (pRasterCursor.Next());
                    System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterEdit);
                    // MessageBox.Show("done");
                }
            }



            rasterRenderer.Update();
            rasterStretchColorRampRenderer.ColorRamp = select;
            rasterRenderer.Update();
            ((IRasterLayer)rasterLayer).Renderer = rasterRenderer;
        }
コード例 #21
0
        private bool getRGB(IFunctionRasterDataset rs, out double r, out double g, out double b)
        {
            r = 0;
            g = 0;
            b = 0;
            IRasterBandCollection rsbc = (IRasterBandCollection)rs;

            double[]      vlArr  = new double[rsbc.Count];
            int[]         cntArr = new int[vlArr.Length];
            IRaster2      rs2    = (IRaster2)rsUtil.createRaster(rs);
            IRasterCursor rsCur  = rs2.CreateCursorEx(null);

            do
            {
                IPixelBlock pb = rsCur.PixelBlock;
                for (int bd = 0; bd < vlArr.Length; bd++)
                {
                    for (int rw = 0; rw < pb.Height; rw++)
                    {
                        for (int cl = 0; cl < pb.Width; cl++)
                        {
                            object vlObj = pb.GetVal(bd, cl, rw);
                            if (vlObj != null)
                            {
                                vlArr[bd]  += System.Convert.ToDouble(vlObj);
                                cntArr[bd] += 1;
                            }
                        }
                    }
                }
            } while (rsCur.Next());
            int  cntr     = cntArr[0];
            int  cntg     = cntArr[1];
            int  cntb     = cntArr[2];
            int  bcheck   = 0;
            bool cntZerro = false;

            if (cntr > 0)
            {
                r = vlArr[0] / cntr;
            }
            else
            {
                bcheck += 1;
            }
            if (cntg > 0)
            {
                g = vlArr[1] / cntg;
            }
            else
            {
                bcheck += 1;
            }
            if (cntb > 0)
            {
                b = vlArr[2] / cntb;
            }
            if (bcheck == 2)
            {
                cntZerro = true;
            }
            return(cntZerro);
        }
コード例 #22
0
        private void btnUpdate_Click(object sender, EventArgs e)
        {
//Class Setting
            int intClsCnt = lstClasses.CheckedItems.Count;

            string[] arrClsNMs = new string[intClsCnt];

            for (int i = 0; i < intClsCnt; i++)
            {
                arrClsNMs[i] = lstClasses.CheckedItems[i].ToString();
            }


            int[,] arrClsColor = new int[4, intClsCnt];

            IRaster2 pClsRaster = (IRaster2)m_pClsRstLayer.Raster;

            IRasterBandCollection pClsBands = pClsRaster.RasterDataset as IRasterBandCollection;
            IRasterBand           pClsBand  = pClsBands.Item(0);
            ITable pClsTable = pClsBand.AttributeTable;

            ICursor pCursor = pClsTable.Search(null, false);
            IRow    pRow    = pCursor.NextRow();

            string strRed = "Red", strGreen = "Green", strBlue = "Blue", strValue = "Value", strNameFld = "Class_name";

            int intRedIdx   = pClsTable.FindField(strRed);
            int intGreenIdx = pClsTable.FindField(strGreen);
            int intBlueIdx  = pClsTable.FindField(strBlue);
            int intValueIdx = pClsTable.FindField(strValue);
            int intNameIdx  = pClsTable.FindField(strNameFld);

            while (pRow != null)
            {
                for (int i = 0; i < intClsCnt; i++)
                {
                    string strClassName = pRow.get_Value(intNameIdx).ToString();
                    if (arrClsNMs[i] == strClassName)
                    {
                        arrClsColor[0, i] = Convert.ToInt32(pRow.get_Value(intValueIdx));
                        arrClsColor[1, i] = Convert.ToInt32(pRow.get_Value(intRedIdx));
                        arrClsColor[2, i] = Convert.ToInt32(pRow.get_Value(intGreenIdx));
                        arrClsColor[3, i] = Convert.ToInt32(pRow.get_Value(intBlueIdx));
                    }
                }
                pRow = pCursor.NextRow();
            }


            // Get NoDataValues
            IRasterProps pClsrasterProps = (IRasterProps)pClsRaster;

            System.Array pClsNoData = (System.Array)pClsrasterProps.NoDataValue;

            IPnt blocksize = new PntClass();

            blocksize.SetCoords(pClsrasterProps.Width, pClsrasterProps.Height);
            // Create a raster cursor with a system-optimized pixel block size by passing a null.

            IRasterCursor pClsRstCursor = pClsRaster.CreateCursorEx(blocksize);

            IPixelBlock3 pClspBlock3 = (IPixelBlock3)pClsRstCursor.PixelBlock;


            System.Array pClspixels = (System.Array)pClspBlock3.get_PixelData(0);

//Layer Setting

            int intLyrCnt = lstLayers.CheckedItems.Count;

            int[] arrLyrIdx = new int[intLyrCnt];
            for (int i = 0; i < intLyrCnt; i++)
            {
                arrLyrIdx[i] = lstLayers.CheckedIndices[i];
            }

            string strOriRSTpath       = m_pOriRstLayer.FilePath;
            string strExtentFileSource = System.IO.Path.GetDirectoryName(strOriRSTpath);
            string strExtentFileName   = System.IO.Path.GetFileName(strOriRSTpath);

            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IRasterWorkspace  rasterWorkspace  = (IRasterWorkspace)
                                                 workspaceFactory.OpenFromFile(strExtentFileSource, 0);

            //Open a file raster dataset.
            IRasterDataset2 rasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(strExtentFileName);
            IRaster2        pOriRaster2   = (IRaster2)rasterDataset.CreateFullRaster();

            //IRaster2 pOriRaster2 = (IRaster2)m_pOriRstLayer.Raster;
            //Create a raster cursor with a system-optimized pixel block size by passing a null.

            // Get NoDataValues
            m_pRasterProps = (IRasterProps)pOriRaster2;
            System.Array pOriNoData = (System.Array)m_pRasterProps.NoDataValue;


            IPnt Oriblocksize = new PntClass();

            Oriblocksize.SetCoords(m_pRasterProps.Width, m_pRasterProps.Height);
            // Create a raster cursor with a system-optimized pixel block size by passing a null.

            IRasterCursor pOriRstCursor = pOriRaster2.CreateCursorEx(Oriblocksize);
            //IRasterCursor pOriRstCursor = pOriRaster2.CreateCursorEx(null);
            IPixelBlock3 pixelblock3 = (IPixelBlock3)pOriRstCursor.PixelBlock;


            System.Array[] OriPixels = new Array[intLyrCnt];
            //UInt16[][,] intArry = new UInt16[intLyrCnt][,];
            for (int i = 0; i < intLyrCnt; i++)
            {
                //intArry[i] = (UInt16[,])pixelblock3.get_PixelData(arrLyrIdx[i]);
                OriPixels[i] = (System.Array)pixelblock3.get_PixelData(arrLyrIdx[i]);
            }

            //Compare the Arrays and Draw
            int intBlockwidth  = m_pRasterProps.Width;
            int intBlockHeight = m_pRasterProps.Height;

            //List<int[]>[] lstDN = new List<int[]>[intClsCnt];
            List <int>[][] lstDN = new List <int> [intLyrCnt][];
            for (int j = 0; j < intLyrCnt; j++)
            {
                lstDN[j] = new List <int> [intClsCnt];
            }

            for (int j = 0; j < intLyrCnt; j++)
            {
                for (int i = 0; i < intClsCnt; i++)
                {
                    lstDN[j][i] = new List <int>();
                }
            }

            List <int>[][] lstLyrIDs = new List <int> [intLyrCnt][];
            for (int j = 0; j < intLyrCnt; j++)
            {
                lstLyrIDs[j] = new List <int> [intClsCnt];
            }

            for (int j = 0; j < intLyrCnt; j++)
            {
                for (int i = 0; i < intClsCnt; i++)
                {
                    lstLyrIDs[j][i] = new List <int>();
                }
            }

            //Uncertainty Layer Settings
            System.Array[] ProbPixels   = null;
            int            intProLyrCnt = 0;

            List <int>[][] lstProb    = null;
            List <int>[][] lstProbIDs = null;

            string strProbRst = cboProbImage.Text;

            if (strProbRst != "" && chkAddProb.Checked)
            {
                IRasterLayer pProbRstLyr = GetRasterLayer(strProbRst, m_pActiveView);

                string strProbRSTpath = pProbRstLyr.FilePath;
                strExtentFileSource = System.IO.Path.GetDirectoryName(strProbRSTpath);
                strExtentFileName   = System.IO.Path.GetFileName(strProbRSTpath);

                workspaceFactory = new RasterWorkspaceFactoryClass();
                rasterWorkspace  = (IRasterWorkspace)
                                   workspaceFactory.OpenFromFile(strExtentFileSource, 0);

                rasterDataset = (IRasterDataset2)rasterWorkspace.OpenRasterDataset(strExtentFileName);
                IRaster2 pProbRaster2 = (IRaster2)rasterDataset.CreateFullRaster();

                // Get NoDataValues
                IRasterProps pProbrasterProps = (IRasterProps)pProbRaster2;
                System.Array pProbNoData      = (System.Array)pProbrasterProps.NoDataValue;

                IRasterCursor pProbRstCursor  = pProbRaster2.CreateCursorEx(Oriblocksize); // Using same block size
                IPixelBlock3  Probpixelblock3 = (IPixelBlock3)pProbRstCursor.PixelBlock;

                intProLyrCnt = Probpixelblock3.Planes;

                ProbPixels = new Array[intProLyrCnt];

                for (int i = 0; i < intProLyrCnt; i++)
                {
                    ProbPixels[i] = (System.Array)Probpixelblock3.get_PixelData(i);
                }

                lstProb = new List <int> [intProLyrCnt][];

                for (int j = 0; j < intProLyrCnt; j++)
                {
                    lstProb[j] = new List <int> [intClsCnt];
                }

                for (int j = 0; j < intProLyrCnt; j++)
                {
                    for (int i = 0; i < intClsCnt; i++)
                    {
                        lstProb[j][i] = new List <int>();
                    }
                }


                lstProbIDs = new List <int> [intProLyrCnt][];

                for (int j = 0; j < intProLyrCnt; j++)
                {
                    lstProbIDs[j] = new List <int> [intClsCnt];
                }

                for (int j = 0; j < intProLyrCnt; j++)
                {
                    for (int i = 0; i < intClsCnt; i++)
                    {
                        lstProbIDs[j][i] = new List <int>();
                    }
                }
            }


            //Store ID and Values for Brushing and Linking
            m_lstIDsValues = new List <int[]>();

            int intID = 0;

            for (int colIndex = 0; colIndex < intBlockwidth; colIndex++)
            {
                for (int rowIndex = 0; rowIndex < intBlockHeight; rowIndex++)
                {
                    int intClass = Convert.ToInt32(pClspixels.GetValue(colIndex, rowIndex));

                    int[] arrValues = new int[intLyrCnt + intProLyrCnt + 3];
                    if (intClass != Convert.ToInt32(pClsNoData.GetValue(0)))
                    {
                        //int[] arrValues = new int[intLyrCnt + intProLyrCnt + 3];

                        arrValues[0] = colIndex;
                        arrValues[1] = rowIndex;
                        arrValues[2] = intClass;

                        for (int i = 0; i < intClsCnt; i++)
                        {
                            if (arrClsColor[0, i] == intClass)
                            {
                                //Get DNs
                                for (int j = 0; j < intLyrCnt; j++)
                                {
                                    if (colIndex == 0 && rowIndex == 241)
                                    {
                                        j = j;
                                    }
                                    int intValue = Convert.ToInt32(OriPixels[j].GetValue(colIndex, rowIndex));
                                    lstDN[j][i].Add(intValue);
                                    lstLyrIDs[j][i].Add(intID);
                                    arrValues[j + 3] = intValue;
                                }

                                //Get Probs
                                if (strProbRst != "" && chkAddProb.Checked)
                                {
                                    for (int j = 0; j < intProLyrCnt; j++)
                                    {
                                        int intValue = Convert.ToInt32(Convert.ToInt32(ProbPixels[j].GetValue(colIndex, rowIndex)) * 2.55);
                                        lstProb[j][i].Add(intValue);
                                        lstProbIDs[j][i].Add(intID);
                                        arrValues[j + 3 + intLyrCnt] = intValue;
                                    }
                                }
                            }
                        }
                    }
                    m_lstIDsValues.Add(arrValues);
                    intID++;
                    if (m_lstIDsValues.Count != intID)
                    {
                        MessageBox.Show("Diff"); //For deburgging
                    }
                }
            }


            pChart.Series.Clear();
            m_intColumnCnt = 0;
            if (strProbRst != "" && chkAddProb.Checked)
            {
                m_intColumnCnt = intLyrCnt + intProLyrCnt;
            }
            else
            {
                m_intColumnCnt = intLyrCnt;
            }

            m_lstPtsIdContainer = new List <List <int> >();
            m_lstPtSeriesID     = new List <int>();

            for (int i = 0; i < intClsCnt; i++)
            {
                Color FillColor = Color.FromArgb(arrClsColor[1, i], arrClsColor[2, i], arrClsColor[3, i]);

                for (int j = 0; j < m_intColumnCnt; j++)
                {
                    List <int> lstTarget;
                    if (j < intLyrCnt)
                    {
                        lstTarget = lstDN[j][i];
                    }
                    else
                    {
                        lstTarget = lstProb[j - intLyrCnt][i];
                    }

                    List <int> lstIDs;
                    if (j < intLyrCnt)
                    {
                        lstIDs = lstLyrIDs[j][i];
                    }
                    else
                    {
                        lstIDs = lstProbIDs[j - intLyrCnt][i];
                    }

                    List <int> sortedTarget = new List <int>(lstTarget);

                    //to prevent overlapping of Boxplots
                    double dblPlotHalfWidth = 0.05;
                    double dblMin           = (dblPlotHalfWidth * (intClsCnt - 1)) * (-1);
                    double dblRefXvalue     = j + (dblMin + (i * (dblPlotHalfWidth * 2)));

                    //Find Max and Min
                    double[] adblStats     = BoxPlotStats(sortedTarget);
                    bool     blnDrawViolin = true;
                    if (adblStats[0] == adblStats[4])
                    {
                        blnDrawViolin = false;
                    }

                    //Restrict Plot min and max
                    if (adblStats[0] < 0)
                    {
                        adblStats[0] = 0;
                    }
                    if (adblStats[4] > 255)
                    {
                        adblStats[4] = 255;
                    }

                    string strNumbering = i.ToString() + "_" + j.ToString();

                    double dblXmin = dblRefXvalue - (dblPlotHalfWidth / 2);
                    double dblXmax = dblRefXvalue + (dblPlotHalfWidth / 2);

                    if (blnDrawViolin)
                    {
                        //Draw Lines
                        AddLineSeries(pChart, "m_" + strNumbering, Color.Red, 1, ChartDashStyle.Dash, dblRefXvalue - dblPlotHalfWidth, dblRefXvalue + dblPlotHalfWidth, adblStats[2], adblStats[2]);
                        AddLineSeries(pChart, "v_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblRefXvalue, dblRefXvalue, adblStats[1], adblStats[3]);
                        //AddLineSeries(pChart, "v2_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblRefXvalue, dblRefXvalue, adblStats[3], adblStats[4]);
                        AddLineSeries(pChart, "h1_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adblStats[1], adblStats[1]);
                        AddLineSeries(pChart, "h2_" + strNumbering, FillColor, 1, ChartDashStyle.Solid, dblXmin, dblXmax, adblStats[3], adblStats[3]);
                    }
                    else
                    {
                        //Draw Outliers
                        var pMedPt = new System.Windows.Forms.DataVisualization.Charting.Series
                        {
                            Name              = "mpt_" + strNumbering,
                            Color             = Color.Red,
                            BorderColor       = FillColor,
                            IsVisibleInLegend = false,
                            ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                            MarkerStyle       = MarkerStyle.Circle,
                            MarkerSize        = 2,
                        };

                        pChart.Series.Add(pMedPt);
                        pMedPt.Points.AddXY(dblRefXvalue, adblStats[2]);
                    }

                    if (blnDrawViolin)
                    {
                        //Draw Violin Plot
                        var pviolin = new System.Windows.Forms.DataVisualization.Charting.Series
                        {
                            Name              = "vio1_" + strNumbering,
                            Color             = FillColor,
                            BorderColor       = FillColor,
                            IsVisibleInLegend = false,
                            ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Line
                        };
                        pChart.Series.Add(pviolin);

                        double[,] adblViolinStats = ViolinPlot(sortedTarget, 4);

                        int intChartLenth = (adblViolinStats.Length) / 2;


                        for (int k = 0; k < intChartLenth; k++)
                        {
                            if (adblViolinStats[k, 0] > adblStats[0] && adblViolinStats[k, 0] < adblStats[4])
                            {
                                pviolin.Points.AddXY(dblRefXvalue - adblViolinStats[k, 1], adblViolinStats[k, 0]);
                            }
                        }
                        pviolin.Points.AddXY(dblRefXvalue, adblStats[4]);
                        for (int k = intChartLenth - 1; k >= 0; k--)
                        {
                            if (adblViolinStats[k, 0] > adblStats[0] && adblViolinStats[k, 0] < adblStats[4])
                            {
                                pviolin.Points.AddXY(dblRefXvalue + adblViolinStats[k, 1], adblViolinStats[k, 0]);
                            }
                        }
                        pviolin.Points.AddXY(dblRefXvalue, adblStats[0]);
                    }



                    //Draw Outliers
                    var pOutlier = new System.Windows.Forms.DataVisualization.Charting.Series
                    {
                        Name              = "out_" + strNumbering,
                        Color             = FillColor,
                        BorderColor       = FillColor,
                        IsVisibleInLegend = false,
                        ChartType         = System.Windows.Forms.DataVisualization.Charting.SeriesChartType.Point,
                        MarkerStyle       = MarkerStyle.Circle,
                        MarkerSize        = 1,
                    };

                    pChart.Series.Add(pOutlier);
                    m_lstPtSeriesID.Add(pChart.Series.Count - 1); //Add Series ID for brushing and linking

                    List <int> lstPTsIds  = new List <int>();
                    int        intListCnt = lstTarget.Count;
                    for (int k = 0; k < intListCnt; k++)
                    {
                        if (lstTarget[k] < adblStats[0] || lstTarget[k] > adblStats[4])
                        {
                            pOutlier.Points.AddXY(dblRefXvalue, lstTarget[k]);
                            lstPTsIds.Add(lstIDs[k]);
                            //if (m_lstIDsValues[lstIDs[k]][3 + i] != lstTarget[k])
                            //    MessageBox.Show("ddd");
                        }
                    }
                    m_lstPtsIdContainer.Add(lstPTsIds);
                }
            }
            m_intTotalNSeries = pChart.Series.Count;

            //Chart Setting
            pChart.ChartAreas[0].AxisY.Minimum = 0;
            pChart.ChartAreas[0].AxisY.Maximum = 255;

            pChart.ChartAreas[0].AxisY.IsLabelAutoFit = true;
            if (chkAddProb.Checked)
            {
                pChart.ChartAreas[0].AxisY.LabelStyle.Enabled = false;
                pChart.ChartAreas[0].AxisY.Title = "DN and Probability";
            }
            else
            {
                pChart.ChartAreas[0].AxisY.Title = "DN";
            }

            pChart.ChartAreas[0].AxisX.Maximum = m_intColumnCnt - 0.5;
            pChart.ChartAreas[0].AxisX.Minimum = -0.5;

            pChart.ChartAreas[0].AxisX.Title = "Layers";

            pChart.ChartAreas[0].AxisX.IsLabelAutoFit = false;
            pChart.ChartAreas[0].AxisX.CustomLabels.Clear();

            for (int j = 0; j < m_intColumnCnt; j++)
            {
                System.Windows.Forms.DataVisualization.Charting.CustomLabel pcutsomLabel = new System.Windows.Forms.DataVisualization.Charting.CustomLabel();
                pcutsomLabel.FromPosition = j - 0.5;
                pcutsomLabel.ToPosition   = j + 0.5;
                if (j < intLyrCnt)
                {
                    pcutsomLabel.Text = "DN of " + lstLayers.CheckedItems[j].ToString() + "(0-255)";
                }
                else
                {
                    pcutsomLabel.Text = "Prob " + lstClasses.Items[j - intLyrCnt].ToString() + "(0-100)";
                }

                this.pChart.ChartAreas[0].AxisX.CustomLabels.Add(pcutsomLabel);
            }
        }
コード例 #23
0
 /// <summary>
 /// create and initialyze raster cursor
 /// </summary>
 protected void CreateRasterCursor()
 {
     rasterCursor = rasterToRead.CreateCursorEx(null);
     rasterEdit   = rasterToRead as IRasterEdit;
 }
コード例 #24
0
        private void buildModelrst()
        {
            n = 0;
            IRaster2 rsV2 = (IRaster2)InValueRaster;
            IRaster2 rsS2 = (IRaster2)InStrataRaster;
            IRasterBandCollection rsbc   = (IRasterBandCollection)rsV2;
            IRasterCursor         rsSCur = rsS2.CreateCursorEx(null);
            IPixelBlock           pbS    = null;

            double[] vlBandArr = new double[rsbc.Count];
            Dictionary <string, int> stratDic = new Dictionary <string, int>();

            double[] sumClms = null;
            double[,] sumCross = null;
            double[,] cov      = null;
            double[,] scov     = null;
            //System.Array[] pbVArrs = new System.Array[rsbc.Count];
            do
            {
                pbS = rsSCur.PixelBlock;
                IPnt pbSize = new PntClass();
                pbSize.SetCoords(pbS.Width, pbS.Height);
                IPixelBlock pb = InValueRaster.CreatePixelBlock(pbSize);
                IPnt        ptLoc = new PntClass();
                double      mx, my;
                rsS2.PixelToMap(System.Convert.ToInt32(rsSCur.TopLeft.X), System.Convert.ToInt32(rsSCur.TopLeft.Y), out mx, out my);
                int px, py;
                rsV2.MapToPixel(mx, my, out px, out py);
                ptLoc.SetCoords(px, py);
                InValueRaster.Read(ptLoc, pb);
                for (int r = 0; r < pb.Height; r++)
                {
                    for (int c = 0; c < pb.Width; c++)
                    {
                        object sobj = pbS.GetVal(0, c, r);
                        if (sobj == null)
                        {
                            continue;
                        }
                        bool chVl = true;
                        for (int p = 0; p < pb.Planes; p++)
                        {
                            object vlobj = pb.GetVal(p, c, r);
                            if (vlobj == null)
                            {
                                chVl = false;
                                break;
                            }
                            vlBandArr[p] = System.Convert.ToDouble(vlobj);
                        }
                        if (chVl)
                        {
                            string strataValue = sobj.ToString();
                            int    sCnt;
                            if (stratDic.TryGetValue(strataValue, out sCnt))
                            {
                                stratDic[strataValue] = sCnt + 1;
                                int lIndex = lbl.IndexOf(strataValue);
                                sumClms  = sumClmsLst[lIndex];
                                sumCross = sumCrossLst[lIndex];
                            }
                            else
                            {
                                stratDic.Add(strataValue, 1);
                                int lIndex = lbl.Count;
                                lbl.Add(strataValue);
                                sumClms  = new double[VariableFieldNames.Length];
                                sumCross = new double[VariableFieldNames.Length, VariableFieldNames.Length];
                                cov      = new double[VariableFieldNames.Length, VariableFieldNames.Length];
                                scov     = new double[VariableFieldNames.Length, VariableFieldNames.Length];
                                sumClmsLst.Add(sumClms);
                                sumCrossLst.Add(sumCross);
                                covLst.Add(cov);
                                scovLst.Add(scov);
                            }
                            for (int v = 0; v < vlBandArr.Length; v++)
                            {
                                sumClms[v]     += vlBandArr[v];
                                sumCross[v, v] += Math.Pow(vlBandArr[v], 2);
                                for (int j = 0 + v + 1; j < vlBandArr.Length; j++)
                                {
                                    double vl1 = vlBandArr[v];
                                    double vl2 = vlBandArr[j];
                                    double p12 = vl1 * vl2;
                                    sumCross[v, j] += p12;
                                    sumCross[j, v] += p12;
                                }
                            }
                            n++;
                        }
                    }
                }
            } while (rsSCur.Next() == true);
            for (int l = 0; l < lbl.Count; l++)
            {
                string lblVl = lbl[l];
                int    sampN = stratDic[lblVl];
                double r     = sampN / (sampN - 1);
                proportionsLst.Add(System.Convert.ToDouble(sampN) / n);
                sumClms = sumClmsLst[l];
                meansLst.Add((from double d in sumClms select d / sampN).ToArray());
                sumCross = sumCrossLst[l];
                cov      = covLst[l];
                scov     = scovLst[l];
                for (int i = 0; i < sumClms.Length; i++)
                {
                    double var = (sumCross[i, i] / sampN) - (Math.Pow(sumClms[i], 2) / Math.Pow((sampN), 2));
                    cov[i, i]  = var;
                    scov[i, i] = var * r;
                    for (int j = 0 + i + 1; j < sumClms.Length; j++)
                    {
                        double vl1 = (sumCross[j, i] / sampN);
                        double vl2 = (sumClms[j] / sampN) * (sumClms[i] / (sampN));
                        double p12 = vl1 - vl2;
                        cov[i, j]  = p12;
                        cov[j, i]  = p12;
                        scov[i, j] = p12 * r;
                        scov[j, i] = p12 * r;
                    }
                }
            }

            k = lbl.Count;
            makeKMeans();
        }
コード例 #25
0
        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;
        }
コード例 #26
0
        private double[][] coef      = null; // slope coefficients for each band second double array = {intercept,slope,R2}
        private void getRegVals()
        {
            IRaster2 mRs     = (IRaster2)rsUtil.createRaster(rsUtil.clipRasterFunction(referenceRaster, clipGeo, esriRasterClippingType.esriRasterClippingOutside));
            IRaster2 sRs     = (IRaster2)rsUtil.createRaster(rsUtil.clipRasterFunction(transformRaster, clipGeo, esriRasterClippingType.esriRasterClippingOutside));
            IPnt     pntSize = new PntClass();

            pntSize.SetCoords(250, 250);
            IRasterCursor mRsCur = mRs.CreateCursorEx(pntSize);
            IRasterCursor sRsCur = sRs.CreateCursorEx(pntSize);
            IRasterCursor cRsCur = ((IRaster2)rsUtil.createRaster(clipRs)).CreateCursorEx(pntSize);
            IPixelBlock   mPb, sPb, cPb;
            int           bndCnt = minArray.Length;

            //int curCnt = 1;
            do
            {
                mPb = mRsCur.PixelBlock;
                sPb = sRsCur.PixelBlock;
                cPb = cRsCur.PixelBlock;
                for (int r = 0; r < cPb.Height; r += 50)
                {
                    for (int c = 0; c < cPb.Width; c += 50)
                    {
                        for (int p = 0; p < bndCnt; p++)
                        {
                            double minVl  = minArray[p];
                            double maxVl  = maxArray[p];
                            int    bCnt   = 0;
                            double ySumVl = 0;
                            double xSumVl = 0;
                            int    adw    = (cPb.Width - c);
                            int    adh    = (cPb.Height - r);
                            if (adw > 50)
                            {
                                adw = 50;
                            }
                            if (adh > 50)
                            {
                                adh = 50;
                            }
                            for (int br = 0; br < adh; br++)
                            {
                                for (int bc = 0; bc < adw; bc++)
                                {
                                    int    c2    = c + bc;
                                    int    r2    = r + br;
                                    object vlObj = cPb.GetVal(p, c2, r2);
                                    if (vlObj == null)
                                    {
                                        //Console.WriteLine("Clip Not a number");
                                        continue;
                                    }
                                    else
                                    {
                                        double vl = System.Convert.ToDouble(vlObj);
                                        if (vl <= maxVl && vl >= minVl)
                                        {
                                            object mVlObj = mPb.GetVal(p, c2, r2);
                                            object sVlObj = sPb.GetVal(p, c2, r2);
                                            if (mVlObj == null || sVlObj == null)
                                            {
                                                //Console.WriteLine("master or slave is null");
                                                continue;
                                            }
                                            else
                                            {
                                                //Console.WriteLine(mVlObj.ToString() + ", " + sVlObj.ToString());
                                                ySumVl += System.Convert.ToDouble(mVlObj);
                                                xSumVl += System.Convert.ToDouble(sVlObj);
                                                bCnt   += 1;
                                            }
                                        }
                                        else
                                        {
                                            continue;
                                        }
                                    }
                                }
                            }
                            if (bCnt == 0)
                            {
                                continue;
                            }
                            else
                            {
                                double yBlock = ySumVl / bCnt;
                                double xBlock = xSumVl / bCnt;
                                //Console.WriteLine(yBlock.ToString() + ", " + xBlock.ToString());
                                sumYArray[p]      = sumYArray[p] + yBlock;
                                sumXArray[p]      = sumXArray[p] + xBlock;
                                sumXYArray[p]     = sumXYArray[p] + (yBlock * xBlock);
                                sumX2Array[p]     = sumX2Array[p] + (xBlock * xBlock);
                                sumY2Array[p]     = sumY2Array[p] + (yBlock * yBlock);
                                blockCellCount[p] = blockCellCount[p] + 1;
                            }
                        }
                    }
                }
                mRsCur.Next();
                sRsCur.Next();
                //Console.WriteLine(curCnt.ToString());
                //curCnt++;
            } while (cRsCur.Next() == true);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(cRsCur);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(mRsCur);
            System.Runtime.InteropServices.Marshal.ReleaseComObject(sRsCur);
            for (int i = 0; i < bndCnt; i++)
            {
                double n     = System.Convert.ToDouble(blockCellCount[i]);
                double meanX = sumXArray[i] / n;
                double meanY = sumYArray[i] / n;
                //double meanX2 = sumX2Array[i]/n;
                //double meanXY = sumXYArray[i]/n;
                //Console.WriteLine("numb of cells = " + n.ToString());
                //Console.WriteLine(meanX.ToString() + ", " + meanY.ToString() + ", " + meanX2.ToString() + ", " + meanXY.ToString());
                double slope     = (n * sumXYArray[i] - (sumXArray[i] * sumYArray[i])) / (n * sumX2Array[i] - (System.Math.Pow(sumXArray[i], 2)));
                double intercept = meanY - (slope * meanX);
                double r2        = System.Math.Pow((n * sumXYArray[i] - (sumXArray[i] * sumYArray[i])) / (System.Math.Sqrt((n * sumX2Array[i] - (System.Math.Pow(sumXArray[i], 2)))) * System.Math.Sqrt(n * sumY2Array[i] - System.Math.Pow(sumYArray[i], 2))), 2);
                //Console.WriteLine("Intercept and Slope = " + intercept.ToString() + ", " + slope.ToString());
                coef[i] = new double[3] {
                    intercept, slope, r2
                };
            }
        }
コード例 #27
0
        public static void OpenFileRasterDataset(string inFolderName, string inRasterDatasetName, string inFeatureName, string inFieldName, double outCellSize, string outSummaryFile)
        {
            EnableEsriLiscences();

            //Get feature raster from feature shp
            string outTempRasterName = "tempZoneRasterFromESRI.tif";
            string outZoneRater      = inFolderName + "\\" + outTempRasterName;
            int    rasterBlockSize   = 1024;

            RasterizeEsri.Rasterize(inFeatureName, outZoneRater, inFieldName, outCellSize);

            //Open raster file workspace
            IWorkspaceFactory workspaceFactory = new RasterWorkspaceFactoryClass();
            IRasterWorkspace  rasterWorkspace  = (IRasterWorkspace)workspaceFactory.OpenFromFile(inFolderName, 0);

            //Align raster
            string inValueRaster         = inFolderName + "\\" + inRasterDatasetName;
            string inClipFeature         = inFeatureName;
            string outClippedRasterName  = "tempValueRasterFromESRI.tif";
            string outClippedValueRaster = inFolderName + "\\" + outClippedRasterName;

            ClipRasterBoundaryEsri.ClipRaster(inValueRaster, inClipFeature, outClippedValueRaster);

            //Open zone raster dataset
            IRasterDataset  zoneRasterDataset  = rasterWorkspace.OpenRasterDataset(outTempRasterName);
            IRasterDataset2 zoneRasterDataset2 = zoneRasterDataset as IRasterDataset2;
            IRaster2        zoneRs2            = zoneRasterDataset2.CreateFullRaster() as IRaster2;


            //Open value raster dataset
            IRasterDataset  valueRasterDataset  = rasterWorkspace.OpenRasterDataset(outClippedRasterName);
            IRasterDataset2 valueRasterDataset2 = valueRasterDataset as IRasterDataset2;
            IRaster2        valueRs2            = valueRasterDataset2.CreateFullRaster() as IRaster2;

            //Extract bands from the raster
            IRasterBandCollection valueRasterPlanes = valueRasterDataset as IRasterBandCollection;


            //create raster cursor to read block by block
            IPnt blockSize = new PntClass();

            blockSize.SetCoords(rasterBlockSize, rasterBlockSize);

            IRasterCursor valueRasterCursor = valueRs2.CreateCursorEx(blockSize);
            IRasterCursor zoneRasterCursor  = zoneRs2.CreateCursorEx(blockSize);


            if (valueRasterPlanes != null)
            {
                Dictionary <int, StatisticsInfo>[] rasInfoDict = new Dictionary <int, StatisticsInfo> [valueRasterPlanes.Count];
                int zoneRasterBandId = 0;

                for (int b = 0; b < valueRasterPlanes.Count; b++)
                {
                    rasInfoDict[b] = new Dictionary <int, StatisticsInfo>();
                }

                do
                {
                    IPixelBlock3 valueRasterPixelBlock3 = valueRasterCursor.PixelBlock as IPixelBlock3;
                    IPixelBlock3 zoneRasterPixelBlock3  = zoneRasterCursor.PixelBlock as IPixelBlock3;

                    //No Idea how esri cursor fills the raster gap if zone is greater than value, so quick and fix using smallest extent

                    int blockWidth  = valueRasterPixelBlock3.Width < zoneRasterPixelBlock3.Width ? valueRasterPixelBlock3.Width : zoneRasterPixelBlock3.Width;
                    int blockHeight = valueRasterPixelBlock3.Height < zoneRasterPixelBlock3.Height ? valueRasterPixelBlock3.Height : zoneRasterPixelBlock3.Height;


                    //Console.WriteLine(zoneRasterPixelBlock3.Width);
                    //Console.WriteLine(blockWidth);

                    try
                    {
                        System.Array zoneRasterPixels = (System.Array)zoneRasterPixelBlock3.get_PixelData(zoneRasterBandId);
                        for (int b = 0; b < valueRasterPlanes.Count; b++)
                        {
                            //Console.WriteLine(b);
                            //Get pixel array
                            System.Array valueRasterPixels = (System.Array)valueRasterPixelBlock3.get_PixelData(b);

                            for (int i = 0; i < blockWidth; i++)
                            {
                                for (int j = 0; j < blockHeight; j++)
                                {
                                    //Get pixel value
                                    object pixelValueFromValue = null;
                                    object pixelValueFromZone  = null;
                                    try
                                    {
                                        pixelValueFromValue = valueRasterPixels.GetValue(i, j);
                                        pixelValueFromZone  = zoneRasterPixels.GetValue(i, j);
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }


                                    //process each pixel value
                                    try
                                    {
                                        if (rasInfoDict[b].ContainsKey(Convert.ToInt32(pixelValueFromZone)))
                                        {
                                            StatisticsInfo rastStatistics = rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)];
                                            rastStatistics.Count++;
                                            rastStatistics.Sum = rastStatistics.Sum + Convert.ToDouble(pixelValueFromValue);

                                            rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)] = rastStatistics;
                                        }
                                        else
                                        {
                                            rasInfoDict[b][Convert.ToInt32(pixelValueFromZone)] = new StatisticsInfo()
                                            {
                                                Count = 1, Sum = Convert.ToDouble(pixelValueFromValue)
                                            };
                                        }
                                    }
                                    catch (Exception ex)
                                    {
                                        Console.WriteLine(ex.Message);
                                    }

                                    //Console.WriteLine(i +"-"+j);
                                    //Console.WriteLine(pixelValueFromValue + "-" + pixelValueFromZone);
                                }
                            }
                        }
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                } while (zoneRasterCursor.Next() == true);

                //Export results
                StatisticsExport writer = new StatisticsExport(outSummaryFile);
                writer.ExportZonalStatistics(ref rasInfoDict, outCellSize);
            }
            else
            {
                Console.WriteLine("No band available in the Value Raster");
            }
        }