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) { raster.Read(pntstart, (IPixelBlock)unionPixelBlock); int[,] intMat = (int[, ])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); }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); IPixelBlock3 pPixelBlock3 = (IPixelBlock3)pPixelBlock; IRaster2 inRs2 = (IRaster2)inrs; IRaster2 outRs2 = (IRaster2)outrs; double mx, my; outRs2.PixelToMap((int)pTlc.X, (int)pTlc.Y, out mx, out my); int clm, rw; inRs2.MapToPixel(mx, my, out clm, out rw); IPnt pntLoc = new PntClass(); pntLoc.SetCoords(clm, rw); IPnt pntSize = new PntClass(); pntSize.SetCoords(pPixelBlock.Width, pPixelBlock.Height); IPixelBlock3 pBIn = (IPixelBlock3)inrs.CreatePixelBlock(pntSize); inrs.Read(pntLoc, (IPixelBlock)pBIn); for (int p = 0; p < pPixelBlock.Planes; p++) { pPixelBlock3.set_PixelData(p, pBIn.get_PixelData(p)); } } catch (Exception e) { Console.WriteLine(e.ToString()); } }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. //Console.WriteLine("Before Read"); myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); IRaster mosRs = (IRaster)mos; IPnt pntSize = new PntClass(); pntSize.SetCoords(pPixelBlock.Width, pPixelBlock.Height); IPixelBlock pb = mosRs.CreatePixelBlock(pntSize); mosRs.Read(pTlc, pb); for (int i = 0; i < pb.Planes; i++) { pPixelBlock.set_SafeArray(i, pb.get_SafeArray(i)); } } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of mosaic Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
/// <summary> /// Get the pixel values in a region of the input raster. /// </summary> /// <param name="tlCorner"></param> /// <param name="brCorner"></param> /// <param name="raster"></param> /// <returns></returns> public static double[,] GetValues(Position tlCorner, Position brCorner, IRaster raster) { int colCount = brCorner.Column - tlCorner.Column + 1; int rowCount = brCorner.Row - tlCorner.Row + 1; IPnt regionSize = new PntClass(); regionSize.SetCoords(colCount, rowCount); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(tlCorner.Column, tlCorner.Row); raster.Read(tl, pixelBlock); double[,] values = new double[colCount, rowCount]; for (int x = 0; x < colCount; x++) { for (int y = 0; y < rowCount; y++) { Pixel cell = Editor.Edits[x + tlCorner.Column, y + tlCorner.Row]; if (cell == null) { values[x, y] = Convert.ToDouble(pixelBlock.GetVal(0, x, y)); } else { values[x, y] = cell.NewValue; } } } return(values); }
/// <summary> /// Read pixels from the input Raster and fill the PixelBlock provided with processed pixels. /// The RasterFunctionHelper object is used to handle pixel type conversion and resampling. /// The log raster is the natural log of the raster. /// </summary> /// <param name="pTlc">Point to start the reading from in the Raster</param> /// <param name="pRaster">Reference Raster for the PixelBlock</param> /// <param name="pPixelBlock">PixelBlock to be filled in</param> public void Read(IPnt pTlc, IRaster pRaster, IPixelBlock pPixelBlock) { try { // Call Read method of the Raster Function Helper object. //System.Array noDataValueArr = (System.Array)((IRasterProps)inrsBandsCoef).NoDataValue; //Console.WriteLine("Before Read"); myFunctionHelper.Read(pTlc, null, pRaster, pPixelBlock); //Console.WriteLine("After Read"); int pBHeight = pPixelBlock.Height; int pBWidth = pPixelBlock.Width; IPnt pbSize = new PntClass(); pbSize.SetCoords(pBWidth, pBHeight); IPixelBlock3 outPb = (IPixelBlock3)inrsBandsCoef.CreatePixelBlock(pbSize);//independent variables inrsBandsCoef.Read(pTlc, (IPixelBlock)outPb); int pBRowIndex = 0; int pBColIndex = 0; IPixelBlock3 ipPixelBlock = (IPixelBlock3)pPixelBlock; //System.Array[] pArr = new System.Array[outPb.Planes]; //for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) //{ // System.Array pixelValues = (System.Array)(outPb.get_PixelData(coefnBand)); // pArr[coefnBand] = pixelValues; //} System.Array pValues = (System.Array)ipPixelBlock.get_PixelData(0);//(System.Array)(td); for (int i = pBRowIndex; i < pBHeight; i++) { for (int k = pBColIndex; k < pBWidth; k++) { double[] xVls = new double[outPb.Planes]; bool ndT = true; for (int coefnBand = 0; coefnBand < outPb.Planes; coefnBand++) { //float noDataValue = System.Convert.ToSingle(noDataValueArr.GetValue(coefnBand)); object pObj = outPb.GetVal(coefnBand, k, i); if (pObj == null) { ndT = false; break; } float pixelValue = Convert.ToSingle(pObj); xVls[coefnBand] = pixelValue; } if (ndT) { int c = cluster.computNew(xVls); pValues.SetValue(c, k, i); } } } ipPixelBlock.set_PixelData(0, pValues); } catch (Exception exc) { System.Exception myExc = new System.Exception("Exception caught in Read method of Cluster Function. " + exc.Message, exc); Console.WriteLine(exc.ToString()); } }
private void updateWithMergedValues(IEnvelope env, IPixelBlock3 ipPixelBlock) { System.Array[] outPixelValuesArr = new System.Array[ipPixelBlock.Planes]; List <System.Array[]> inPixelValuesArrLst = new List <System.Array[]>(); List <System.Array> inPixelNoDataArrLst = new List <System.Array>(); IPnt pntSize = new PntClass(); pntSize.SetCoords(ipPixelBlock.Width, ipPixelBlock.Height); ISpatialFilter spFlt = new SpatialFilterClass(); spFlt.Geometry = (IGeometry)env; spFlt.GeometryField = ftrCls.ShapeFieldName; spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelOverlaps; IFeatureCursor fCur = ftrCls.Search(spFlt, false); int fIndex = ftrCls.FindField("catIndex"); IFeature ftr = fCur.NextFeature(); for (int i = 0; i < ipPixelBlock.Planes; i++) { outPixelValuesArr[i] = (System.Array)ipPixelBlock.get_PixelData(i); } while (ftr != null) { int rsIndex = System.Convert.ToInt32(ftr.get_Value(fIndex)); IRaster rs = inrs[rsIndex]; IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); IRaster2 rs2 = (IRaster2)rs; int pClm, pRw; rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); IPnt tlc = new PntClass(); tlc.SetCoords(pClm, pRw); rs.Read(tlc, inputPb); System.Array[] inPixelValuesArr = new System.Array[inputPb.Planes]; for (int i = 0; i < inputPb.Planes; i++) { inPixelValuesArr[i] = (System.Array)inputPb.get_SafeArray(i); } inPixelNoDataArrLst.Add((System.Array)((IRasterProps)rs).NoDataValue); inPixelValuesArrLst.Add(inPixelValuesArr); ftr = fCur.NextFeature(); } for (int i = 0; i < outPixelValuesArr.Length; i++) { for (int r = 0; r < ipPixelBlock.Height; r++) { for (int c = 0; c < ipPixelBlock.Width; c++) { double vl = getValue(i, c, r, inPixelValuesArrLst, inPixelNoDataArrLst); outPixelValuesArr[i].SetValue(vl, c, r); } } } for (int i = 0; i < outPixelValuesArr.Length; i++) { ipPixelBlock.set_PixelData(i, outPixelValuesArr[i]); } }
//获取最大最小栅格值 private void SetMaxMinValue(int flag) { if (flag == 1) { textBoxMax.Text = "高:255"; textBoxMin.Text = "低:0"; return; } uint valueMax = 50; uint valueMin = 50; IRasterLayer pRasterLayer = m_layer as IRasterLayer; IRaster pRaster = pRasterLayer.Raster; IRasterProps pRasterProps = pRaster as IRasterProps; int Height = pRasterProps.Height; int Width = pRasterProps.Width; double dX = pRasterProps.MeanCellSize().X; double dY = pRasterProps.MeanCellSize().Y; //栅格的高度 IEnvelope extent = pRasterProps.Extent; //当前栅格数据集的范围 rstPixelType pixelType = pRasterProps.PixelType; //当前栅格像素类型 IPnt pntSize = new PntClass(); pntSize.SetCoords(dX, dY); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); IPnt pnt = new PntClass(); for (int i = 0; i < Height; i += 10) { for (int j = 0; j < Width; j += 10) { pnt.SetCoords(i, j); pRaster.Read(pnt, pixelBlock); if (pixelBlock != null) { object obj = pixelBlock.GetVal(0, 0, 0); uint temp = Convert.ToUInt32(obj); if (temp > valueMax) { valueMax = temp; } else if (temp < valueMin) { valueMin = temp; } } } } textBoxMax.Text = "高:" + valueMax.ToString(); textBoxMin.Text = "低:" + valueMin.ToString(); }
/// <summary> /// Gets value of pixel at the specified position. /// </summary> /// <param name="pos"></param> /// <param name="raster"></param> /// <returns></returns> public static double GetValue(Position pos, IRaster raster) { IPnt regionSize = new PntClass(); regionSize.SetCoords(1, 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(pos.Column, pos.Row); raster.Read(tl, pixelBlock); return(Convert.ToDouble(pixelBlock.GetVal(0, 0, 0))); }
private IPixelBlock GetAllPixelBlock(int width, int height) { IRaster pRaster = GetRaster(); IPnt pnt = new PntClass(); pnt.SetCoords(0, 0); IPnt pntSize = new PntClass(); pntSize.SetCoords(width, height); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); pRaster.Read(pnt, pixelBlock); return(pixelBlock); }
public bool readBlockDataToFile(Point2D ptLeftTop, ref double[,] dbData, IRaster pRaster /*, IRasterEdit rasterEdit*/) { if (pRaster == null) { return(false); } try { //Create a pixel block using the weight and height of the raster dataset. //If the raster dataset is large, a smaller pixel block should be used. //Refer to the topic "How to access pixel data using a raster cursor". int nWidth = dbData.GetLength(0); int nHeight = dbData.GetLength(1); IPnt blocksize = new PntClass(); blocksize.SetCoords(nWidth, nHeight); //Define the location that the upper left corner of the pixel block is to write. IPnt upperLeft = new PntClass(); upperLeft.SetCoords(ptLeftTop.X, ptLeftTop.Y); IPixelBlock3 pixelblock = pRaster.CreatePixelBlock(blocksize) as IPixelBlock3; pRaster.Read(upperLeft, pixelblock as IPixelBlock); //Populate some pixel values to the pixel block. System.Array pixels; pixels = (System.Array)pixelblock.get_PixelData(0); for (int i = 0; i < nWidth; i++) { for (int j = 0; j < nHeight; j++) { dbData[i, j] = Convert.ToDouble(pixels.GetValue(i, j));//.GetType().; } } return(true); } catch (Exception ex) { System.Diagnostics.Debug.WriteLine("Error: " + ex.Message); return(false); } GC.Collect(); return(true); }
/// <summary> /// 读取数据 /// </summary> /// <param name="xIndex">水平方向的序号</param> /// <param name="yIndex">垂直方向的序号</param> /// <returns>获取的值,如果为null,表明该位置没有数据</returns> public object Read(int xIndex, int yIndex) { IRaster pRaster = GetRaster(); IPnt pnt = new PntClass(); pnt.SetCoords(xIndex, yIndex); IPnt pntSize = new PntClass(); pntSize.SetCoords(1, 1); IPixelBlock pixelBlock = pRaster.CreatePixelBlock(pntSize); pRaster.Read(pnt, pixelBlock); object obj = pixelBlock.GetVal(0, 0, 0); return(obj); }
public static double GetPixelVal(IRaster pRaster, IPoint pPoint) { IPixelBlock pPixelBlock; IPnt pPnt; IPnt pCurrentPnt; ISpatialReference pSR; pSR = pPoint.SpatialReference; pPnt = new DblPnt(); pPnt.SetCoords(1.0, 1.0); pPixelBlock = pRaster.CreatePixelBlock(pPnt); pCurrentPnt = GetCurrPnt(pRaster, pPoint.X, pPoint.Y, pSR); pRaster.Read(pCurrentPnt, pPixelBlock); return(Convert.ToDouble(string.Format("{0,10:###0.0000}", pPixelBlock.GetVal(0, 0, 0)))); }
/// <summary> /// 读取指定块处的像元值到数组. /// </summary> /// <param name="pRasterDS">The p raster ds.</param> /// <param name="pBlockSize0">左上角点.</param> /// <param name="pBlockSize1">块大小.</param> /// <returns>System.Single[].</returns> public static float[,] ReadFloat(IRasterDataset2 pRasterDS, IPnt pBlockSize0, IPnt pBlockSize1) { try { //IRaster pRaster = thisRasterLayer.Raster; IRaster pRaster = pRasterDS.CreateFullRaster(); IRaster2 pRaster2 = (IRaster2)pRaster; IRasterProps pRSp = (IRasterProps)pRaster; IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize1).PixelBlock; pRaster.Read(pBlockSize0, pixelBlock); IPixelBlock3 block2 = (IPixelBlock3)pixelBlock; return((float[, ])block2.get_PixelData(0)); } catch (Exception ex) { XtraMessageBox.Show("读取影像失败!\n" + ex.Message); return(null); } }
/// <summary> /// 一次读取整幅影像像元值 /// </summary> /// <typeparam name="T"></typeparam> /// <param name="pRasterDS">The p raster ds.</param> /// <returns>T[].</returns> public static T[,] ReadPixelValue <T>(IRasterDataset2 pRasterDS) { try { //IRaster pRaster = thisRasterLayer.Raster; IRaster pRaster = pRasterDS.CreateFullRaster(); IRaster2 pRaster2 = (IRaster2)pRaster; IRasterProps pRSp = (IRasterProps)pRaster; IPnt pBlockSize = new PntClass(); pBlockSize.SetCoords((float)pRSp.Width, (float)pRSp.Height); IPixelBlock pixelBlock = pRaster2.CreateCursorEx(pBlockSize).PixelBlock; pBlockSize.SetCoords(0.0, 0.0); pRaster.Read(pBlockSize, pixelBlock); IPixelBlock3 block2 = (IPixelBlock3)pixelBlock; return((T[, ])block2.get_PixelData(0));; } catch (Exception ex) { XtraMessageBox.Show("读取分类影像失败!\n" + ex.Message); return(null); } }
static void Main(string[] args) { //ESRI License Initializer generated code. m_AOLicenseInitializer.InitializeApplication(new esriLicenseProductCode[] { esriLicenseProductCode.esriLicenseProductCodeAdvanced }, new esriLicenseExtensionCode[] { esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst });//{esriLicenseExtensionCode.esriLicenseExtensionCode3DAnalyst}); System.DateTime dt = System.DateTime.Now; System.DateTime dt2; TimeSpan ts; rasterUtil rsUtil = new rasterUtil(); geoDatabaseUtility geoUtil = new geoDatabaseUtility(); string pred = @"C:\Users\jshogland\Documents\John\projects\FtStewart\models\TreeEstimates\HdwPresentPred.bch"; string mdl = @"C:\Users\jshogland\Documents\John\projects\FtStewart\models\TreeEstimates\HdwPresent.mdl"; double[] minArr, maxArr; Console.WriteLine("Getting Min Max"); batchCalculations.getMinMaxArr(mdl, out minArr, out maxArr); Console.WriteLine("First Min Max: " + minArr[0].ToString() + ";" + maxArr[0].ToString()); IFunctionRasterDataset fdset = rsUtil.extactModelDomainFunction(pred, minArr, maxArr); Console.WriteLine(fdset.RasterInfo.PixelType.ToString()); IRaster rs = rsUtil.createRaster(fdset); IPnt pntSize = new PntClass(); pntSize.SetCoords(100, 100); IPixelBlock pb = rs.CreatePixelBlock(pntSize); rs.Read(pntSize, pb); int cnt = 0; for (int r = 0; r < pb.Height; r++) { for (int c = 0; c < pb.Width; c++) { object vl = pb.GetVal(0, c, r); if (vl != null) { if (System.Convert.ToInt32(vl) == 0) { cnt++; } } } } Console.WriteLine("Total zeros = " + cnt.ToString()); //string dir = @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Classes\Mining Big Data\Assignments\NatureServe\train\ALB"; //string[] fls = System.IO.Directory.GetFiles(dir, "*.jpg"); //foreach (string flPath in fls) //{ // string nm = System.IO.Path.GetFileNameWithoutExtension(flPath); // Console.WriteLine(nm); // Bitmap bm = new Bitmap(flPath); // Accord.Imaging.Moments.CentralMoments cm = new Accord.Imaging.Moments.CentralMoments(bm, 3); // //Console.WriteLine(cm.Mu00.ToString()); // Console.WriteLine("\t"+cm.Mu01.ToString()); // Console.WriteLine("\t" + cm.Mu02.ToString()); // Console.WriteLine("\t" + cm.Mu03.ToString()); // Console.WriteLine("\t" + cm.Mu10.ToString()); // Console.WriteLine("\t" + cm.Mu20.ToString()); // Console.WriteLine("\t" + cm.Mu30.ToString()); //} //string plots = @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\coReg.gdb\SampleLocations"; //string ls= @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\FloridaLandsat.tif"; //string naip= @"C:\Users\jshogland\Documents\John\projects\UMGradSchool\Project\papers\Co-registration\Data\GeorgiaNaipAgAl.tif"; //rasterUtil rsUtil = new rasterUtil(); //HashSet<string> uStr = new HashSet<string>(); //int[] filesLines = getClasses(prjDir,ref uStr); //Console.WriteLine("Files = " + filesLines[0].ToString()); //Console.WriteLine("Lines = " + filesLines[1].ToString()); //Console.WriteLine(uStr.Count().ToString()); //geoDatabaseUtility geoUtil = new geoDatabaseUtility(); //rasterUtil rsUtil = new rasterUtil(); //featureUtil ftrUtil = new featureUtil(rsUtil); ////string origPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\OriginalSample"; ////string nwPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\RandomtShiftSample"; ////CreateNewPoints(origPath, nwPath, rsUtil, ftrUtil, geoUtil, true); //string fiaTestPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\RandomtShiftSample"; //string fiaOutPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\Shift.gdb\adjustSample"; //string rsPath = @"C:\Users\jshogland\Documents\John\projects\SpatialAdjust\models\predictorsOneVariable.bch"; //IFunctionRasterDataset fDset = rsUtil.createIdentityRaster(rsPath); //IFeatureClass ftrCls = geoUtil.getFeatureClass(fiaTestPath); //int error = 15; //adjustCoregistrationErrors aE = new adjustCoregistrationErrors(rsUtil); //aE.FunctionRasterDataset = fDset; //aE.DependentField = "Pred15"; //aE.GeometricErrorCells = error; //aE.OutFtrClassPath = fiaOutPath; //aE.PlotFeatureClass = ftrCls; //aE.adjustErrors(); dt2 = System.DateTime.Now; ts = dt2.Subtract(dt); Console.WriteLine("Total Seconds = " + ts.TotalSeconds.ToString()); m_AOLicenseInitializer.ShutdownApplication(); }
private void updateWithMergedValues(IEnvelope env, IPixelBlock3 ipPixelBlock) { System.Array[] outPixelValuesArr = new System.Array[ipPixelBlock.Planes]; IPnt pntSize = new PntClass(); pntSize.SetCoords(ipPixelBlock.Width, ipPixelBlock.Height); ISpatialFilter spFlt = new SpatialFilterClass(); spFlt.Geometry = (IGeometry)env; spFlt.GeometryField = ftrCls.ShapeFieldName; spFlt.SpatialRel = esriSpatialRelEnum.esriSpatialRelIndexIntersects; IFeatureCursor fCur = ftrCls.Search(spFlt, false); ////int fIndex = ftrCls.FindField("catIndex"); IFeature ftr = fCur.NextFeature(); for (int i = 0; i < ipPixelBlock.Planes; i++) { outPixelValuesArr[i] = (System.Array)ipPixelBlock.get_PixelData(i); } //IQueryFilter qf = new QueryFilterClass(); //string s1 = "(XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s2 = "(XMIN > " + env.XMin.ToString() + " AND XMIN < " + env.XMax.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s3 = "(XMAX < " + env.XMax.ToString() + " AND XMIN > " + env.XMin.ToString() + " AND YMIN <= " + env.YMin.ToString() + " AND YMAX >= " + env.YMax.ToString() + ")"; //string s4 = "(YMIN > " + env.YMin.ToString() + " AND YMIN < " + env.YMax.ToString() + " AND XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + ")"; //string s5 = "(YMAX < " + env.YMax.ToString() + " AND YMIN > " + env.YMin.ToString() + " AND XMIN <= " + env.XMin.ToString() + " AND XMAX >= " + env.XMax.ToString() + ")"; //qf.WhereClause = s1 + " OR " + s2 + " OR " + s3 + " OR " + s4 + " OR " + s5; //ICursor cur = tbl.Search(qf, false); //IRow rw = cur.NextRow(); List <IPixelBlock> inPbValue = new List <IPixelBlock>(); //while (rw != null) //{ // int rsIndex = System.Convert.ToInt32(rw.get_Value(catIndex)); // IRaster rs = inrs[rsIndex]; // IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); // IRaster2 rs2 = (IRaster2)rs; // int pClm, pRw; // rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); // IPnt tlc = new PntClass(); // tlc.SetCoords(pClm, pRw); // rs.Read(tlc, inputPb); // inPbValue.Add(inputPb); // rw = cur.NextRow(); //} while (ftr != null) { int rsIndex = System.Convert.ToInt32(ftr.get_Value(catIndex)); IRaster rs = inrs[rsIndex]; IPixelBlock inputPb = rs.CreatePixelBlock(pntSize); IRaster2 rs2 = (IRaster2)rs; int pClm, pRw; rs2.MapToPixel(env.XMin, env.YMax, out pClm, out pRw); IPnt tlc = new PntClass(); tlc.SetCoords(pClm, pRw); rs.Read(tlc, inputPb); inPbValue.Add(inputPb); ftr = fCur.NextFeature(); } for (int i = 0; i < ipPixelBlock.Planes; i++) { for (int r = 0; r < ipPixelBlock.Height; r++) { for (int c = 0; c < ipPixelBlock.Width; c++) { object vl = getValue(i, c, r, inPbValue); outPixelValuesArr[i].SetValue(vl, c, r); } } } for (int i = 0; i < outPixelValuesArr.Length; i++) { ipPixelBlock.set_PixelData(i, outPixelValuesArr[i]); } }
//逐点算法 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); }
private void middleRowColumn(IPnt loc, int[] startRows, int[] startColumns) { double x = loc.X; double y = loc.Y; string outLocStr = x.ToString() + ":" + y.ToString(); //string inLocStr = (x - 1).ToString() + ":" + (y - 1).ToString(); IPnt readLoc = new PntClass(); readLoc.SetCoords(x - 1, y - 1); IRasterEdit regRsE = (IRasterEdit)OutRaster; IPnt writePbSize = new PntClass(); writePbSize.SetCoords(pbwidth, pbheight); IPnt readPbSize = new PntClass(); readPbSize.SetCoords(pbwidth + 2, pbheight + 2); IPixelBlock pb = inRs.CreatePixelBlock(readPbSize); IPixelBlock pb2 = OutRaster.CreatePixelBlock(writePbSize); System.Array[] inOutArr; System.Array inArr = null; System.Array outArr = null; if (outArrDic.TryGetValue(outLocStr, out inOutArr)) { inArr = inOutArr[0]; outArr = inOutArr[1]; } else { //Console.WriteLine(outLocStr); OutRaster.Read(loc, pb2); inRs.Read(readLoc, pb); OutRaster.Read(loc, pb2); inArr = (System.Array)pb.get_SafeArray(0); outArr = (System.Array)pb2.get_SafeArray(0); outArrDic[outLocStr] = new System.Array[] { inArr, outArr }; } int height = pb2.Height; int width = pb2.Width; for (int si = 0; si < startRows.Length; si++) { int c = startColumns[si]; int r = startRows[si]; int ic = c + 1; int ir = r + 1; //Console.WriteLine(cr[0]); int inVl = System.Convert.ToInt32(inArr.GetValue(ic, ir)); if ((inVl == noDataVl) || (inVl == (noDataVl - 1))) { Console.WriteLine("Invalue form 2 middle = " + inVl.ToString()); continue; } else { int outVl32 = System.Convert.ToInt32(outArr.GetValue(c, r)); if (outVl32 != noDataVl2) { } else { List <string> cr = new List <string>(); cr.Add(c.ToString() + ":" + r.ToString()); outArr.SetValue(counter, c, r); List <int>[] nextArray = { new List <int>(), new List <int>(), new List <int>(), new List <int>() };//determines if the next pixel block must be queried {left,top,right,bottom} while (cr.Count > 0) { rCnt++; rPerm += findRegion(inVl, counter, noDataVl2, inArr, outArr, cr, nextArray); } for (int i = 0; i < nextArray.Length; i++) { List <int> pbNextLst = nextArray[i]; if (pbNextLst.Count > 0) { int[] startClms = new int[pbNextLst.Count]; int[] startRws = new int[pbNextLst.Count]; IPnt newLoc = new PntClass(); double nClP = loc.X; double nRwP = loc.Y; switch (i) { case 0: nClP = nClP - pbwidth; startRws = pbNextLst.ToArray(); int stcl = pbwidth - 1; for (int k = 0; k < startRws.Length; k++) { startClms[k] = stcl; } break; case 1: nRwP = nRwP - pbheight; startClms = pbNextLst.ToArray(); //rws=pbHeight-1 int strw = pbheight - 1; for (int k = 0; k < startClms.Length; k++) { startRws[k] = strw; } break; case 2: nClP = nClP + pbwidth; startRws = pbNextLst.ToArray(); //clms=0; break; default: nRwP = nRwP + pbheight; startClms = pbNextLst.ToArray(); //rws = 0; break; } if ((nClP >= 0 && nRwP >= 0 & nClP <= rsProps2.Width && nRwP <= rsProps2.Height)) { newLoc.SetCoords(nClP, nRwP); middleRowColumn(newLoc, startRws, startClms); } } } } } } return; }
/// <summary> /// Gets value of pixel at the specified position. /// </summary> /// <param name="pos"></param> /// <param name="raster"></param> /// <returns></returns> public static double GetValue(Position pos, IRaster raster) { IPnt regionSize = new PntClass(); regionSize.SetCoords(1, 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(pos.Column, pos.Row); raster.Read(tl, pixelBlock); return Convert.ToDouble(pixelBlock.GetVal(0, 0, 0)); }
/// <summary> /// Write edits to the input raster. /// </summary> /// <param name="raster">Raster of raster layer to be edited.</param> /// <param name="edits">Pixel collection that contains edited pixels.</param> private static void WriteEdits(IRaster raster, PixelCollection edits) { IRasterProps rasterProps = (IRasterProps)raster; int minRow = rasterProps.Height - 1; int maxRow = 0; int minCol = rasterProps.Width - 1; int maxCol = 0; for (int i = 0; i < edits.Count; i++) { #region Get the extent of the edition region Position cellPos = edits[i].Position; if (cellPos.Row > maxRow) { maxRow = cellPos.Row; } if (cellPos.Row < minRow) { minRow = cellPos.Row; } if (cellPos.Column > maxCol) { maxCol = cellPos.Column; } if (cellPos.Column < minCol) { minCol = cellPos.Column; } #endregion } IPnt pos = new PntClass(); pos.SetCoords(maxCol - minCol + 1, maxRow - minRow + 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(pos); pos.SetCoords(minCol, minRow); raster.Read(pos, pixelBlock); // Set new values IPixelBlock3 pixelBlock3 = (IPixelBlock3)pixelBlock; Array pixels = (Array)pixelBlock3.get_PixelData(0); for (int i = 0; i < edits.Count; i++) { object value = null; Raster.CSharpValue2PixelValue(edits[i].NewValue, rasterProps.PixelType, out value); pixels.SetValue(value, edits[i].Position.Column - minCol, edits[i].Position.Row - minRow); } pixelBlock3.set_PixelData(0, (System.Object)pixels); IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(pos, (IPixelBlock)pixelBlock3); }
/// <summary> /// Get the pixel values in a region of the input raster. /// </summary> /// <param name="tlCorner"></param> /// <param name="brCorner"></param> /// <param name="raster"></param> /// <returns></returns> public static double[,] GetValues(Position tlCorner, Position brCorner, IRaster raster) { int colCount = brCorner.Column - tlCorner.Column + 1; int rowCount = brCorner.Row - tlCorner.Row + 1; IPnt regionSize = new PntClass(); regionSize.SetCoords(colCount, rowCount); IPixelBlock pixelBlock = raster.CreatePixelBlock(regionSize); IPnt tl = new PntClass(); tl.SetCoords(tlCorner.Column, tlCorner.Row); raster.Read(tl, pixelBlock); double[,] values = new double[colCount, rowCount]; for (int x = 0; x < colCount; x++) { for (int y = 0; y < rowCount; y++) { values[x, y] = Convert.ToDouble(pixelBlock.GetVal(0, x, y)); } } return values; }
/// <summary> /// Write edits to the input raster. /// </summary> /// <param name="raster"></param> private static void WriteEdits(IRaster raster) { IRasterProps rasterProps = (IRasterProps)raster; int minRow = rasterProps.Height - 1; int maxRow = 0; int minCol = rasterProps.Width - 1; int maxCol = 0; for (int i = 0; i < Editor.Edits.Count; i++) { #region Get the extent of the edition region Position cellPos = Editor.Edits[i].Position; if (cellPos.Row > maxRow) { maxRow = cellPos.Row; } if (cellPos.Row < minRow) { minRow = cellPos.Row; } if (cellPos.Column > maxCol) { maxCol = cellPos.Column; } if (cellPos.Column < minCol) { minCol = cellPos.Column; } #endregion } IPnt pos = new PntClass(); pos.SetCoords(maxCol - minCol + 1, maxRow - minRow + 1); IPixelBlock pixelBlock = raster.CreatePixelBlock(pos); pos.SetCoords(minCol, minRow); raster.Read(pos, pixelBlock); // Set new values IPixelBlock3 pixelBlock3 = (IPixelBlock3)pixelBlock; Array pixels = (Array)pixelBlock3.get_PixelData(0); for (int i = 0; i < Editor.Edits.Count; i++) { object value = null; Editor.CSharpValue2PixelValue(Editor.Edits[i].NewValue, rasterProps.PixelType, out value); pixels.SetValue(value, Editor.Edits[i].Position.Column - minCol, Editor.Edits[i].Position.Row - minRow); } pixelBlock3.set_PixelData(0, (System.Object)pixels); IRasterEdit rasterEdit = (IRasterEdit)raster; rasterEdit.Write(pos, (IPixelBlock)pixelBlock3); }
public void ConvertGridMetricsToRaster(string metricsDir, string outDir, int[] metrics) { string[] metricFiles = System.IO.Directory.GetFiles(metricsDir, "*.csv"); string[] headerFiles = System.IO.Directory.GetFiles(metricsDir, "*.txt"); IPnt cellSize; IPnt[] tlPntArr; int[] rwArr; int[] clmArr; float noDataVl; IEnvelope ext = getExtentsFromHeader(headerFiles, out cellSize, out tlPntArr, out rwArr, out clmArr, out noDataVl); IWorkspace outWks = geoUtil.OpenRasterWorkspace(outDir); string exePath = "\"" + fusDir + "\\" + csv2Grid + "\""; IRasterEdit[] rsArr = new IRasterEdit[metrics.Length]; for (int i = 0; i < metrics.Length; i++) { int clm = metrics[i]; string metricName = MetricsArr[clm]; IRasterDataset rsDset = rsUtil.createNewRaster(ext, cellSize, outWks, metricName, 1, rstPixelType.PT_FLOAT, rasterUtil.rasterType.IMAGINE, null);//rsWk2.CreateRasterDataset(metricName+".img","IMAGINE Image",ext.LowerLeft,w,h,cellSize.X,cellSize.Y,1,rstPixelType.PT_FLOAT,null,true); IRasterBand rsB = ((IRasterBandCollection)rsDset).Item(0); IRasterProps rsP = (IRasterProps)rsB; rsP.NoDataValue = noDataVl; IRaster rs = ((IRasterDataset2)rsDset).CreateFullRaster(); rsArr[i] = (IRasterEdit)rs; } foreach (string s in metricFiles) { Console.WriteLine("Working on " + s); int pntIndex = System.Array.IndexOf(metricFiles, s); IPnt tl = tlPntArr[pntIndex]; int cl, rw; ((IRaster2)rsArr[0]).MapToPixel(tl.X, tl.Y, out cl, out rw); IPnt tlp = new PntClass(); tlp.X = cl; tlp.Y = rw; int rws = rwArr[pntIndex]; int clms = clmArr[pntIndex]; IPnt bSize = new PntClass(); bSize.SetCoords(clms, rws); System.Array[] pbSafeArr = new System.Array[metrics.Length]; IPixelBlock3[] pbArr = new IPixelBlock3[metrics.Length]; for (int i = 0; i < metrics.Length; i++) { IRasterEdit rsE = rsArr[i]; IRaster rs = (IRaster)rsE; IPixelBlock3 pb = (IPixelBlock3)rs.CreatePixelBlock(bSize); rs.Read(tlp, (IPixelBlock)pb); //pb.Mask(0); pbArr[i] = pb; System.Array vlArr = (System.Array)pb.get_PixelData(0); pbSafeArr[i] = vlArr; } using (System.IO.StreamReader sr = new System.IO.StreamReader(s)) { string hdr = sr.ReadLine(); while (!sr.EndOfStream) { string ln = sr.ReadLine(); string[] lnArr = ln.Split(new char[] { ',' }); int r = (rws - 1) - System.Convert.ToInt32(lnArr[0]); int c = System.Convert.ToInt32(lnArr[1]); for (int i = 0; i < metrics.Length; i++) { int clIndex = metrics[i]; float clVl = System.Convert.ToSingle(lnArr[clIndex]); if (clVl != noDataVl) { pbSafeArr[i].SetValue(clVl, c, r); } } } sr.Close(); } for (int i = 0; i < metrics.Length; i++) { IPixelBlock3 pb = pbArr[i]; pb.set_PixelData(0, pbSafeArr[i]); rsArr[i].Write(tlp, (IPixelBlock)pb); } } for (int i = 0; i < rsArr.Length; i++) { System.Runtime.InteropServices.Marshal.ReleaseComObject(rsArr[i]); } }