示例#1
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);
        }
        public static float[,] Raster2Mat(IRasterLayer rasterlayer) //将栅格数据转为二元数组
        {
            IRaster      raster       = rasterlayer.Raster;
            IRaster2     raster2      = raster as IRaster2;
            IRasterProps pRasterProps = (IRasterProps)raster;
            IPnt         pntstart     = new DblPntClass();

            pntstart.SetCoords(0, 0);
            IPnt pntend = new DblPntClass();

            pntend.SetCoords(pRasterProps.Width, pRasterProps.Height);
            IPixelBlock3 unionPixelBlock = (IPixelBlock3)raster.CreatePixelBlock(pntend);

            System.Single[,] floatMat;
            try
            {
                raster.Read(pntstart, (IPixelBlock)unionPixelBlock);
                floatMat = (System.Single[, ])unionPixelBlock.get_PixelData(0);
            }
            catch (Exception e) {
                try
                {
                    raster.Read(pntstart, (IPixelBlock)unionPixelBlock);
                    Int16[,] intMat = (Int16[, ])unionPixelBlock.get_PixelData(0);
                    floatMat        = new System.Single[pRasterProps.Width, pRasterProps.Height];
                    Parallel.For(0, pRasterProps.Width, i =>
                    {
                        for (int j = 0; j < pRasterProps.Height; j++)
                        {
                            floatMat[i, j] = Convert.ToSingle(intMat[i, j]);
                        }
                    });
                }
                catch {
                    try
                    {
                        raster.Read(pntstart, (IPixelBlock)unionPixelBlock);
                        Int32[,] intMat = (Int32[, ])unionPixelBlock.get_PixelData(0);
                        floatMat        = new System.Single[pRasterProps.Width, pRasterProps.Height];
                        Parallel.For(0, pRasterProps.Width, i =>
                        {
                            for (int j = 0; j < pRasterProps.Height; j++)
                            {
                                floatMat[i, j] = Convert.ToSingle(intMat[i, j]);
                            }
                        });
                    }
                    catch {
                        raster.Read(pntstart, (IPixelBlock)unionPixelBlock);
                        byte[,] intMat = (byte[, ])unionPixelBlock.get_PixelData(0);
                        floatMat       = new System.Single[pRasterProps.Width, pRasterProps.Height];
                        Parallel.For(0, pRasterProps.Width, i =>
                        {
                            for (int j = 0; j < pRasterProps.Height; j++)
                            {
                                floatMat[i, j] = Convert.ToSingle(intMat[i, j]);
                            }
                        });
                    }
                }
            }

            return(floatMat);
        }
示例#3
0
        public override void OnMouseDown(int Button, int Shift, int X, int Y)
        {
            // TODO:  Add ToolAddStone.OnMouseDown implementation
            if (pTinLayer != null)
            {
                ITin         pTin     = pTinLayer.Dataset;
                ISurface     pSurface = ((ITinAdvanced)pTin).Surface;
                IMapControl2 pMapCtr  = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2;
                //在mapctr操作
                if (pMapCtr != null)
                {
                    IPoint  mapPoint = pMapCtr.ToMapPoint(X, Y);
                    IZAware za       = mapPoint as IZAware;
                    za.ZAware = true;
                    double zVal;
                    zVal = pSurface.GetElevation(mapPoint);
                    if (double.IsNaN(zVal))
                    {
                        MessageBox.Show("获取模型的高度失败!");
                        return;
                    }
                    if (m_listModels.Count == 0)
                    {
                        MessageBox.Show("请先生成模型!");
                        return;
                    }
                    mapPoint.Z = zVal;
                    IFeature pfeature = null;
                    try
                    {
                        //IMultiPatch pMP = new MultiPatchClass();
                        IFeatureClass pFC  = pFeatureLayer.FeatureClass;
                        IFeature      pF   = pFC.CreateFeature();
                        IImport3DFile pI3D = new Import3DFileClass();
                        pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]);
                        IMultiPatch  pMP  = pI3D.Geometry as IMultiPatch;
                        ITransform3D pT3D = pMP as ITransform3D;
                        pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z);
                        pF.Shape = pMP as IGeometry;
                        pfeature = pF as IFeature;
                        pF.Store();
                        if (pMapCtr != null)
                        {
                            pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                        }
                    }
                    catch (SystemException e)
                    {
                        if (e.Message == "The spatial index grid size is invalid.")
                        {
                            IFeatureClassLoad pFCL = pFeatureLayer.FeatureClass as IFeatureClassLoad;
                            pFCL.LoadOnlyMode = true;
                            pfeature.Store();
                            pFCL.LoadOnlyMode = false;
                        }
                        else
                        {
                            MessageBox.Show(e.Message);
                        }
                    }



                    //IMultiPatch pMP = new MultiPatchClass();
                    //for (int i = 0; i < 5; i++)
                    //{
                    //    IFeature pF = pFC.CreateFeature();
                    //    IImport3DFile pI3D = new Import3DFileClass();
                    //    pI3D.CreateFromFile(@"C:\Users\Administrator\Desktop\sampleAnalysis\1002.3ds");
                    //    IMultiPatch pMP = pI3D.Geometry as IMultiPatch;
                    //   // ITransform3D pT3D = pMP as ITransform3D;
                    //    pF.Shape = pMP as IGeometry;
                    //    ITransform3D pT3D = pF.Shape as ITransform3D;
                    //    pT3D.Move3D(5293 + 1600, -20427 , 800 + i*400);
                    //    // pF.Shape = pI3D.Geometry;
                }
            }
            if (pRasterLayer != null)
            {
                //ITin pTin = pTinLayer.Dataset;
                //ISurface pSurface = ((ITinAdvanced)pTin).Surface;
                IMapControl2 pMapCtr = (((IToolbarControl)m_hookHelper.Hook).Buddy) as IMapControl2;
                //在mapctr操作
                if (pMapCtr != null)
                {
                    IPoint mapPoint = pMapCtr.ToMapPoint(X, Y);

                    //添加手工编辑窗口
                    FrmManualSetModelPara pManualSetPara = null;
                    if (m_pModel == null)
                    {
                        Pt2d ptCurrent = new Pt2d();
                        ptCurrent.X    = mapPoint.X;
                        ptCurrent.Y    = mapPoint.Y;
                        pManualSetPara = new FrmManualSetModelPara(ptCurrent, "Rock");
                    }
                    else
                    {
                        m_pModel.x     = mapPoint.X;
                        m_pModel.y     = mapPoint.Y;
                        pManualSetPara = new FrmManualSetModelPara(m_pModel);
                    }

                    if (pManualSetPara.ShowDialog() == DialogResult.OK)
                    {
                        if (m_pModel == null)
                        {
                            m_pModel = new Model();
                        }

                        //bool bFlag = m_pModel.compareModelPara(pManualSetPara.m_pModel);
                        //if (!bFlag)//模型参数已经被修改,需要重新生成新的模型文件
                        //{
                        //    m_pModel.copyFromModel(pManualSetPara.m_pModel);

                        //    //获得当前文件路径下的石头模型文件,并随机获得石块模型
                        //    String szAppPathName = GetParentPathofExe() + @"Resource\RockModel";
                        //    String[] szFileList = Directory.GetFiles(szAppPathName);
                        //    if (szFileList.Length > 0)
                        //    {
                        //        Random r = new Random(TerrainGen.Chaos_GetRandomSeed());
                        //        int nRandomPos = r.Next(szFileList.Length);
                        //        String szModelOutputFilename = szFileList[nRandomPos];
                        //        m_listModels.Add(szModelOutputFilename);
                        //    }
                        //}

                        m_pModel.copyFromModel(pManualSetPara.m_pModel);

                        //获得当前文件路径下的石头模型文件,并随机获得石块模型
                        String   szAppPathName = ClsGlobal.GetParentPathofExe() + @"Resource\RockModel";
                        String[] szFileList    = Directory.GetFiles(szAppPathName);
                        if (szFileList.Length > 0)
                        {
                            Random r                     = new Random(TerrainGen.Chaos_GetRandomSeed());
                            int    nRandomPos            = r.Next(szFileList.Length);
                            String szModelOutputFilename = szFileList[nRandomPos];
                            m_listModels.Add(szModelOutputFilename);
                        }

                        //保存当前添加的模型参数
                        Model pTmpModel = new Model();
                        pTmpModel.copyFromModel(pManualSetPara.m_pModel);
                        m_manualAddModels.Add(pTmpModel);
                    }
                    else
                    {
                        return;
                    }

                    IZAware za = mapPoint as IZAware;
                    za.ZAware = true;
                    double   zVal;
                    IRaster2 pRaster2 = pRasterLayer.Raster as IRaster2;
                    int      col, row;
                    pRaster2.MapToPixel(mapPoint.X, mapPoint.Y, out col, out row);
                    zVal = Convert.ToDouble(pRaster2.GetPixelValue(0, col, row));
                    if (double.IsNaN(zVal))
                    {
                        MessageBox.Show("获取模型的高度失败!");
                        return;
                    }
                    if (m_listModels.Count == 0)
                    {
                        MessageBox.Show("请先生成模型!");
                        return;
                    }
                    mapPoint.Z = zVal;
                    try
                    {
                        //IMultiPatch pMP = new MultiPatchClass();
                        IFeatureClass pFC  = pFeatureLayer.FeatureClass;
                        IFeature      pF   = pFC.CreateFeature();
                        IImport3DFile pI3D = new Import3DFileClass();
                        pI3D.CreateFromFile(m_listModels[m_listModels.Count - 1]);
                        IMultiPatch  pMP  = pI3D.Geometry as IMultiPatch;
                        ITransform3D pT3D = pMP as ITransform3D;
                        pT3D.Move3D(mapPoint.X, mapPoint.Y, mapPoint.Z);
                        IRasterProps pRasterProps = pRasterLayer.Raster as IRasterProps;
                        double       xmax         = pRasterProps.Extent.XMax;
                        double       xmin         = pRasterProps.Extent.XMin;
                        double       ymax         = pRasterProps.Extent.YMax;
                        double       ymin         = pRasterProps.Extent.YMin;
                        //生成地形的地理范围
                        double dbGeoRangeX = xmax - xmin;
                        double dbGeoRangeY = ymax - ymin;

                        double dbModelRangeX = pMP.Envelope.Width;
                        double dbModelRangeY = pMP.Envelope.Height;
                        double dbModelRangeZ = pMP.Envelope.ZMax - pMP.Envelope.ZMin;

                        //根据地形大小改变石块大小
                        //double dbRandomSize = Math.Min(dbGeoRangeX, dbGeoRangeY) * (0.03 ); //[0.03 0.06]
                        //double dbScale = dbRandomSize / Math.Max(dbModelRangeX, dbModelRangeY);
                        double dbScale = m_pModel.dbSize / Math.Max(dbModelRangeX, Math.Max(dbModelRangeY, dbModelRangeZ));
                        pT3D.Scale3D(mapPoint, dbScale, dbScale, dbScale);


                        pF.Shape = pMP as IGeometry;
                        pF.Store();
                        if (pMapCtr != null)
                        {
                            pMapCtr.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                        }
                    }
                    catch (SystemException e)
                    {
                        MessageBox.Show(e.Message);
                    }
                }
            }
        }
示例#4
0
        //拉伸到灰度图像
        private bool stretchToGrayImage(IRaster pSrcRaster, string szOutputFilename, double dbMinThreshold = 0.02, double dbMaxThreshold = 0.98)
        {
            try
            {
                if (pSrcRaster == null || szOutputFilename == null)
                {
                    return(false);
                }

                //深拷贝
                IClone       pSrcClone    = pSrcRaster as IClone;
                IClone       pDstClone    = pSrcClone.Clone();
                IRaster      pDstRaster   = pDstClone as IRaster;
                IRaster2     pDstRaster2  = pDstRaster as IRaster2;
                IRasterProps pRasterProps = pDstRaster as IRasterProps;

                //原始统计信息
                bool        bFlag       = false;
                IRasterBand pRasterBand = (pDstRaster as IRasterBandCollection).Item(0);
                pRasterBand.HasStatistics(out bFlag);
                if (!bFlag)
                {
                    pRasterBand.ComputeStatsAndHist();
                }

                //得到原始栅格影像的最大最小值和步长
                double dbSrcMaxValue     = pRasterBand.Statistics.Maximum;
                double dbSrcMinValue     = pRasterBand.Statistics.Minimum;
                double dbSrcStep         = (dbSrcMaxValue - dbSrcMinValue) / 256;
                double dbStretchMaxValue = pRasterBand.Statistics.Maximum;
                double dbStretchMinValue = pRasterBand.Statistics.Minimum;

                #region 灰度映射,利用重分类来做

                //第一次重分类
                IReclassOp   reclassOp   = new RasterReclassOpClass();
                INumberRemap numberRemap = new NumberRemapClass();
                for (int i = 0; i < 256; i++)
                {
                    numberRemap.MapRange(dbSrcMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i);
                }
                IRaster      pRasterTemp      = reclassOp.ReclassByRemap((IGeoDataset)(pDstRaster2.RasterDataset), (IRemap)numberRemap, true) as IRaster;
                IRaster2     pRasterTemp2     = pRasterTemp as IRaster2;
                IRasterProps pRasterTempProps = pRasterTemp as IRasterProps;

                //得到属性表
                IRasterDatasetEdit3 pRasterDatasetEdit3 = pRasterTemp2.RasterDataset as IRasterDatasetEdit3;
                pRasterDatasetEdit3.ComputeStatisticsHistogram(1, 1, null, true);
                IRasterBand       rasterBand       = (pRasterTempProps as IRasterBandCollection).Item(0);
                IRasterHistogram  rasterHistogram  = rasterBand.Histogram;
                IRasterStatistics rasterStatistics = rasterBand.Statistics;

                double[] pHistogramCount = (double[])rasterHistogram.Counts;

                int nCurrentCount = 0;
                int nIndex        = 0;
                int nPixelCount   = 0;//pRasterProps.Width * pRasterProps.Height;
                //double dSum = 0.0;
                for (int i = 0; i < 256; i++)
                {
                    nPixelCount += (int)pHistogramCount[i];
                }
                //得到拉伸的最大最小值
                while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMinThreshold)
                {
                    nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]);
                }
                dbStretchMinValue = nIndex * dbSrcStep + dbSrcMinValue;

                while (Convert.ToDouble(nCurrentCount) / nPixelCount < dbMaxThreshold)
                {
                    nCurrentCount += Convert.ToInt32(pHistogramCount[nIndex++]);
                }
                dbStretchMaxValue = nIndex * dbSrcStep + dbSrcMinValue;

                dbSrcStep = (dbStretchMaxValue - dbStretchMinValue) / 256;
                #endregion

                #region 拉伸
                INumberRemap numberRemapForStretch = new NumberRemapClass();

                numberRemapForStretch.MapRange(dbSrcMinValue, dbStretchMinValue + dbSrcStep, 0);
                for (int i = 1; i < 255; i++)
                {
                    numberRemapForStretch.MapRange(dbStretchMinValue + i * dbSrcStep, dbStretchMinValue + (i + 1) * dbSrcStep, i);
                }
                numberRemapForStretch.MapRange(dbStretchMinValue + 255 * dbSrcStep, dbSrcMaxValue, 255);

                IRaster      pRasterStretch      = reclassOp.ReclassByRemap((IGeoDataset)((pDstRaster as IRaster2).RasterDataset), (IRemap)numberRemapForStretch, true) as IRaster;
                IRasterProps pRasterStretchProps = pRasterStretch as IRasterProps;

                #region 注释代码
                ////拉伸
                //IPixelBlock3 pixelBlock3 = null;
                //IRasterCursor rasterCursor = (pDstRaster as IRaster2).CreateCursorEx(null);//null时为128*128

                //do
                //{
                //    pixelBlock3 = rasterCursor.PixelBlock as IPixelBlock3;
                //    int nWidth = pixelBlock3.Width;
                //    int nHeight = pixelBlock3.Height;

                //    System.Array pixels = (System.Array)pixelBlock3.get_PixelData(0);
                //    for (int m = 0; m < nWidth; m++)
                //    {
                //        for (int n = 0; n < nHeight; n++)
                //        {
                //            double dbSrcValue = Convert.ToDouble(pixels.GetValue(m, n));
                //            if (double.IsNaN(dbSrcValue) || dbSrcValue == dbNoDataValue)
                //                continue;

                //            if (dbSrcValue >= dbStretchMaxValue)
                //                pixels.SetValue(255, m, n);
                //            else if (dbSrcValue <= dbStretchMinValue)
                //                pixels.SetValue(0, m, n);
                //            else
                //            {
                //                byte dbDstValue = Convert.ToByte((dbSrcValue - dbStretchMinValue) / (dbStretchMaxValue - dbStretchMinValue) * 255);
                //                pixels.SetValue(dbDstValue, m, n);
                //            }
                //        }
                //    }
                //    pixelBlock3.set_PixelData(0, (System.Array)pixels);

                //    //修改数据
                //    pRasterEdit.Write(rasterCursor.TopLeft, pixelBlock3 as IPixelBlock);
                //    pRasterEdit.Refresh();
                //} while (rasterCursor.Next() == true);
                #endregion

                #endregion

                #region 存储数据
                IWorkspaceFactory pWorkspaceFactory = new RasterWorkspaceFactoryClass();
                IWorkspace        inmemWor          = pWorkspaceFactory.OpenFromFile(System.IO.Path.GetDirectoryName(szOutputFilename), 0);
                pRasterStretchProps.PixelType = rstPixelType.PT_UCHAR;
                ISaveAs2 pSaveAs = pRasterStretchProps as ISaveAs2;
                if (pSaveAs == null)
                {
                    return(false);
                }

                IRasterStorageDef pRSDef   = new RasterStorageDefClass();
                IRasterDataset    pDataset = pSaveAs.SaveAsRasterDataset(System.IO.Path.GetFileName(szOutputFilename), inmemWor, "TIFF", pRSDef);
                (pDataset as IRasterDataset3).Refresh();
                //IRasterEdit pRasterEdit = pDstRaster as IRasterEdit;

                IRasterEdit pRasterTempEdit = pRasterTemp as IRasterEdit;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterTempEdit);
                IRasterEdit pRasterStretchEdit = pRasterStretch as IRasterEdit;
                System.Runtime.InteropServices.Marshal.ReleaseComObject(pRasterStretchEdit);
                #endregion

                return(true);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                return(false);
            }
        }
        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");
            }
        }
示例#6
0
        private void BtnOK_Click(object sender, EventArgs e)
        {
            int i = 0; int j = 0;

            if (string.IsNullOrEmpty(this.ComboBoxInLayer.Text))
            {
                MessageBox.Show("请选择需要二值化的图层!", "栅格二值化", MessageBoxButtons.OK, MessageBoxIcon.Information);
                return;
            }

            int intLyrCount = frm.mainMapControl.LayerCount;

            for (i = 0; i <= intLyrCount - 1; i++)
            {
                if ((frm.mainMapControl.Map.get_Layer(i).Name == this.ComboBoxInLayer.Text.Trim()))
                {
                    IRasterLayer   pRasterLayer  = frm.mainMapControl.get_Layer(i) as IRasterLayer;
                    IRaster2       raster        = pRasterLayer.Raster as IRaster2;
                    IRasterDataset rasterDataset = raster.RasterDataset;

                    IRasterBandCollection dirBandCollection = (IRasterBandCollection)rasterDataset;
                    IRasterBand           dirRasterBand     = dirBandCollection.Item(0);
                    IRawPixels            dirRawPixels      = (IRawPixels)dirRasterBand;

                    IPnt         pixelBlockOrigin = null;
                    IPnt         dirBlockSize     = new DblPntClass();
                    IRasterProps dirProps         = (IRasterProps)dirRawPixels;
                    int          dirColumns       = dirProps.Width;       //列数
                    int          dirRows          = dirProps.Height;      //行数

                    IPixelBlock3 dirPixelBlock = (IPixelBlock3)dirRawPixels.CreatePixelBlock(dirBlockSize);
                    dirRawPixels.Read(pixelBlockOrigin, (IPixelBlock)dirPixelBlock);

                    System.Array array;
                    array = (System.Array)dirPixelBlock.get_PixelDataByRef(0);//获取栅格数组

                    int min;
                    if (textBox1.Text == "")
                    {
                        min = 20;
                    }
                    else
                    {
                        min = Convert.ToInt32(textBox1.Text);
                    }
                    /////获得栅格数据像元值
                    double[,] b = new double[dirRows, dirColumns];
                    double value;
                    string strExcute = null;
                    for (int row = 0; row < dirRows; row++)
                    {
                        for (int col = 0; col < dirColumns; col++)
                        {
                            b[row, col] = Convert.ToSingle(array.GetValue(col, row));
                            /////阈值判断
                            if (b[row, col] > min)
                            {
                                value = 1;
                            }
                            else
                            {
                                value = 0;
                            }
                            strExcute = Convert.ToString(value);
                        }
                    }
                    IGeoDataset   tempGeodata1  = (IGeoDataset)pRster;
                    IMapAlgebraOp pMapAlgebraOp = new RasterMapAlgebraOpClass();

                    //设置栅格运算空间
                    IRasterAnalysisEnvironment pRasterAnalysisEnvironment = (IRasterAnalysisEnvironment)pMapAlgebraOp;
                    IWorkspaceFactory          pWorkspaceFactory          = new RasterWorkspaceFactoryClass();

                    string outPath      = null;
                    string outLayerName = null;
                    outPath = this.TxtBox.Text.Trim();
                    j       = this.TxtBox.Text.Trim().LastIndexOf("\\");

                    outPath      = this.TxtBox.Text.Substring(0, j);
                    outLayerName = this.TxtBox.Text.Substring(j + 1);
                    string DataSetName = this.TxtBox.Text.Substring(j + 1);

                    //设置输出空间
                    IWorkspace pWorkspace = pWorkspaceFactory.OpenFromFile(outPath, 0);
                    pRasterAnalysisEnvironment.OutWorkspace = pWorkspace;
                    IGeoDataset  outGetDataset = pMapAlgebraOp.Execute(strExcute);
                    IRasterLayer pCreatRalyr   = new RasterLayerClass();
                    pCreatRalyr.CreateFromRaster((IRaster)outGetDataset);

                    pCreatRalyr.Name = outLayerName;
                    frm.mainMapControl.AddLayer(pCreatRalyr);
                    break;
                }
            }
        }
示例#7
0
 public override void OnMouseDown(int Button, int Shift, int X, int Y)
 {
     if (Button == 1)
     {
         List <ILayer> layers = EngineAPI.GetLayers(this.m_hookHelper.FocusMap, "{6CA416B1-E160-11D2-9F4E-00C04F6BC78E}", null);
         if (layers.Count == 0)
         {
             IdentifyManager.instance.FrmIdentify.Close();
             IdentifyManager.instance.FrmIdentify      = null;
             EnviVars.instance.MapControl.CurrentTool  = null;
             EnviVars.instance.MapControl.MousePointer = esriControlsMousePointer.esriPointerDefault;
         }
         else
         {
             foreach (ILayer current in layers)
             {
                 IIdentify identify = current as IIdentify;
                 IPoint    point    = this.m_hookHelper.ActiveView.ScreenDisplay.DisplayTransformation.ToMapPoint(X, Y);
                 IArray    array    = identify.Identify(point);
                 if (array != null && array.Count != 0)
                 {
                     IdentifyManager.instance.FrmIdentify.treeList1.ClearNodes();
                     IIdentifyObj identifyObj = array.get_Element(0) as IIdentifyObj;
                     identifyObj.Flash(this.m_hookHelper.ActiveView.ScreenDisplay);
                     TreeListNode treeListNode = IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[]
                     {
                         identifyObj.Layer.Name
                     }, 0, identifyObj);
                     DataColumn column    = new DataColumn("字段", typeof(string));
                     DataColumn column2   = new DataColumn("值", typeof(string));
                     DataTable  dataTable = new DataTable();
                     dataTable.Columns.Add(column);
                     dataTable.Columns.Add(column2);
                     if (current is IFeatureLayer)
                     {
                         IFeature     feature       = (identifyObj as IRowIdentifyObject).Row as IFeature;
                         TreeListNode treeListNode2 = IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[]
                         {
                             feature.OID.ToString()
                         }, treeListNode);
                         int num = feature.Fields.FindField((current as IFeatureLayer).FeatureClass.ShapeFieldName);
                         for (int i = 0; i < feature.Fields.FieldCount; i++)
                         {
                             if (num != i)
                             {
                                 DataRow dataRow = dataTable.NewRow();
                                 dataRow["字段"] = feature.Fields.get_Field(i).AliasName;
                                 dataRow["值"]  = feature.get_Value(i).ToString();
                                 dataTable.Rows.Add(dataRow);
                             }
                         }
                         treeListNode2.Tag = dataTable;
                     }
                     else if (current is IRasterLayer)
                     {
                         IRasterLayer rasterLayer = current as IRasterLayer;
                         IRaster2     raster      = rasterLayer.Raster as IRaster2;
                         int          num2        = raster.ToPixelRow(point.Y);
                         int          num3        = raster.ToPixelColumn(point.X);
                         double       num4        = CommonAPI.ConvertToDouble(raster.GetPixelValue(0, num3, num2));
                         this.AddRow(dataTable, "像素值", num4);
                         this.AddRow(dataTable, "行号", num2);
                         this.AddRow(dataTable, "列号", num3);
                         IRasterIdentifyObj rasterIdentifyObj = array.get_Element(0) as IRasterIdentifyObj;
                         if (rasterLayer.BandCount != 1)
                         {
                             Regex           regex           = new Regex("\\d{2,3}");
                             MatchCollection matchCollection = regex.Matches(rasterIdentifyObj.MapTip);
                             if (matchCollection.Count == 3)
                             {
                                 this.AddRow(dataTable, "R", matchCollection[0].Value);
                                 this.AddRow(dataTable, "G", matchCollection[1].Value);
                                 this.AddRow(dataTable, "B", matchCollection[2].Value);
                             }
                         }
                         IdentifyManager.instance.FrmIdentify.treeList1.AppendNode(new object[]
                         {
                             rasterIdentifyObj.Name
                         }, treeListNode, dataTable);
                     }
                     IdentifyManager.instance.FrmIdentify.UpdateStatusText(string.Format("X:{0:0.000 },Y:{1:0.000}", point.X, point.Y));
                     IdentifyManager.instance.FrmIdentify.treeList1.ExpandAll();
                     if (treeListNode.Nodes.Count > 0)
                     {
                         IdentifyManager.instance.FrmIdentify.treeList1.FocusedNode = treeListNode.Nodes[0];
                     }
                     IdentifyManager.instance.FrmIdentify.Show();
                     break;
                 }
                 IdentifyManager.instance.FrmIdentify.Close();
                 IdentifyManager.instance.FrmIdentify = null;
             }
         }
     }
 }
示例#8
0
        void DemBreakStart()
        {
            //读入dem,manning
            DemPath = txbDemIpute.Text;
            GISdataManager.readRaster(DemPath, ref demRaster);
            //
            //IRasterProps rasterprops = demRaster.Raster as IRasterProps;
            //object nodataValue1 = rasterprops.NoDataValue;
            //float[] mit = nodataValue1 as float[];
            //nodataValue = mit[0];
            //
            dem         = GISdataManager.Raster2Mat(demRaster);
            ManningPath = txbManingInput.Text;
            GISdataManager.readRaster(ManningPath, ref manningRaster);
            manNing = GISdataManager.Raster2Mat(manningRaster);

            //获取栅格分辨率
            IRasterInfo rasterinfo = (demRaster.Raster as IRawBlocks).RasterInfo;

            flowLength  = Convert.ToInt32(rasterinfo.CellSize.X);
            flowLength2 = flowLength * 1.141f;

            //判断DEM与曼宁系数栅格是否一致!
            if (demRaster.ColumnCount != manningRaster.ColumnCount || demRaster.RowCount != manningRaster.RowCount)
            {
                MessageBox.Show("请在检查DEM与曼宁糙率栅格行列是否对应后重新输入!");
                return;
            }
            rowCount = demRaster.RowCount;
            colCount = demRaster.ColumnCount;

            //初始化中间参数
            slope     = new float[rowCount, colCount];
            flowDir   = new byte[rowCount, colCount];
            waterDeep = new float[rowCount, colCount];
            tempDeep  = new float[rowCount, colCount];
            flowVel   = new float[rowCount, colCount];
            arrived   = new bool[rowCount, colCount];
            for (int i = 0; i < rowCount; i++)
            {
                for (int j = 0; j < colCount; j++)
                {
                    slope[i, j]     = 0f;
                    flowDir[i, j]   = 0;
                    waterDeep[i, j] = 0f;
                    tempDeep[i, j]  = 0f;
                    flowVel[i, j]   = 0f;
                    arrived[i, j]   = false;
                }
            }
            DBpointPath = txbDBpoint.Text;
            GISdataManager.readSHP(DBpointPath, ref DBpointshp);
            IFeatureClass featureClass = DBpointshp.FeatureClass;
            int           count        = featureClass.FeatureCount(new QueryFilter());

            for (int i = 0; i < count; i++)
            {
                IFeature  feature = featureClass.GetFeature(i);
                IGeometry Geo = feature.Shape;
                IPoint    point = Geo as IPoint;
                double    x, y;
                x = point.X;
                y = point.Y;
                //获取出水点在Mit中的位置
                IRaster  raster  = demRaster.Raster;
                IRaster2 raster2 = raster as IRaster2;
                DPcolIndex = raster2.ToPixelColumn(x);
                DProwIndex = raster2.ToPixelRow(y);
                dbPointList.Add(new int[2] {
                    DProwIndex, DPcolIndex
                });
                arrived[DProwIndex, DPcolIndex] = true;
                waterGrids.Add(new int[2] {
                    DProwIndex, DPcolIndex
                });
            }
            //读取流量过程线表格
            HydroPath       = txbHydroghraph.Text;
            HydroRecordList = TxTReader.txt2List3(HydroPath, dbPointList.Count);
        }
示例#9
0
        //逐点算法
        public bool ImageReprojectionRange(IRaster pSrcRaster, out IRaster pDstRaster, ExOriPara exori,
                                           double dbFocus, double fx, double fy, int nImgWidth, int nImgHeight, int nGeoRange)
        {
            pDstRaster = null;

            Pt2i ptSubImgLeftTop = new Pt2i();

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

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

            IRaster2 pRaster2 = pSrcRaster as IRaster2;

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

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

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

            double dbCurCameraZ = 0;

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

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


            Point2D ptLeftTop = new Point2D(0, 0);

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

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

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

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

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

            //Pt2d pt;
            Matrix matA, matB;

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

            matR = new Matrix(3, 3);

            //Matrix matX;

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

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

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

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

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

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

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

            //double dthreshold = 0.01;

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



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

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

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

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

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

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

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

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

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

            return(true);
        }
示例#10
0
        private void btnCaculate_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog m_FolderBrowserDialog = new FolderBrowserDialog();
            string m_DataPathName = "";
            string m_DataName     = "";
            string parentPath     = "";

            if (m_DataPathName != "" || m_DataName != "" || parentPath != "")
            {
                m_DataPathName = m_FolderBrowserDialog.SelectedPath;
                DirectoryInfo m_DirectoryInfo = new DirectoryInfo(m_DataPathName);
                m_DataName = m_DirectoryInfo.Name;
                DirectoryInfo pDirectoryInfo = m_DirectoryInfo.Parent;
                parentPath = pDirectoryInfo.FullName;
            }
            textBox3.Text = m_DataPathName;

            stw.Start();

            string jieguo2;

            for (int i = 0; i < frm.mainMapControl.LayerCount; i++)
            {
                string inputname = frm.mainMapControl.get_Layer(i).Name;
                int    location2 = inputname.LastIndexOf('.');
                string sss2      = inputname;
                jieguo2 = sss2.Substring(0, location2);////"."后文件名称
                IRasterLayer   pRasterLayer     = frm.mainMapControl.get_Layer(i) as IRasterLayer;
                IRaster2       raster           = pRasterLayer.Raster as IRaster2;
                IRasterDataset rasterDataset    = raster.RasterDataset;
                IPnt           pixelBlockOrigin = new DblPntClass();
                pixelBlockOrigin.SetCoords(0, 0);
                IRasterBandCollection dirBandCollection = (IRasterBandCollection)rasterDataset;
                IRasterBand           dirRasterBand     = dirBandCollection.Item(0);
                IRawPixels            dirRawPixels      = (IRawPixels)dirRasterBand;
                IRasterProps          dirProps          = (IRasterProps)dirRawPixels;

                int    dirColumns   = dirProps.Width;                 //列数
                int    dirRows      = dirProps.Height;                //行数
                double cellSizeX    = dirProps.MeanCellSize().X;      //得到x方向栅格大小
                double cellSizeY    = dirProps.MeanCellSize().Y;      //得到y方向栅格大小
                IPnt   dirBlockSize = new DblPntClass();
                dirBlockSize.X = dirColumns;
                dirBlockSize.Y = dirRows;
                IPixelBlock3 dirPixelBlock = (IPixelBlock3)dirRawPixels.CreatePixelBlock(dirBlockSize);
                dirRawPixels.Read(pixelBlockOrigin, (IPixelBlock)dirPixelBlock);
                System.Array array = (System.Array)dirPixelBlock.get_PixelDataByRef(0);

                string ss = "";
                double[,] b = new double[dirRows, dirColumns];
                for (int row = 0; row < dirRows; row++)
                {
                    for (int col = 0; col < dirColumns; col++)
                    {
                        b[row, col] = Convert.ToSingle(array.GetValue(col, row));/////得到按行排列的值,注意这个为GetValue(col, row))
                    }
                }

                if (textBox3.Text == "")
                {
                    MessageBox.Show("文件保存名不能为空");
                }

                String savename = textBox3.Text + "\\" + jieguo2 + ".txt";
                for (int c = 0; c < maxnum; c++)
                {
                    double sum, mean, a;//修改程序2012年7月27日
                    a    = 0;
                    sum  = 0;
                    mean = 0;

                    if (cbBDirection.Text == "左边--->右边")
                    {
                        for (int row = 0; row < dirRows; row++)            ////窗口大小与图像行列数关系
                        {
                            for (int col = 0; col < dirColumns - k; col++) ////窗口大小与图像行列数关系
                            {
                                sum += Math.Pow((b[row, col] - b[row, col + k]), 2);
                                a    = a + 1;
                            }
                        }
                    }
                    if (cbBDirection.Text == "上边--->下边")
                    {
                        for (int row = 0; row < dirRows - k; row++)    ////窗口大小与图像行列数关系
                        {
                            for (int col = 0; col < dirColumns; col++) ////窗口大小与图像行列数关系
                            {
                                sum = sum + Math.Pow((b[row, col] - b[row + k, col]), 2);
                                a   = a + 1;
                            }
                        }
                    }
                    if (cbBDirection.Text == "左下--->右上")
                    {
                        for (int row = 0; row < dirRows - k; row++)        ////窗口大小与图像行列数关系
                        {
                            for (int col = 0; col < dirColumns - k; col++) ////窗口大小与图像行列数关系
                            {
                                sum += Math.Pow((b[row, col] - b[row + k, col + k]), 2);
                                a    = a + 1;
                            }
                        }
                    }
                    if (cbBDirection.Text == "左上--->右下")
                    {
                        for (int row = 0; row < dirRows - k; row++)        ////窗口大小与图像行列数关系
                        {
                            for (int col = 0; col < dirColumns - k; col++) ////窗口大小与图像行列数关系
                            {
                                sum += Math.Pow((b[row, col + k] - b[row + k, col]), 2);
                                a    = a + 1;
                            }
                        }
                    }
                    mean = sum / (2 * a);
                    ss  += mean + " " + a + " " + k + "\r\n";

                    String       Strsavefile = savename;
                    StreamWriter sw          = new StreamWriter(Strsavefile);
                    sw.WriteLine(ss);
                    sw.Close();
                    k = k + 1;
                }
            }
            stw.Stop();
            MessageBox.Show("程序共运行时间:" + stw.Elapsed.Minutes.ToString() + "分钟" + stw.Elapsed.Seconds.ToString() + "秒");
        }
示例#11
0
        private void button1_Click(object sender, EventArgs e)
        {
            string jieguo2;

            for (int i = 0; i < frm.mainMapControl.LayerCount; i++)
            {
                string inputname = frm.mainMapControl.get_Layer(i).Name;
                int    location2 = inputname.LastIndexOf('.');
                string sss2      = inputname;
                jieguo2 = sss2.Substring(0, location2);////"."后文件名称
                IRasterLayer pRasterLayer = frm.mainMapControl.get_Layer(i) as IRasterLayer;

                IRaster2       raster = pRasterLayer.Raster as IRaster2;
                System.Array   array;
                IRasterDataset rasterDataset = raster.RasterDataset;
                IPoint         pPointOrign   = new PointClass();
                pPointOrign.X = 0;
                pPointOrign.Y = 0;
                IPnt pixelBlockOrigin = null;
                pixelBlockOrigin = new DblPntClass();
                pixelBlockOrigin.SetCoords(pPointOrign.X, pPointOrign.Y);
                IRasterBandCollection dirBandCollection = (IRasterBandCollection)rasterDataset;
                IRasterBand           dirRasterBand     = dirBandCollection.Item(0);
                IRawPixels            dirRawPixels      = (IRawPixels)dirRasterBand;
                IRasterProps          dirProps          = (IRasterProps)dirRawPixels;
                int    dirColumns   = dirProps.Width;             //列数
                int    dirRows      = dirProps.Height;            //行数
                double cellSizeX    = dirProps.MeanCellSize().X;  //得到x方向栅格大小
                double cellSizeY    = dirProps.MeanCellSize().Y;  ////得到y方向栅格大小
                IPnt   dirBlockSize = new DblPntClass();
                dirBlockSize.X = dirColumns;
                dirBlockSize.Y = dirRows;
                IPixelBlock3 dirPixelBlock = (IPixelBlock3)dirRawPixels.CreatePixelBlock(dirBlockSize);
                dirRawPixels.Read(pixelBlockOrigin, (IPixelBlock)dirPixelBlock);
                array = (System.Array)dirPixelBlock.get_PixelDataByRef(0);

                string ss = "";
                double[,] b = new double[dirRows, dirColumns];
                for (int row = 0; row < dirRows; row++)
                {
                    for (int col = 0; col < dirColumns; col++)
                    {
                        b[row, col] = Convert.ToSingle(array.GetValue(col, row));
                    }
                }
                int minnum, maxnum, chuangkou;

                if (textBox1.Text == "")
                {
                    minnum = 2;
                }
                else
                {
                    minnum = Convert.ToInt32(textBox1.Text);
                }

                if (textBox2.Text == "")
                {
                    maxnum = 1;
                }
                else
                {
                    maxnum = Convert.ToInt32(textBox2.Text);
                }
                chuangkou = minnum;


                if (textBox3.Text == "")
                {
                    MessageBox.Show("文件保存名不能为空");
                }

                String savename = textBox3.Text + "\\" + jieguo2 + ".txt";

                for (int c = 0; c < maxnum; c++)
                {
                    double result, sum, mean, fangcha, ste, a;////////修改程序2011年11月15日
                    a       = 0;
                    ste     = 0;
                    sum     = 0;
                    fangcha = 0;

                    for (int row = 0; row < dirRows - chuangkou + 1; row++)        ////窗口大小与图像行列数关系
                    {
                        for (int col = 0; col < dirColumns - chuangkou + 1; col++) ////窗口大小与图像行列数关系
                        {
                            for (int k = row; k < row + chuangkou; k++)            ////窗口大小与图像栅格和的关系
                            {
                                for (int l = col; l < col + chuangkou; l++)
                                {
                                    sum = sum + b[k, l];
                                }
                            }
                            mean = sum / (chuangkou * chuangkou);

                            for (int m = row; m < row + chuangkou; m++)
                            {
                                for (int n = col; n < col + chuangkou; n++)
                                {
                                    fangcha = fangcha + (b[m, n] - mean) * (b[m, n] - mean);
                                }
                            }

                            result = System.Math.Sqrt(fangcha / (chuangkou * chuangkou));

                            fangcha = 0;
                            sum     = 0;
                            ste     = ste + result;
                            a       = a + 1;
                        }
                    }
                    //ss += ste / a + "    " + chuangkou + "\r\n";
                    ss += ste / a + "    " + a + "    " + ste + "\r\n";
                    //string varString = Convert.ToString(chuangkou);

                    //////////////////////////////////////////////////////////////////////////
                    ///////////////改写内容
                    String Strsavefile;
                    Strsavefile = savename;
                    ////////FileStream fs = new FileStream(Strsavefile);

                    StreamWriter sw = new StreamWriter(Strsavefile);
                    sw.WriteLine(ss);
                    sw.Close();
                    //////////////////////////////////////////////////////////////////////////
                    chuangkou = chuangkou + 1;
                    //MessageBox.Show(varString,"OK");
                    //this.Hide();
                }
            }
            MessageBox.Show("OK");
            this.Hide();//////点击ok后计算窗口消失
        }
        protected override void OnClick()
        {
            string straboPath = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableSTRABO_HOME, EnvironmentVariableTarget.User);
            string tessPath   = Environment.GetEnvironmentVariable(ArcStrabo2Extension.EnvironmentVariableTESS_DATA, EnvironmentVariableTarget.User);


            if (ArcStrabo2Extension.PathSet == false)
            {
                if (String.IsNullOrEmpty(straboPath) == true)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHome);
                    return;
                }
                if (String.IsNullOrEmpty(tessPath) == true)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoTess_Data);
                    return;
                }

                bool Initialize_straboPath_Correct = ArcStrabo2Extension.initialize_straboPath_directories(straboPath);

                if (Initialize_straboPath_Correct == false)
                {
                    MessageBox.Show(ArcStrabo2Extension.ErrorMsgNoStraboHomeWritePermission);
                    return;
                }

                ArcStrabo2Extension.PathSet = true;
            }
            //
            //  TODO: Sample code showing how to access button host
            //
            ArcMap.Application.CurrentTool = null;
            ComboBoxLayerSelector layerNameCombo = ComboBoxLayerSelector.GetLayerNameComboBox();

            RasterLayer rasterlayer = new RasterLayer();

            rasterlayer = ((RasterLayer)layerNameCombo.GetSelectedLayer());
            //raster.Raster
            //RasterLayer raster2 = new RasterLayer();
            //raster2.CreateFromRaster(raster.Raster);
            //IMap map = ArcMap.Document.FocusMap;
            //map.AddLayer((ILayer)raster2);
            //MessageBox.Show(layerNameCombo.selected_layer_name + " " + raster2.RowCount + " " + raster2.ColumnCount + " " + raster2.BandCount);
            ColorSegmentationWorker cs = new ColorSegmentationWorker();

            try
            {
                IRaster2 iraster2   = rasterlayer.Raster as IRaster2;
                string[] bitmap_fns = cs.Apply(System.IO.Path.GetDirectoryName(iraster2.RasterDataset.CompleteName) + "\\", ArcStrabo2Extension.Text_Result_Path + "\\", System.IO.Path.GetFileName(iraster2.RasterDataset.CompleteName));
                IMap     map        = ArcMap.Document.FocusMap;
                foreach (string path in bitmap_fns)
                {
                    //RasterDataset rds = new RasterDataset();
                    //rds.OpenFromFile(path);
                    RasterLayer rasterlayer2 = new RasterLayer();
                    rasterlayer2.CreateFromFilePath(path);
                    map.AddLayer(rasterlayer2);
                }
            }
            catch (Exception e)
            {
                Console.WriteLine(e.ToString());
            }
        }
示例#13
0
        private static Dictionary <string, double[][]> getDictionaryValues(ESRI.ArcGIS.Geodatabase.IFeatureClass pointFtr, ESRI.ArcGIS.Geodatabase.IField[] fldsToSummarize, IFunctionRasterDataset strataRaster, geoDatabaseUtility geoUtil, rasterUtil rsUtil)
        {
            IRaster2 rs2 = (IRaster2)rsUtil.createRaster(strataRaster);

            int[] ptfldIndex = new int[fldsToSummarize.Length];
            for (int i = 0; i < ptfldIndex.Length; i++)
            {
                ptfldIndex[i] = pointFtr.FindField(fldsToSummarize[i].Name);
            }
            Dictionary <string, double[][]> outDic = new Dictionary <string, double[][]>();
            IFeatureCursor sCur = pointFtr.Search(null, true);
            IFeature       sFtr = sCur.NextFeature();

            while (sFtr != null)
            {
                IGeometry geo = sFtr.Shape;
                IPoint    pnt = (IPoint)geo;
                int       clm, rw;
                rs2.MapToPixel(pnt.X, pnt.Y, out clm, out rw);
                object strataVlObj = rs2.GetPixelValue(0, clm, rw);
                if (strataVlObj != null)
                {
                    string     strataVl = strataVlObj.ToString();
                    double[][] vlArr;
                    if (outDic.TryGetValue(strataVl, out vlArr))
                    {
                        for (int i = 0; i < ptfldIndex.Length; i++)
                        {
                            object vlObj = sFtr.get_Value(ptfldIndex[i]);
                            if (vlObj != null)
                            {
                                double vl = System.Convert.ToDouble(vlObj);
                                vlArr[i][0] += vl;
                                vlArr[i][1] += (vl * vl);
                                vlArr[i][2] += 1;
                            }
                        }
                    }
                    else
                    {
                        vlArr = new double[fldsToSummarize.Length][];
                        for (int i = 0; i < ptfldIndex.Length; i++)
                        {
                            double[] vlSumArr = new double[3];
                            object   vlObj    = sFtr.get_Value(ptfldIndex[i]);
                            if (vlObj != null && !System.Convert.IsDBNull(vlObj))
                            {
                                double vl = System.Convert.ToDouble(vlObj);
                                vlSumArr[0] = vl;
                                vlSumArr[1] = (vl * vl);
                                vlSumArr[2] = 1;
                            }
                            vlArr[i] = vlSumArr;
                        }
                        outDic[strataVl] = vlArr;
                    }
                }
                sFtr = sCur.NextFeature();
            }
            System.Runtime.InteropServices.Marshal.ReleaseComObject(sCur);
            return(outDic);
        }
 public static object FindValue(IRaster2 raster, int band, IPoint point)
 {
     int col, row;
     raster.MapToPixel(point.X, point.Y, out col, out row);
     return raster.GetPixelValue(band, col, row);
 }
示例#15
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);
            }
        }
示例#16
0
        public double[,] getSubDem(IRaster pSrcRaster, Pt3d ptCenter, double nGeoRange, ref Pt2i ptImageTopLeft)
        {
            //IRaster pDstRaster = null;
            if (pSrcRaster == null)
            {
                return(null);
            }

            IRasterProps pProps   = pSrcRaster as IRasterProps;
            IEnvelope    pEnvelop = pProps.Extent;

            Pt2d[] ptRange = new Pt2d[4];
            for (int i = 0; i < 4; i++)
            {
                ptRange[i] = new Pt2d();
            }

            ptRange[0].X = ptCenter.X - nGeoRange;  //lefttop
            ptRange[0].X = Math.Max(ptRange[0].X, pEnvelop.UpperLeft.X);
            ptRange[0].Y = ptCenter.Y + nGeoRange;
            ptRange[0].Y = Math.Min(ptRange[0].Y, pEnvelop.UpperLeft.Y);

            ptRange[1].X = ptCenter.X + nGeoRange;  //righttop
            ptRange[1].Y = ptCenter.Y + nGeoRange;
            ptRange[1].X = Math.Min(ptRange[1].X, pEnvelop.UpperRight.X);
            ptRange[1].Y = Math.Min(ptRange[1].Y, pEnvelop.UpperRight.Y);

            ptRange[2].X = ptCenter.X - nGeoRange;  //leftbottom
            ptRange[2].Y = ptCenter.Y - nGeoRange;
            ptRange[2].X = Math.Max(ptRange[2].X, pEnvelop.LowerLeft.X);
            ptRange[2].Y = Math.Max(ptRange[2].Y, pEnvelop.LowerLeft.Y);

            ptRange[3].X = ptCenter.X + nGeoRange;  //rightbottom
            ptRange[3].Y = ptCenter.Y - nGeoRange;
            ptRange[3].X = Math.Min(ptRange[3].X, pEnvelop.LowerRight.X);
            ptRange[3].Y = Math.Max(ptRange[3].Y, pEnvelop.LowerRight.Y);

            Pt2i[] ptImageRange = new Pt2i[4];
            for (int i = 0; i < 4; i++)
            {
                ptImageRange[i] = new Pt2i();
            }

            IRaster2 pRaster2 = pSrcRaster as IRaster2;

            ptImageRange[0].X = pRaster2.ToPixelColumn(ptRange[0].X);
            ptImageRange[0].Y = pRaster2.ToPixelRow(ptRange[0].Y);
            ptImageRange[1].X = pRaster2.ToPixelColumn(ptRange[1].X);
            ptImageRange[1].Y = pRaster2.ToPixelRow(ptRange[1].Y);
            ptImageRange[2].X = pRaster2.ToPixelColumn(ptRange[2].X);
            ptImageRange[2].Y = pRaster2.ToPixelRow(ptRange[2].Y);
            ptImageRange[3].X = pRaster2.ToPixelColumn(ptRange[3].X);
            ptImageRange[3].Y = pRaster2.ToPixelRow(ptRange[3].Y);

            ptImageTopLeft.X = Math.Min(Math.Min(Math.Min(ptImageRange[0].X, ptImageRange[1].X), ptImageRange[2].X), ptImageRange[3].X);
            ptImageTopLeft.Y = Math.Min(Math.Min(Math.Min(ptImageRange[0].Y, ptImageRange[1].Y), ptImageRange[2].Y), ptImageRange[3].Y);

            int[] nSize = new int[2];
            nSize[0] = Math.Max(Math.Max(Math.Max(ptImageRange[0].X, ptImageRange[1].X), ptImageRange[2].X), ptImageRange[3].X) - ptImageTopLeft.X;
            nSize[1] = Math.Max(Math.Max(Math.Max(ptImageRange[0].Y, ptImageRange[1].Y), ptImageRange[2].Y), ptImageRange[3].Y) - ptImageTopLeft.Y;

            double[,] dbData = new double[nSize[0], nSize[1]];
            Point2D ptLeftTop = new Point2D();

            ptLeftTop.X = ptImageTopLeft.X;
            ptLeftTop.Y = ptImageTopLeft.Y;
            //double[,] dbData = new double[pProps.Width,pProps.Height];
            //Point2D ptLeftTop = new Point2D();
            //ptImageTopLeft.X = pRaster2.ToPixelColumn(pEnvelop.UpperLeft.X); //(int)pEnvelop.UpperLeft.X;
            //ptImageTopLeft.Y = pRaster2.ToPixelRow(pEnvelop.UpperLeft.Y); //(int)pEnvelop.UpperLeft.X;//(int)pEnvelop.UpperLeft.Y;
            //ptLeftTop.X = ptImageTopLeft.X;// pEnvelop.UpperLeft.X;
            //ptLeftTop.Y = ptImageTopLeft.Y;// pEnvelop.UpperLeft.Y;
            readBlockDataToFile(ptLeftTop, ref dbData, pSrcRaster);

            return(dbData);
        }
        //绘制直方图的函数,传入参数为波段索引、最大像元数、绘图对象
        private void DrawHisto(int index, int maxst, Graphics g)
        {
            //实现绘制直方图的函数
            //获取指定index的波段
            IRaster2              raster2              = m_rstlayer.Raster as IRaster2;
            IRasterDataset        rasterDataset        = raster2.RasterDataset;
            IRasterBandCollection rasterBandCollection = rasterDataset as IRasterBandCollection;
            IRasterBand           rasterBand           = rasterBandCollection.Item(index);
            //计算该波段的histogram(tips:类似于计算statistics)
            bool hasStat = false;

            rasterBand.HasStatistics(out hasStat);
            if (null == rasterBand.Statistics || !hasStat || rasterBand.Histogram == null)
            {
                rasterBand.ComputeStatsAndHist();
            }
            double[] histo;
            if (null != rasterBand.Statistics || rasterBand.Histogram != null)
            {
                //获取每个象元值的统计个数
                histo = rasterBand.Histogram.Counts as double[];
                //计算最大像元数
                int maxCount = (int)histo[0];
                for (int j = 0; j < histo.Length; j++)
                {
                    if (maxCount < histo[j])
                    {
                        maxCount = (int)histo[j];
                    }
                }

                //画笔颜色设置
                Pen   pen   = new Pen(Brushes.Black, 1); //实例化细度为1的黑色画笔
                Color color = new Color();
                switch (index)
                {
                case 0:
                    color = Color.Red;
                    break;

                case 1:
                    color = Color.Orange;
                    break;

                case 2:
                    color = Color.Yellow;
                    break;

                case 3:
                    color = Color.Green;
                    break;

                case 4:
                    color = Color.Blue;
                    break;

                case 5:
                    color = Color.Purple;
                    break;

                case 6:
                    color = Color.Peru;
                    break;
                }
                pen.Color = color;
                //绘制并标识最大灰度值
                int maxLine = 40 + (1 - (int)(maxCount / maxst)) * 200;//计算最大值所在的y坐标
                g.DrawLine(pen, 50, maxLine, 300, maxLine);
                g.DrawString(maxCount.ToString(), new Font("New Timer", 8), Brushes.Black, new PointF(9, 34));

                //绘制直方图
                double xTemp = 0;
                double yTemp = 0;

                for (int i = 0; i < histo.Length; i++)
                {
                    xTemp = i * 1.0 / histo.Length * (300 - 50); //计算横向位置,0~250
                    yTemp = histo[i] / maxst * 200.0;            //计算纵向长度并绘制,0~200
                    g.DrawLine(pen, 50 + (int)xTemp, 240, 50 + (int)xTemp, 240 - (int)yTemp);
                }
                //释放资源
                pen.Dispose();
            }
        }
示例#18
0
        //计算某个像素点是否可见,只适用于东北天坐标,即Z轴向上
        private bool getPixelIsCoverd(IRaster pRaster, double[,] dbSubDemData, Pt2i ptSubImgLeftTop,
                                      int posx, int posy, out Point2D ptGeoCovered, ExOriPara exOriPara, double[] dbCoef, double dbFocus, double fx, double fy, double dbInitialStep)
        {
            ptGeoCovered = null;
            if (pRaster == null)
            {
                return(false);
            }

            bool bFlag = false;

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

            double dbNoDataValue = getNoDataValue(pProps.NoDataValue);// Convert.ToDouble(((object[])pProps.NoDataValue)[0]);

            double xPix, yPix;

            xPix = posx - fx; // nImgWidth / 2;       //行列号转摄影测量像平面坐标
            yPix = fy - posy; //nImgHeight / 2

            double dVecX   = dbCoef[0] * xPix + dbCoef[1] * yPix - dbCoef[2] * dbFocus;
            double dVecY   = dbCoef[3] * xPix + dbCoef[4] * yPix - dbCoef[5] * dbFocus;
            double dVecZ   = dbCoef[6] * xPix + dbCoef[7] * yPix - dbCoef[8] * dbFocus;
            double dVecDis = Math.Sqrt(dVecX * dVecX + dVecY * dVecY + dVecZ * dVecZ);
            double dRatioX = dVecX / dVecDis;
            double dRatioY = dVecY / dVecDis;
            double dRatioZ = dVecZ / dVecDis;

            //迭代步长
            double dDemZ      = 0.0;
            double dXCumulate = exOriPara.pos.X;
            double dYCumulate = exOriPara.pos.Y;
            double dZCumulate = exOriPara.pos.Z;
            double dStep      = dbInitialStep;

            int nDemW = 0;
            int nDemH = 0;

            #region
            int nIter = 0;
            while (true)
            {
                nIter++;

                #region 如果迭代次数太多,则取最后一次的结果,避免无限循环
                if (nIter > 10000)
                {
                    if (true == GetGeoZ(pRaster, dbSubDemData, ptSubImgLeftTop, dXCumulate, dYCumulate, ref dDemZ))
                    {
                        ptGeoCovered   = new Point2D();
                        ptGeoCovered.X = dXCumulate;
                        ptGeoCovered.Y = dYCumulate;
                        bFlag          = true;
                    }

                    break;
                }
                #endregion

                #region 由于存在“回头探测”的现象,因此要判断是否已经过头,此判断仅适用于Z值朝上(东北天坐标)的DEM
                if ((dXCumulate - exOriPara.pos.X) / dRatioX < 0)
                {
                    break;
                }
                #endregion

                //正常迭代
                dXCumulate = dXCumulate + dStep * dRatioX;
                dYCumulate = dYCumulate + dStep * dRatioY;
                dZCumulate = dZCumulate + dStep * dRatioZ;

                IRaster2 pRaster2 = pRaster as IRaster2;
                nDemW = pRaster2.ToPixelColumn(dXCumulate); //dXCumulate - pDem.m_PtOrigin.X) / dXRdem;
                nDemH = pRaster2.ToPixelRow(dYCumulate);    // (dYCumulate - pDem.m_PtOrigin.Y) / dYRdem;
                if (nDemH < 0 || nDemH >= nDemHeight || nDemW < 0 || nDemW >= nDemWidth)
                {
                    break;
                }

                if (false == GetGeoZ(pRaster, dbSubDemData, ptSubImgLeftTop, dXCumulate, dYCumulate, ref dDemZ))
                {
                    continue;
                }

                if (Math.Abs(dDemZ - dbNoDataValue) <= 10e-10)
                {
                    //“回头探测”时遇到无效值,认为可以终止
                    if (dStep < 0)
                    {
                        break;
                    }
                    else
                    {
                        continue;
                    }
                }

                //if (Math.Abs(dDemZ - dbNoDataValue) < 1)
                //{
                //    continue;
                //}

                //double dZMinus = dDemZ - dZCumulate;
                double dZMinus = dZCumulate - dDemZ;

                //表示已经到了地形点上
                if (Math.Abs(dZMinus) < 0.01)
                {
                    if (true == GetGeoZ(pRaster, dbSubDemData, ptSubImgLeftTop, dXCumulate, dYCumulate, ref dDemZ))
                    {
                        ptGeoCovered   = new Point2D();
                        ptGeoCovered.X = dXCumulate;
                        ptGeoCovered.Y = dYCumulate;
                        bFlag          = true;
                    }

                    break;
                }

                //表示已经穿过DEM,需要进行“回头探测”
                if (dZMinus < 0)
                {
                    dStep = -Math.Abs(0.1 * dZMinus);
                }
                else
                {
                    dStep = Math.Abs(dStep);
                }

                //if (Math.Abs(dZMinus) < 0.5)
                //{
                //    dStep = 0.3;
                //}

                //if (Math.Abs(dZMinus) < 0.2)
                //{
                //    dStep = 0.1;
                //}
                //if (Math.Abs(dZMinus) < 0.1)
                //{
                //    dStep = 0.03;
                //}

                //if (Math.Abs(dZMinus) < 0.05)
                //{
                //    if (false == GetGeoZ(pRaster, dbSubDemData, ptSubImgLeftTop, dXCumulate, dYCumulate, ref dDemZ))
                //    {
                //        break;
                //    }

                //    ptGeoCovered = new Point2D();
                //    ptGeoCovered.X = dXCumulate;
                //    ptGeoCovered.Y = dYCumulate;
                //    bFlag = true;

                //    break;
                //}
            }
            #endregion

            return(bFlag);
        }
示例#19
0
 /// <summary>
 /// this constructor takes input raster and writes it to the respective variable of the parent class
 /// </summary>
 /// <param name="rasterToRead"></param>
 public ReadPixelData(IRaster2 rasterToRead)
 {
     this.rasterToRead = rasterToRead;
     CreateRasterCursor();
     ProcessPixels();
 }
示例#20
0
        public bool ImageReprojectionRange(IRaster pSrcRaster, out Point2D[,] ptResult, ExOriPara exori, InOriPara pInOri, int nGeoRange)
        {
            double dbFocus    = pInOri.df;
            double fx         = pInOri.dfx;
            double fy         = pInOri.dfy;
            int    nImgWidth  = pInOri.nW;
            int    nImgHeight = pInOri.nH;

            ptResult = null;

            Pt2i ptSubImgLeftTop = new Pt2i();

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

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

            IRaster2 pRaster2 = pSrcRaster as IRaster2;

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

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

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

            double dbCurCameraZ = 0;

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

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


            Point2D ptLeftTop = new Point2D(0, 0);

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

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

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

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

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

            //Pt2d pt;
            Matrix matA, matB;

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

            matR = new Matrix(3, 3);

            //Matrix matX;

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

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

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

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

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

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

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

            //double dthreshold = 0.01;


            //for (int i = 0; i < nDemWidth; i++)
            //{
            //    for (int j = 0; j < nDemHeight; j++)
            //    {
            //        dbData[i, j] = bt;
            //    }
            //}


            ptResult = new Point2D[2, nImgWidth];

            int nSearchStep = 50;

            for (int j = 0; j < nImgWidth + nSearchStep - 1; j += nSearchStep)
            {
                if (j >= nImgWidth)
                {
                    j = nImgWidth - 1;
                }

                //最下面的点
                Point2D ptBottom = null, ptTop = null;
                Point2D ptLastTime = null;
                if (getPixelIsCoverd(pSrcRaster, dbSubDemData, ptSubImgLeftTop, j, nImgHeight - 1, out ptBottom, exori, dbCoef, dbFocus, fx, fy, dbInitialStep))
                {
                    int nposy = 0;
                    int nStep = nImgHeight - 1;
                    while (nStep > 1 && nposy >= 0 && nposy < nImgHeight)
                    {
                        nStep /= 2;

                        if (getPixelIsCoverd(pSrcRaster, dbSubDemData, ptSubImgLeftTop, j, nposy, out ptTop, exori, dbCoef, dbFocus, fx, fy, dbInitialStep))
                        {
                            if (ptLastTime == null)
                            {
                                ptLastTime = new Point2D();
                            }

                            ptLastTime.X = ptTop.X;
                            ptLastTime.Y = ptTop.Y;
                            nposy       -= nStep;
                        }
                        else
                        {
                            nposy += nStep;
                        }
                    }
                }

                //加入链表
                ptResult[0, j] = ptLastTime;
                ptResult[1, j] = ptBottom;
            }

            //write block data
            //if (!WriteToRaster(pDstRaster, dbData, ptLeftTop))
            //    return false;
            //if (!writeBlockDataToFile(ptLeftTop, dbData, nSize, pDstRaster))
            //    return false;

            return(true);
        }
示例#21
0
        //private bool RasterClip(IRasterLayer pRasterLayer, IPolygon clipGeo, string FileName)
        //{
        //    try
        //    {
        //        IRaster pRaster = pRasterLayer.Raster;
        //        IRasterProps pProps = pRaster as IRasterProps;
        //        object cellSizeProvider = pProps.MeanCellSize().X;
        //        IGeoDataset pInputDataset = pRaster as IGeoDataset;
        //        IExtractionOp pExtractionOp = new RasterExtractionOpClass();
        //        IRasterAnalysisEnvironment pRasterAnaEnvir = pExtractionOp as IRasterAnalysisEnvironment;
        //        pRasterAnaEnvir.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue, ref cellSizeProvider);
        //        object extentProvider = clipGeo.Envelope;
        //        object snapRasterData = Type.Missing;
        //        pRasterAnaEnvir.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue, ref extentProvider, ref snapRasterData);
        //        IGeoDataset pOutputDataset = pExtractionOp.Polygon(pInputDataset, clipGeo as IPolygon, true);//裁切操作
        //        IRaster clipRaster; //裁切后得到的IRaster
        //        if (pOutputDataset is IRasterLayer)
        //        {
        //            IRasterLayer rasterLayer = pOutputDataset as IRasterLayer;
        //            clipRaster = rasterLayer.Raster;
        //        }
        //        else if (pOutputDataset is IRasterDataset)
        //        {
        //            IRasterDataset rasterDataset = pOutputDataset as IRasterDataset;
        //            clipRaster = rasterDataset.CreateDefaultRaster();
        //        }
        //        else if (pOutputDataset is IRaster)
        //        {
        //            clipRaster = pOutputDataset as IRaster;
        //        }
        //        else
        //        {
        //            return false;
        //        }

        //        //保存裁切后得到的clipRaster
        //        //如果直接保存为img影像文件
        //        IWorkspaceFactory pWKSF = new RasterWorkspaceFactoryClass();
        //        IWorkspace pWorkspace = pWKSF.OpenFromFile(System.IO.Path.GetDirectoryName(FileName), 0);
        //        ISaveAs pSaveAs = clipRaster as ISaveAs;
        //        IDataset pDataset = pSaveAs.SaveAs(System.IO.Path.GetFileName(FileName) + ".tif", pWorkspace, "TIFF");//以TIF格式保存
        //        System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset);
        //        return true;
        //        //MessageBox.Show("成功!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //    }
        //    catch (Exception exp)
        //    {
        //        MessageBox.Show(exp.Message, "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
        //        return false;
        //    }
        //}

        //从RASTER中根据SHP截取子图
        //private bool GetRasterSubset(IRasterLayer pRasterLayer, ILayer pLayerRegion, string szOutputRasterFilename,out IPoint ptLeftTopOffset)
        //{
        //    ptLeftTopOffset = null;
        //    if (pLayerRegion ==null)//裁切区域为空时,使用整个栅格
        //    {

        //    }
        //    else
        //    {
        //        //得到范围
        //    }


        //    return true;
        //}

        //private bool GetRasterSubset(IRasterLayer pRasterLayer, string szShpFilename, string szOutputRasterFilename, out IPoint ptLeftTopOffset)
        //{
        //    ptLeftTopOffset = null;
        //    if (string.IsNullOrEmpty(szOutputRasterFilename) || pRasterLayer==null || string.IsNullOrEmpty(szShpFilename))
        //        return false;

        //    try
        //    {
        //        //打开源文件
        //        IRasterLayer rasterlayer = pRasterLayer;

        //        //获得SHP文件
        //        string szShpPath = System.IO.Path.GetDirectoryName(szShpFilename);
        //        string szShpFile = System.IO.Path.GetFileName(szShpFilename);
        //        IWorkspaceFactory PWorkSpaceFactory = new ShapefileWorkspaceFactory();
        //        IFeatureWorkspace pFeatureWorkSpace = (IFeatureWorkspace)PWorkSpaceFactory.OpenFromFile(szShpPath, 0);
        //        IFeatureLayer pFeatureLayer = new FeatureLayerClass();
        //        pFeatureLayer.FeatureClass = pFeatureWorkSpace.OpenFeatureClass(szShpFile);
        //        esriGeometryType pType = pFeatureLayer.FeatureClass.ShapeType;
        //        if (pType != esriGeometryType.esriGeometryPolygon)
        //        {
        //            MessageBox.Show("矢量文件必须是多边形图层!请重新输入!");
        //            return false;
        //        }

        //        //截取子图
        //        IFeatureCursor pFeatureCursor = pFeatureLayer.FeatureClass.Search(null, false);
        //        IFeature pFeature = pFeatureCursor.NextFeature();
        //        IGeometry pGeometry = pFeature.Shape;
        //        IPolygon pPolygon = pGeometry as IPolygon;

        //        IRasterProps pRasterProps = rasterlayer.Raster as IRasterProps;
        //        IPoint pRasterLeftTop = pRasterProps.Extent.UpperLeft;
        //        IPoint pShpLeftTop = pPolygon.Envelope.UpperLeft;

        //        ptLeftTopOffset = new PointClass();
        //        ptLeftTopOffset.X = Math.Abs(pShpLeftTop.X - pRasterLeftTop.X);
        //        ptLeftTopOffset.Y = Math.Abs(pRasterLeftTop.Y - pShpLeftTop.Y);

        //        //保存到文件
        //        bool result = RasterClip(rasterlayer, pPolygon, szOutputRasterFilename);
        //        return result;
        //    }
        //    catch (System.Exception ex)
        //    {
        //        MessageBox.Show(ex.Message);
        //        return false;
        //    }
        //}
        #endregion
        private void btnOK_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtRightImage.Text))
            {
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            m_pRasterLayerRight = ClsGDBDataCommon.GetLayerFromName(m_pMapCtrl.Map, txtRightImage.Text) as IRasterLayer;
            //待配准影像完整名
            string strRegisterFile = "";
            //基准图层完整名
            string strBaseFile = "";

            if (m_pRasterLayerRight == null || m_pRasterLayerLeft == null)
            {
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            if (m_pRasterLayerRight.Raster == null || m_pRasterLayerLeft.Raster == null)
            {
                this.DialogResult = DialogResult.Cancel;
                return;
            }

            IDataLayer   pDatalayer = m_pRasterLayerLeft as IDataLayer;
            IDatasetName pDname     = (IDatasetName)pDatalayer.DataSourceName;

            strRegisterFile = pDname.WorkspaceName.PathName + pDname.Name;

            pDatalayer  = m_pRasterLayerRight as IDataLayer;
            pDname      = (IDatasetName)pDatalayer.DataSourceName;
            strBaseFile = pDname.WorkspaceName.PathName + pDname.Name;

            //得到Raster2
            m_pRasterLeft  = m_pRasterLayerLeft.Raster as IRaster2;
            m_pRasterRight = m_pRasterLayerRight.Raster as IRaster2;

            string szLeftGrayImage  = System.IO.Path.GetTempFileName();
            string szRightGrayImage = System.IO.Path.GetTempFileName();

            try
            {
                IPoint ptLeftTopOffset = new PointClass();
                ptLeftTopOffset.X = 0;
                ptLeftTopOffset.Y = 0;

                //配置配准参数
                szLeftGrayImage  = System.IO.Path.GetDirectoryName(szLeftGrayImage) + "\\" + System.IO.Path.GetFileNameWithoutExtension(szLeftGrayImage) + ".tif";
                szRightGrayImage = System.IO.Path.GetDirectoryName(szRightGrayImage) + "\\" + System.IO.Path.GetFileNameWithoutExtension(szRightGrayImage) + ".tif";
                if (!stretchToGrayImage(m_pRasterLeft as IRaster, szLeftGrayImage))
                {
                    return;                                                                 //拉伸左影像
                }
                if (!stretchToGrayImage(m_pRasterRight as IRaster, szRightGrayImage))
                {
                    return;                                          //拉伸右影像
                }
                m_pSiftMatchPara.szLeftFilename  = szLeftGrayImage;  // strRegisterFile;
                m_pSiftMatchPara.szRightFilename = szRightGrayImage; // strBaseFile;
                //m_pSiftMatchPara.szOutputFilename = txtOutputFilename.Text;

                m_pSiftMatchPara.dbLeftTopOffsetX = ptLeftTopOffset.X;
                m_pSiftMatchPara.dbLeftTopOffsetY = ptLeftTopOffset.Y;

                m_pSiftMatchPara.dbRatio       = dbiRatio.Value;
                m_pSiftMatchPara.nMaxBlockSize = Convert.ToUInt32(iiMaxBlockSize.Value);
                m_pSiftMatchPara.nOverlaySize  = Convert.ToUInt32(iiOverlaySize.Value);
                m_pSiftMatchPara.dbRansacSigma = doubleRansac.Value;
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.Message);
                this.DialogResult = DialogResult.Cancel;
                return;
            }
        }
示例#22
0
        private void ExportToTif()
        {
            string strFloder = txtOutData.Text;

            for (int i = 0; i < m_pMapControl.Map.LayerCount; i++)
            {
                if (m_pMapControl.Map.get_Layer(i) is IRasterLayer)
                {
                    //导入数据
                    IRasterLayer pRLayer     = m_pMapControl.Map.get_Layer(i) as IRasterLayer;
                    IRaster2     pRaster     = pRLayer.Raster as IRaster2;
                    IRawBlocks   pRawBlocks  = pRaster as IRawBlocks;
                    IRasterInfo  pRInfo      = pRawBlocks.RasterInfo;
                    IPnt         pPnt        = pRInfo.CellSize;
                    double       dcellSize   = pPnt.X;
                    double       dcellsizeY  = pPnt.Y;
                    string       sCellSize   = Convert.ToInt32(dcellSize * 10).ToString();
                    string       strFileName = "R" + sCellSize + "_" + pRLayer.Name;
                    string       strFullName = txtOutData.Text + "\\" + strFileName;
                    //设置空间参考
                    ISpatialReference pSpatialRef;
                    if (rdoLayer.Checked)//与原图相同
                    {
                        IGeoDataset pGeo = (IGeoDataset)pRLayer;
                        pSpatialRef = pGeo.SpatialReference;
                    }
                    else//与工作空间相同
                    {
                        pSpatialRef = m_pMapControl.Map.SpatialReference;
                    }

                    try
                    {
                        //IRasterLayerExport pRLayerExport = new RasterLayerExportClass();
                        //pRLayerExport.RasterLayer = pRLayer;
                        //pRLayerExport.SpatialReference = pSpatialRef;
                        //pRLayerExport.SetSize(pRLayer.ColumnCount, pRLayer.RowCount);
                        IWorkspaceFactory pWSF = new RasterWorkspaceFactoryClass();
                        IWorkspace        pWS  = pWSF.OpenFromFile(txtOutData.Text, 0);
                        //IRasterDataset pRDset = pRLayerExport.Export(pWS, strFileName, "TIFF");
                        //System.Runtime.InteropServices.Marshal.ReleaseComObject(pRDset);

                        IRasterProps pRasterProps = pRaster as IRasterProps;
                        //pRasterProps.PixelType = pRInfo.PixelType;
                        //投影发生变化,栅格的分辨率会发生变化
                        pRasterProps.SpatialReference = pSpatialRef;
                        IRawBlocks  pRBlocks = pRasterProps as IRawBlocks;
                        IRasterInfo pRaInfo  = pRBlocks.RasterInfo;
                        //计算出重投影之后对应的栅格的行数和列数,行列数改变之后,它对应的栅格的分辨率也会变化为原始栅格的分辨率
                        //如果没有下面的计算行列的步骤,重投影之后的分辨率和原始影响的分辨率不同,行列数相同
                        pRasterProps.Width  = Convert.ToInt32(pRasterProps.MeanCellSize().X *pRLayer.ColumnCount / dcellSize);
                        pRasterProps.Height = Convert.ToInt32(pRasterProps.MeanCellSize().Y *pRLayer.RowCount / dcellsizeY);
                        IEnvelope pEnvelope = new EnvelopeClass();
                        pEnvelope.XMin      = pRasterProps.Extent.UpperLeft.X;
                        pEnvelope.YMax      = pRasterProps.Extent.UpperLeft.Y;
                        pEnvelope.XMax      = pRasterProps.Extent.UpperLeft.X + pRasterProps.Width * dcellSize;
                        pEnvelope.YMin      = pRasterProps.Extent.UpperLeft.Y - pRasterProps.Height * dcellsizeY;
                        pRasterProps.Extent = pEnvelope;

                        ISaveAs2          pSaveAs = pRasterProps as ISaveAs2;
                        IRasterStorageDef pRSDef  = new RasterStorageDefClass();
                        //将存储栅格的分辨率设置为与原始图像相同,其实经过上面行列计算之后已经是相同的
                        IPnt pPntdec = new PntClass();
                        pPntdec.X       = dcellSize;
                        pPntdec.Y       = dcellsizeY;
                        pRSDef.CellSize = pPntdec;

                        IRasterDataset pDataset = pSaveAs.SaveAsRasterDataset(strFileName, pWS, "TIFF", pRSDef);
                        pDataset.PrecalculateStats(0);
                        System.Runtime.InteropServices.Marshal.ReleaseComObject(pDataset);
                    }
                    catch (Exception exc)
                    {
                        //MessageBox.Show(exc.Message, "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
            this.Close();
        }
示例#23
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   = pRasterDs.CreateDefaultRaster();

            IRasterLayer resLayer = new RasterLayerClass();

            resLayer.CreateFromRaster(praster);
            m_raster = resLayer.Raster;
        }
示例#24
0
        /// <summary>
        /// Occurs when this command is clicked
        /// </summary>
        public override void OnClick()
        {
            // TODO: Add CmdRasterRegister.OnClick implementation
            IMapControl3 pMapCtrl = null;

            if (m_hookHelper.Hook is IToolbarControl)
            {
                if (((IToolbarControl)m_hookHelper.Hook).Buddy is IMapControl3)
                {
                    pMapCtrl = (IMapControl3)((IToolbarControl)m_hookHelper.Hook).Buddy;
                }
            }
            //In case the container is MapControl
            else if (m_hookHelper.Hook is IMapControl3)
            {
                pMapCtrl = (IMapControl3)m_hookHelper.Hook;
            }
            else
            {
                return;
            }

            System.GC.Collect();
            FrmSiftMatching frmSiftMatching = new FrmSiftMatching(pMapCtrl, pRasterLayer);

            if (frmSiftMatching.ShowDialog() == DialogResult.OK)
            {
                ClsSiftMatching pSiftMatching = new ClsSiftMatching();
                double[]        dbMatchPts;
                int             nCount = 0;
                if (pSiftMatching.siftMatching(frmSiftMatching.m_pSiftMatchPara, out dbMatchPts, out nCount))
                {
                    IRaster2     pLeftRaster    = frmSiftMatching.m_pRasterLeft;
                    IRasterProps pLeftProps     = pLeftRaster as IRasterProps;
                    IPoint       pLeftLowerLeft = pLeftProps.Extent.LowerLeft;

                    IRaster2     pRightRaster    = frmSiftMatching.m_pRasterRight;
                    IRasterProps pRightProps     = pRightRaster as IRasterProps;
                    IPoint       pRightLowerLeft = pRightProps.Extent.LowerLeft;

                    //SIFT匹配出来的都是影像坐标,应该先转换成MAPCTRL单位为准
                    for (int i = 0; i < nCount; i++)
                    {
                        int x = (int)dbMatchPts[4 * i];
                        int y = (int)(dbMatchPts[4 * i + 1]);
                        //y = (int)(-1*dbMatchPts[4 * i + 1]);
                        pLeftRaster.PixelToMap(x, y, out dbMatchPts[4 * i], out dbMatchPts[4 * i + 1]);

                        x = (int)dbMatchPts[4 * i + 2];
                        y = (int)(dbMatchPts[4 * i + 3]);
                        //y = (int)(-1*dbMatchPts[4 * i + 3]);
                        pRightRaster.PixelToMap(x, y, out dbMatchPts[4 * i + 2], out dbMatchPts[4 * i + 3]);

                        #region 废弃代码
                        //int x = (int)dbMatchPts[4 * i];
                        //int y = (int)(dbMatchPts[4 * i + 1]);
                        //dbMatchPts[4 * i] = x * pLeftProps.MeanCellSize().X + pLeftLowerLeft.X;
                        //dbMatchPts[4 * i + 1] = y * pLeftProps.MeanCellSize().Y + pLeftLowerLeft.Y;

                        //x = (int)dbMatchPts[4 * i + 2];
                        //y = (int)(dbMatchPts[4 * i + 3]);
                        //dbMatchPts[4 * i + 2] = x * pRightProps.MeanCellSize().X + pRightLowerLeft.X;
                        //dbMatchPts[4 * i + 3] = y * pRightProps.MeanCellSize().Y + pRightLowerLeft.Y;
                        //IPoint ptFrom = pMapCtrl.ToMapPoint(Convert.ToInt32(dbMatchPts[4 * i + 0]), Convert.ToInt32(dbMatchPts[4 * i + 1]));
                        //IPoint ptTo = pMapCtrl.ToMapPoint(Convert.ToInt32(dbMatchPts[4 * i + 2]), Convert.ToInt32(dbMatchPts[4 * i + 3]));

                        //dbMatchPts[4 * i + 0] = ptFrom.X;
                        //dbMatchPts[4 * i + 1] = ptFrom.Y;
                        //dbMatchPts[4 * i + 2] = ptTo.X;
                        //dbMatchPts[4 * i + 3] = ptTo.Y;
                        #endregion
                    }
                    pSiftMatching.outputMatchPointsToFile("d:\\b.txt", dbMatchPts, nCount);

                    //添加到控制点中
                    m_FrmLink.DelAllPoints();
                    for (int i = 0; i < nCount; i++)
                    {
                        IPoint ptOrg = new ESRI.ArcGIS.Geometry.PointClass();
                        ptOrg.PutCoords(dbMatchPts[4 * i], dbMatchPts[4 * i + 1]);
                        m_FrmLink.OriginPoints.AddPoint(ptOrg);

                        IPoint ptTarget = new ESRI.ArcGIS.Geometry.PointClass();
                        ptTarget.PutCoords(dbMatchPts[4 * i + 2], dbMatchPts[4 * i + 3]);
                        m_FrmLink.TargetPoints.AddPoint(ptTarget);
                    }
                    m_FrmLink.RefreshControlAllPoints();
                    m_FrmLink.Show();
                    pMapCtrl.ActiveView.PartialRefresh(esriViewDrawPhase.esriViewGeography, null, null);
                    //MessageBox.Show("匹配成功!");
                }
                else
                {
                    MessageBox.Show("匹配失败!");
                }

                //把临时创建的文件删除
                try
                {
                    string szLeftFilename  = frmSiftMatching.m_pSiftMatchPara.szLeftFilename;
                    string szRightFilename = frmSiftMatching.m_pSiftMatchPara.szRightFilename;
                    if (System.IO.File.Exists(szLeftFilename))
                    {
                        System.IO.File.Delete(szLeftFilename);
                    }

                    if (System.IO.File.Exists(szRightFilename))
                    {
                        System.IO.File.Delete(szRightFilename);
                    }
                }
                catch (System.Exception ex)
                {
                    return;
                }
            }
        }