Ejemplo n.º 1
0
        public static InputBand <short> NewShortBand(GdalBand gdalBand,
                                                     PixelBand pixelBand)
        {
            RasterBandReader <short> rasterBandReader = RasterBandReaders.NewShortReader(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.UInt16:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <ushort, short>(pixelBand, Convert.ToUInt16)));

            case TypeCode.Int16:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <short, short>(pixelBand, Convert.ToInt16)));

            case TypeCode.UInt32:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <uint, short>(pixelBand, Convert.ToUInt32)));

            case TypeCode.Int32:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <int, short>(pixelBand, Convert.ToInt32)));

            case TypeCode.Single:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <float, short>(pixelBand, Convert.ToSingle)));

            case TypeCode.Double:
                return(new InputBand <short>(rasterBandReader, new PixelBandSetter <double, short>(pixelBand, Convert.ToDouble)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not ushort, short, uint, int, float, double");
            }
        }
Ejemplo n.º 2
0
        public static OutputBand <double> NewDoubleBand(GdalBand gdalBand,
                                                        PixelBand pixelBand)
        {
            RasterBandWriter <double> rasterBandWriter = RasterBandWriters.NewDoubleWriter(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.Byte:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <byte, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.SByte:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <sbyte, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.UInt16:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <ushort, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.Int16:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <short, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.UInt32:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <uint, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.Int32:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <int, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.Single:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <float, double>(pixelBand, Convert.ToDouble)));

            case TypeCode.Double:
                return(new OutputBand <double>(rasterBandWriter, new PixelBandGetter <double, double>(pixelBand, Convert.ToDouble)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not byte, sbyte, ushort, short, uint, int, float, double");
            }
        }
Ejemplo n.º 3
0
        public static IOutputBand NewOutputBand(DataType dataType,
                                                GdalBand gdalBand,
                                                PixelBand pixelBand)
        {
            switch (dataType)
            {
            case DataType.GDT_Byte:
                return(NewByteBand(gdalBand, pixelBand));

            case DataType.GDT_Int16:
                return(NewShortBand(gdalBand, pixelBand));

            case DataType.GDT_Int32:
                return(NewIntBand(gdalBand, pixelBand));

            case DataType.GDT_Float32:
                return(NewFloatBand(gdalBand, pixelBand));

            case DataType.GDT_Float64:
                return(NewDoubleBand(gdalBand, pixelBand));

            default:
                throw new ArgumentException("dataType is not byte, short, int, float, double");
            }
        }
Ejemplo n.º 4
0
        public void Save(int xoff, int yoff, int buf_xsize, int buf_ysize, double[] buffer)
        {
            try
            {
                OSGeo.GDAL.Gdal.AllRegister();
                _dataSet = OSGeo.GDAL.Gdal.Open(_fileName, OSGeo.GDAL.Access.GA_Update);

                _band1 = _dataSet.GetRasterBand(1);
                CPLErr err1 = _band1.WriteRaster(xoff,
                                                 yoff,
                                                 _resultInfo.Width,
                                                 buf_ysize,
                                                 buffer,
                                                 buf_xsize,
                                                 buf_ysize,
                                                 0,
                                                 0);

                _dataSet.Dispose();
                _band1.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("数据写入失败。" + ex.Message);
            }
        }
Ejemplo n.º 5
0
        public static OutputBand <int> NewIntBand(GdalBand gdalBand,
                                                  PixelBand pixelBand)
        {
            RasterBandWriter <int> rasterBandWriter = RasterBandWriters.NewIntWriter(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.Byte:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <byte, int>(pixelBand, Convert.ToInt32)));

            case TypeCode.SByte:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <sbyte, int>(pixelBand, Convert.ToInt32)));

            case TypeCode.UInt16:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <ushort, int>(pixelBand, Convert.ToInt32)));

            case TypeCode.Int16:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <short, int>(pixelBand, Convert.ToInt32)));

            case TypeCode.UInt32:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <uint, int>(pixelBand, Convert.ToInt32)));

            case TypeCode.Int32:
                return(new OutputBand <int>(rasterBandWriter, new PixelBandGetter <int, int>(pixelBand, Convert.ToInt32)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not byte, sbyte, ushort, short, uint, int");
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// 数据保存
        /// </summary>
        public void Save()
        {
            try
            {
                OSGeo.GDAL.Gdal.AllRegister();
                _dataSet = OSGeo.GDAL.Gdal.Open(_fileName, OSGeo.GDAL.Access.GA_Update);

                _band1 = _dataSet.GetRasterBand(1);
                CPLErr err1 = _band1.WriteRaster(0,
                                                 0,
                                                 _resultInfo.Width,
                                                 _resultInfo.Height,
                                                 _pixels1,
                                                 _resultInfo.Width,
                                                 _resultInfo.Height,
                                                 0,
                                                 0);

                _dataSet.Dispose();
                _band1.Dispose();
            }
            catch (Exception ex)
            {
                throw new Exception("数据写入失败。" + ex.Message);
            }
        }
Ejemplo n.º 7
0
 /// <summary>
 /// 和GetData功能相同,但是使用GDAL直接从文件中读取数据。
 /// </summary>
 /// <param name="fileName">文件名字</param>
 /// <param name="width">ref用于返回数据的宽度</param>
 /// <param name="height">ref用于返回数据的高度</param>
 /// <returns>一维数据数组,按行优先</returns>
 private double[] GdalGetData(string fileName, ref int width, ref int height)
 {
     OSGeo.GDAL.Dataset dataset = OSGeo.GDAL.Gdal.Open(fileName, OSGeo.GDAL.Access.GA_ReadOnly);
     width  = dataset.RasterXSize;
     height = dataset.RasterYSize;
     double[]        imageBuffer = new double[width * height];
     OSGeo.GDAL.Band b           = dataset.GetRasterBand(1);
     b.ReadRaster(0, 0, width, height, imageBuffer, width, height, 0, 0);
     return(imageBuffer);
 }
Ejemplo n.º 8
0
 public static HandleRef getCPtrAndSetReference(Band obj, object parent) {
   if (obj != null)
   {
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
Ejemplo n.º 9
0
 public static HandleRef getCPtrAndDisown(Band obj, object parent) {
   if (obj != null)
   {
     obj.swigCMemOwn = false;
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
Ejemplo n.º 10
0
        public static InputBand <double> NewDoubleBand(GdalBand gdalBand,
                                                       PixelBand pixelBand)
        {
            RasterBandReader <double> rasterBandReader = RasterBandReaders.NewDoubleReader(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.Double:
                return(new InputBand <double>(rasterBandReader, new PixelBandSetter <double, double>(pixelBand, Convert.ToDouble)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not double");
            }
        }
Ejemplo n.º 11
0
        private static unsafe IntPtr ApplyContrastEnhancement(OSGeo.GDAL.Band rasterBand, IntPtr data, int minCutValue, int maxCutValue)
        {
            Action <int> action;

            // Select appropriate datatype
            if (rasterBand.DataType == DataType.GDT_UInt16)
            {
                action = (index) =>
                {
                    ushort *dataPtr = (ushort *)data.ToPointer();
                    ushort  current = *(dataPtr + index);
                    *(dataPtr + index) = (ushort)MoreMath.Clamp((current - minCutValue) / (double)(maxCutValue - minCutValue) * ushort.MaxValue, 0, ushort.MaxValue);
                };
            }
            else if (rasterBand.DataType == DataType.GDT_Int16)
            {
                action = (index) =>
                {
                    short *dataPtr = (short *)data.ToPointer();
                    short  current = *(dataPtr + index);
                    *(dataPtr + index) = (short)MoreMath.Clamp((current - minCutValue) / (double)(maxCutValue - minCutValue) * short.MaxValue, 0, short.MaxValue);
                };
            }
            else if (rasterBand.DataType == DataType.GDT_Float32)
            {
                action = (index) =>
                {
                    float *dataPtr = (float *)data.ToPointer();
                    float  current = *(dataPtr + index);

                    *(dataPtr + index) = (float)MoreMath.Clamp((current - minCutValue) / (double)(maxCutValue - minCutValue) * 1.0f, 0.0f, 1.0f);
                };
            }
            else
            {
                throw new InvalidOperationException();
            }

            // Execute contrast enhancement
            Parallel.ForEach(Partitioner.Create(0, rasterBand.XSize * rasterBand.YSize), (range) =>
            {
                for (int dataIndex = range.Item1; dataIndex < range.Item2; ++dataIndex)
                {
                    action(dataIndex);
                }
            });

            return(data);
        }
Ejemplo n.º 12
0
        public static OutputBand <byte> NewByteBand(GdalBand gdalBand,
                                                    PixelBand pixelBand)
        {
            RasterBandWriter <byte> rasterBandWriter = RasterBandWriters.NewByteWriter(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.Byte:
                return(new OutputBand <byte>(rasterBandWriter, new PixelBandGetter <byte, byte>(pixelBand, Convert.ToByte)));

            case TypeCode.SByte:
                return(new OutputBand <byte>(rasterBandWriter, new PixelBandGetter <sbyte, byte>(pixelBand, Convert.ToByte)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not byte or sbyte");
            }
        }
Ejemplo n.º 13
0
        public static InputBand <float> NewFloatBand(GdalBand gdalBand,
                                                     PixelBand pixelBand)
        {
            RasterBandReader <float> rasterBandReader = RasterBandReaders.NewFloatReader(gdalBand);

            switch (pixelBand.TypeCode)
            {
            case TypeCode.Single:
                return(new InputBand <float>(rasterBandReader, new PixelBandSetter <float, float>(pixelBand, Convert.ToSingle)));

            case TypeCode.Double:
                return(new InputBand <float>(rasterBandReader, new PixelBandSetter <double, float>(pixelBand, Convert.ToDouble)));

            default:
                throw new ArgumentException("pixelBand.TypeCode is not float or double");
            }
        }
Ejemplo n.º 14
0
        private static void CalculateMinMaxCut(OSGeo.GDAL.Band rasterBand, double minPercentage, double maxPercentage, out int minCutValue, out int maxCutValue)
        {
            double[] minMax = new double[2];
            rasterBand.ComputeRasterMinMax(minMax, 0);
            int min = (int)minMax[0];
            int max = (int)minMax[1];

            int[] histogram = new int[max - min];
            rasterBand.GetHistogram(min, max, max - min, histogram, 1, 0, ProgressFunc, "");

            int totalPixels = 0;

            for (int bucket = 0; bucket < histogram.Length; ++bucket)
            {
                totalPixels += histogram[bucket];
            }

            double minCut = totalPixels * minPercentage;

            minCutValue = int.MaxValue;
            bool minCutSet = false;

            double maxCut = totalPixels * maxPercentage;

            maxCutValue = 0;
            bool maxCutSet = false;

            int pixelCount = 0;

            for (int bucket = 0; bucket < histogram.Length; ++bucket)
            {
                pixelCount += histogram[bucket];
                if (pixelCount >= minCut && !minCutSet)
                {
                    minCutValue = bucket + min;
                    minCutSet   = true;
                }
                if (pixelCount >= maxCut && !maxCutSet)
                {
                    maxCutValue = bucket + min;
                    maxCutSet   = true;
                }
            }
        }
Ejemplo n.º 15
0
        ///// <summary>
        ///// 根据栅格图层名字返回栅格图层数据数组
        ///// </summary>
        ///// <param name="layerName">图层名字</param>
        ///// <param name="width">ref类型,数据的宽度</param>
        ///// <param name="height">ref类型,数据的高度</param>
        ///// <returns>数据数组,按行优先</returns>
        //private double[] GetData(string layerName, ref int width, ref int height)
        //{
        //    var map = GIS.FrameWork.Application.App.Map;
        //    var layers = map.Layers;
        //    ILayer selectedLayer = null;
        //    for (int i = 0; i < layers.Count; i++)
        //    {
        //        var layer = layers[i];
        //        if (layer.LegendText == layerName)
        //        {
        //            selectedLayer = layer;
        //            break;
        //        }
        //    }

        //    if (selectedLayer == null)
        //    {
        //        return null; // 图层名无效
        //    }

        //    try
        //    {
        //        RasterLayer rasterLayer = selectedLayer as RasterLayer;
        //        IRaster rasterDataSet = rasterLayer.DataSet;
        //        Dataset dataset = GIS.GDAL.RasterConverter.Ds2GdalRaster(rasterDataSet, null, new int[] { 1 });
        //        width = dataset.RasterXSize;
        //        height = dataset.RasterYSize;
        //        double[] imageBuffer = new double[width * height];
        //        Band band = dataset.GetRasterBand(1);
        //        band.ReadRaster(0, 0, width, height, imageBuffer, width, height, 0, 0);
        //        return imageBuffer;
        //    }
        //    catch
        //    {
        //        return null; // 图层不是栅格图层或将图层转化为GDAL dataset失败或从GDAL dataset中读取数据失败
        //    }
        //}



        /// <summary>
        /// 和GetData功能相同,但是使用GDAL直接从文件中读取数据。
        /// 获取空间参照信息
        /// </summary>
        /// <param name="fileName">文件名字</param>
        /// <param name="width">ref用于返回数据的宽度</param>
        /// <param name="height">ref用于返回数据的高度</param>
        /// <returns>一维数据数组,按行优先</returns>
        protected double[] GdalGetData(string fileName, ref int width, ref int height)
        {
            OSGeo.GDAL.Dataset dataset = OSGeo.GDAL.Gdal.Open(fileName, OSGeo.GDAL.Access.GA_ReadOnly);
            width             = dataset.RasterXSize;
            height            = dataset.RasterYSize;
            this.geoTransform = new double[6];

            dataset.GetGeoTransform(geoTransform);
            this.projStr  = dataset.GetProjection();
            this.tiffType = dataset.GetType();

            double[]        imageBuffer = new double[width * height];
            OSGeo.GDAL.Band b           = dataset.GetRasterBand(1);
            b.ReadRaster(0, 0, width, height, imageBuffer, width, height, 0, 0);
            double noDataVal;
            int    hasVal;

            b.GetNoDataValue(out noDataVal, out hasVal);
            this.noDataVal = noDataVal;
            return(imageBuffer);
        }
Ejemplo n.º 16
0
 /// <summary>
 /// Gets the dimensions of the original (0) plus any overlays.
 /// The overlays get smaller as the index gets larger..
 /// </summary>
 /// <returns></returns>
 public Size[] GetSizes()
 {
     EnsureDatasetOpen();
     _red = _dataset.GetRasterBand(1);
     int numOverviews = _red.GetOverviewCount();
     Debug.WriteLine("Num overviews:" + numOverviews);
     if (numOverviews == 0) return null;
     Size[] result = new Size[numOverviews + 1];
     result[0] = new Size(_red.XSize, _red.YSize);
     for (int i = 0; i < numOverviews; i++)
     {
         Band temp = _red.GetOverview(i);
         result[i + 1] = new Size(temp.XSize, temp.YSize);
     }
     return result;
 }
Ejemplo n.º 17
0
        /// <summary>
        /// Attempts to open the specified file.
        /// </summary>
        public override void Open()
        {
            try
            {
                _dataset = Gdal.Open(Filename, Access.GA_Update);
            }
            catch
            {
                try
                {
                    _dataset = Gdal.Open(Filename, Access.GA_ReadOnly);
                }
                catch (Exception ex)
                {
                    throw new GdalException(ex.ToString());
                }
            }

            _red = _dataset.GetRasterBand(1);
            if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
            {
                ReadPaletteBuffered();
            }
            if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
            {
                ReadGrayIndex();
            }
            if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_RedBand)
            {
                ReadRGB();
            }
            if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_AlphaBand)
            {
                ReadARGB();
            }


        }
Ejemplo n.º 18
0
        private void ReadARGB()
        {
            if (_dataset.RasterCount < 4)
            {
                throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _alpha = _red;
            _red = _dataset.GetRasterBand(2);
            _green = _dataset.GetRasterBand(3);
            _blue = _dataset.GetRasterBand(4);

            Width = _red.XSize;
            Height = _red.YSize;

            _image = new Bitmap(Width, Height, PixelFormat.Format32bppRgb);

            byte[] a = new byte[Width * Height];
            byte[] r = new byte[Width * Height];
            byte[] g = new byte[Width * Height];
            byte[] b = new byte[Width * Height];

            
            _alpha.ReadRaster(0, 0, Width, Height, a, Width, Height, 0, 0);
            _red.ReadRaster(0, 0, Width, Height, r, Width, Height, 0, 0);
            _green.ReadRaster(0, 0, Width, Height, g, Width, Height, 0, 0);
            _blue.ReadRaster(0, 0, Width, Height, b, Width, Height, 0, 0);

            BitmapData bData = _image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            Stride = bData.Stride;
            _image.UnlockBits(bData);
            Values = new byte[Width * Height * 4];
            BytesPerPixel = 4;
            for (int row = 0; row < Height; row++)
            {
                for (int col = 0; col < Width; col++)
                {
                    Values[row * Stride + col * BytesPerPixel] = b[row * Width + col];
                    Values[row * Stride + col * BytesPerPixel + 1] = g[row * Width + col];
                    Values[row * Stride + col * BytesPerPixel + 2] = r[row * Width + col];
                    Values[row * Stride + col * BytesPerPixel + 3] = a[row * Width + col];
                }
            }
            WriteBytes();
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Attempts to open the specified file into memory.
        /// </summary>
        public override void Open()
        {
            try
            {
                _dataset = Gdal.Open(Filename, Access.GA_Update);
            }
            catch
            {
                try
                {
                    _dataset = Gdal.Open(Filename, Access.GA_ReadOnly);
                }
                catch (Exception ex)
                {
                    throw new GdalException(ex.ToString());
                }
            }
            int numBands = _dataset.RasterCount;
            _red = _dataset.GetRasterBand(1);
            this.BandType = ImageBandType.RGB;
            for (int i = 1; i <= numBands; i++)
            {
                Band tempBand = _dataset.GetRasterBand(i);
                if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
                {
                    this.BandType = ImageBandType.Gray;
                    _red = tempBand;
                }
                if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
                {
                    this.BandType = ImageBandType.PalletCoded;
                    _red = tempBand;
                }

                if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_RedBand)
                {
                    _red = tempBand;
                }
                if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_AlphaBand)
                {
                    _alpha = tempBand;
                    this.BandType = ImageBandType.ARGB;
                }
                else if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand)
                {
                    _blue = tempBand;
                }
                else if (tempBand.GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand)
                {
                    _green = tempBand;
                }
            }
            /*
            if (this.BandType == ImageBandType.PalletCoded)
            {
                ReadPaletteBuffered();
            }
            else if (this.BandType == ImageBandType.Gray)
            {
                ReadGrayIndex();
            }
            else if (this.BandType == ImageBandType.ARGB)
            {
                ReadArgb();
            }
            else if (this.BandType == ImageBandType.RGB)
            {
                ReadRgb();
            }*/
        }
Ejemplo n.º 20
0
        protected virtual void GetPreview(Dataset dataset, Size size, Graphics g,
                                          BoundingBox displayBbox, ProjectionInfo mapProjection, Map map)
#endif
        {
            double[] geoTrans = new double[6];
            _gdalDataset.GetGeoTransform(geoTrans);

            // not rotated, use faster display method
            if ((!_useRotation ||
                 (geoTrans[1] == 1 && geoTrans[2] == 0 && geoTrans[4] == 0 && Math.Abs(geoTrans[5]) == 1))
                && !_haveSpot && _transform == null)
            {
                GetNonRotatedPreview(dataset, size, g, displayBbox, mapProjection);
                return;
            }
            // not rotated, but has spot...need default rotation
            else if ((geoTrans[0] == 0 && geoTrans[3] == 0) && _haveSpot)
                geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 };

            _geoTransform = new GeoTransform(geoTrans);
            double DsWidth = _imagesize.Width;
            double DsHeight = _imagesize.Height;
            double left, top, right, bottom;
            double GndX = 0, GndY = 0, ImgX = 0, ImgY = 0, PixX, PixY;
            double[] intVal = new double[Bands];
            double imageVal = 0, SpotVal = 0;
            double bitScalar = 1.0;
            Bitmap bitmap = null;
            Point bitmapTL = new Point(), bitmapBR = new Point();
            Geometries.Point imageTL = new Geometries.Point(), imageBR = new Geometries.Point();
            BoundingBox shownImageBbox, trueImageBbox;
            int bitmapLength, bitmapHeight;
            int displayImageLength, displayImageHeight;

            int iPixelSize = 3; //Format24bppRgb = byte[b,g,r] 

            if (dataset != null)
            {
                //check if image is in bounding box
                if ((displayBbox.Left > _envelope.Right) || (displayBbox.Right < _envelope.Left)
                    || (displayBbox.Top < _envelope.Bottom) || (displayBbox.Bottom > _envelope.Top))
                    return;

                // init histo
                _histogram = new List<int[]>();
                for (int i = 0; i < _lbands + 1; i++)
                    _histogram.Add(new int[256]);

                // bounds of section of image to be displayed
                left = Math.Max(displayBbox.Left, _envelope.Left);
                top = Math.Min(displayBbox.Top, _envelope.Top);
                right = Math.Min(displayBbox.Right, _envelope.Right);
                bottom = Math.Max(displayBbox.Bottom, _envelope.Bottom);

                trueImageBbox = new BoundingBox(left, bottom, right, top);

                // put display bounds into current projection
                if (_transform != null)
                {
#if !DotSpatialProjections
                    _transform.MathTransform.Invert();
                    shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.MathTransform);
                    _transform.MathTransform.Invert();
#else
                    shownImageBbox = GeometryTransform.TransformBox(trueImageBbox, _transform.Source, _transform.Target);
#endif
                }
                else
                    shownImageBbox = trueImageBbox;

                // find min/max x and y pixels needed from image
                imageBR.X =
                    (int)
                    (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft).X,
                              Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight).X,
                                       Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft).X,
                                                _geoTransform.GroundToImage(shownImageBbox.BottomRight).X))) + 1);
                imageBR.Y =
                    (int)
                    (Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopLeft).Y,
                              Math.Max(_geoTransform.GroundToImage(shownImageBbox.TopRight).Y,
                                       Math.Max(_geoTransform.GroundToImage(shownImageBbox.BottomLeft).Y,
                                                _geoTransform.GroundToImage(shownImageBbox.BottomRight).Y))) + 1);
                imageTL.X =
                    (int)
                    Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft).X,
                             Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight).X,
                                      Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft).X,
                                               _geoTransform.GroundToImage(shownImageBbox.BottomRight).X)));
                imageTL.Y =
                    (int)
                    Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopLeft).Y,
                             Math.Min(_geoTransform.GroundToImage(shownImageBbox.TopRight).Y,
                                      Math.Min(_geoTransform.GroundToImage(shownImageBbox.BottomLeft).Y,
                                               _geoTransform.GroundToImage(shownImageBbox.BottomRight).Y)));

                // stay within image
                if (imageBR.X > _imagesize.Width)
                    imageBR.X = _imagesize.Width;
                if (imageBR.Y > _imagesize.Height)
                    imageBR.Y = _imagesize.Height;
                if (imageTL.Y < 0)
                    imageTL.Y = 0;
                if (imageTL.X < 0)
                    imageTL.X = 0;

                displayImageLength = (int)(imageBR.X - imageTL.X);
                displayImageHeight = (int)(imageBR.Y - imageTL.Y);

                // find ground coordinates of image pixels
                Geometries.Point groundBR = _geoTransform.ImageToGround(imageBR);
                Geometries.Point groundTL = _geoTransform.ImageToGround(imageTL);

                // convert ground coordinates to map coordinates to figure out where to place the bitmap
                bitmapBR = new Point((int)map.WorldToImage(trueImageBbox.BottomRight).X + 1,
                                     (int)map.WorldToImage(trueImageBbox.BottomRight).Y + 1);
                bitmapTL = new Point((int)map.WorldToImage(trueImageBbox.TopLeft).X,
                                     (int)map.WorldToImage(trueImageBbox.TopLeft).Y);

                bitmapLength = bitmapBR.X - bitmapTL.X;
                bitmapHeight = bitmapBR.Y - bitmapTL.Y;

                // check to see if image is on its side
                if (bitmapLength > bitmapHeight && displayImageLength < displayImageHeight)
                {
                    displayImageLength = bitmapHeight;
                    displayImageHeight = bitmapLength;
                }
                else
                {
                    displayImageLength = bitmapLength;
                    displayImageHeight = bitmapHeight;
                }

                // scale
                if (_bitDepth == 12)
                    bitScalar = 16.0;
                else if (_bitDepth == 16)
                    bitScalar = 256.0;
                else if (_bitDepth == 32)
                    bitScalar = 16777216.0;

                // 0 pixels in length or height, nothing to display
                if (bitmapLength < 1 || bitmapHeight < 1)
                    return;

                //initialize bitmap
                bitmap = new Bitmap(bitmapLength, bitmapHeight, PixelFormat.Format24bppRgb);
                BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmapLength, bitmapHeight),
                                                        ImageLockMode.ReadWrite, bitmap.PixelFormat);

                try
                {
                    unsafe
                    {
                        // turn everything to _noDataInitColor, so we can make fill transparent
                        byte cr = _noDataInitColor.R;
                        byte cg = _noDataInitColor.G;
                        byte cb = _noDataInitColor.B;

                        for (int y = 0; y < bitmapHeight; y++)
                        {
                            byte* brow = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
                            for (int x = 0; x < bitmapLength; x++)
                            {
                                Int32 offsetX = x * 3;
                                brow[offsetX++] = cb;
                                brow[offsetX++] = cg;
                                brow[offsetX] = cr;
                            }
                        }

                        // create 3 dimensional buffer [band][x pixel][y pixel]
                        double[][] tempBuffer = new double[Bands][];
                        double[][][] buffer = new double[Bands][][];
                        for (int i = 0; i < Bands; i++)
                        {
                            buffer[i] = new double[displayImageLength][];
                            for (int j = 0; j < displayImageLength; j++)
                                buffer[i][j] = new double[displayImageHeight];
                        }

                        Band[] band = new Band[Bands];
                        int[] ch = new int[Bands];

                        //
                        Double[] noDataValues = new Double[Bands];
                        Double[] scales = new Double[Bands];
                        ColorTable colorTable = null;


                        // get data from image
                        for (int i = 0; i < Bands; i++)
                        {
                            tempBuffer[i] = new double[displayImageLength * displayImageHeight];
                            band[i] = dataset.GetRasterBand(i + 1);

                            //get nodata value if present
                            Int32 hasVal = 0;
                            band[i].GetNoDataValue(out noDataValues[i], out hasVal);
                            if (hasVal == 0) noDataValues[i] = Double.NaN;
                            band[i].GetScale(out scales[i], out hasVal);
                            if (hasVal == 0) scales[i] = 1.0;

                            band[i].ReadRaster(
                                (int)imageTL.X,
                                (int)imageTL.Y,
                                (int)(imageBR.X - imageTL.X),
                                (int)(imageBR.Y - imageTL.Y),
                                tempBuffer[i], displayImageLength, displayImageHeight, 0, 0);

                            // parse temp buffer into the image x y value buffer
                            long pos = 0;
                            for (int y = 0; y < displayImageHeight; y++)
                            {
                                for (int x = 0; x < displayImageLength; x++, pos++)
                                    buffer[i][x][y] = tempBuffer[i][pos];
                            }

                            if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand) ch[i] = 1;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) ch[i] = 2;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_Undefined)
                            {
                                if (Bands > 1)
                                    ch[i] = 3; // infrared
                                else
                                {
                                    ch[i] = 4;
                                    if (_colorBlend == null)
                                    {
                                        Double dblMin, dblMax;
                                        band[i].GetMinimum(out dblMin, out hasVal);
                                        if (hasVal == 0) dblMin = Double.NaN;
                                        band[i].GetMaximum(out dblMax, out hasVal);
                                        if (hasVal == 0) dblMax = double.NaN;
                                        if (Double.IsNaN(dblMin) || Double.IsNaN(dblMax))
                                        {
                                            double dblMean, dblStdDev;
                                            band[i].GetStatistics(0, 1, out dblMin, out dblMax, out dblMean, out dblStdDev);
                                            //double dblRange = dblMax - dblMin;
                                            //dblMin -= 0.1*dblRange;
                                            //dblMax += 0.1*dblRange;
                                        }
                                        Single[] minmax = new float[] { Convert.ToSingle(dblMin), 0.5f * Convert.ToSingle(dblMin + dblMax), Convert.ToSingle(dblMax) };
                                        Color[] colors = new Color[] { Color.Blue, Color.Yellow, Color.Red };
                                        _colorBlend = new ColorBlend(colors, minmax);
                                    }
                                    intVal = new Double[3];
                                }
                            }
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 0;
                            else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
                            {
                                colorTable = band[i].GetRasterColorTable();
                                ch[i] = 5;
                                intVal = new Double[3];
                            }
                            else ch[i] = -1;
                        }

                        // store these values to keep from having to make slow method calls
                        int bitmapTLX = bitmapTL.X;
                        int bitmapTLY = bitmapTL.Y;
                        double imageTop = imageTL.Y;
                        double imageLeft = imageTL.X;
                        double dblMapPixelWidth = map.PixelWidth;
                        double dblMapPixelHeight = map.PixelHeight;
                        double dblMapMinX = map.Envelope.Min.X;
                        double dblMapMaxY = map.Envelope.Max.Y;
                        double geoTop, geoLeft, geoHorzPixRes, geoVertPixRes, geoXRot, geoYRot;

                        // get inverse values
                        geoTop = _geoTransform.Inverse[3];
                        geoLeft = _geoTransform.Inverse[0];
                        geoHorzPixRes = _geoTransform.Inverse[1];
                        geoVertPixRes = _geoTransform.Inverse[5];
                        geoXRot = _geoTransform.Inverse[2];
                        geoYRot = _geoTransform.Inverse[4];

                        double dblXScale = (imageBR.X - imageTL.X) / (displayImageLength - 1);
                        double dblYScale = (imageBR.Y - imageTL.Y) / (displayImageHeight - 1);
                        double[] dblPoint;

                        // get inverse transform  
                        // NOTE: calling transform.MathTransform.Inverse() once and storing it
                        // is much faster than having to call every time it is needed
#if !DotSpatialProjections
                        IMathTransform inverseTransform = null;
                        if (_transform != null)
                            inverseTransform = _transform.MathTransform.Inverse();
#endif

                        for (PixY = 0; PixY < bitmapBR.Y - bitmapTL.Y; PixY++)
                        {
                            byte* row = (byte*)bitmapData.Scan0 + ((int)Math.Round(PixY) * bitmapData.Stride);

                            for (PixX = 0; PixX < bitmapBR.X - bitmapTL.X; PixX++)
                            {
                                // same as Map.ImageToGround(), but much faster using stored values...rather than called each time
                                GndX = dblMapMinX + (PixX + bitmapTLX) * dblMapPixelWidth;
                                GndY = dblMapMaxY - (PixY + bitmapTLY) * dblMapPixelHeight;

                                // transform ground point if needed
                                if (_transform != null)
                                {
#if !DotSpatialProjections
                                    dblPoint = inverseTransform.Transform(new[] { GndX, GndY });
#else
                                    dblPoint = new double[] { GndX, GndY };
                                    Reproject.ReprojectPoints(dblPoint, null, _transform.Source, _transform.Target, 0, 1);
#endif
                                    GndX = dblPoint[0];
                                    GndY = dblPoint[1];
                                }

                                // same as GeoTransform.GroundToImage(), but much faster using stored values...
                                ImgX = (geoLeft + geoHorzPixRes * GndX + geoXRot * GndY);
                                ImgY = (geoTop + geoYRot * GndX + geoVertPixRes * GndY);

                                if (ImgX < imageTL.X || ImgX > imageBR.X || ImgY < imageTL.Y || ImgY > imageBR.Y)
                                    continue;

                                // color correction
                                for (int i = 0; i < Bands; i++)
                                {
                                    intVal[i] =
                                        buffer[i][(int)((ImgX - imageLeft) / dblXScale)][
                                            (int)((ImgY - imageTop) / dblYScale)];

                                    imageVal = SpotVal = intVal[i] = intVal[i] / bitScalar;
                                    if (ch[i] == 4)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            Color color = _colorBlend.GetColor(Convert.ToSingle(imageVal));
                                            intVal[0] = color.B;
                                            intVal[1] = color.G;
                                            intVal[2] = color.R;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else if (ch[i] == 5 && colorTable != null)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            ColorEntry ce = colorTable.GetColorEntry(Convert.ToInt32(imageVal));
                                            intVal[0] = ce.c3;
                                            intVal[1] = ce.c2;
                                            intVal[2] = ce.c1;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else
                                    {

                                        if (_colorCorrect)
                                        {
                                            intVal[i] = ApplyColorCorrection(imageVal, SpotVal, ch[i], GndX, GndY);

                                            // if pixel is within ground boundary, add its value to the histogram
                                            if (ch[i] != -1 && intVal[i] > 0 && (_histoBounds.Bottom >= (int)GndY) &&
                                                _histoBounds.Top <= (int)GndY &&
                                                _histoBounds.Left <= (int)GndX && _histoBounds.Right >= (int)GndX)
                                            {
                                                _histogram[ch[i]][(int)intVal[i]]++;
                                            }
                                        }

                                        if (intVal[i] > 255)
                                            intVal[i] = 255;
                                    }
                                }

                                // luminosity
                                if (_lbands >= 3)
                                    _histogram[_lbands][(int)(intVal[2] * 0.2126 + intVal[1] * 0.7152 + intVal[0] * 0.0722)]
                                        ++;

                                WritePixel(PixX, intVal, iPixelSize, ch, row);
                            }
                        }
                    }
                }

                finally
                {
                    bitmap.UnlockBits(bitmapData);
                }
            }
            bitmap.MakeTransparent(_noDataInitColor);
            if (_transparentColor != Color.Empty)
                bitmap.MakeTransparent(_transparentColor);
            g.DrawImage(bitmap, new Point(bitmapTL.X, bitmapTL.Y));
        }
Ejemplo n.º 21
0
 private static void WritePaletteBuffered(Bitmap value, int xOffset, int yOffset, Band first)
 {
     ColorTable ct = first.GetRasterColorTable();
     if (ct == null)
     {
         throw new GdalException("Image was stored with a palette interpretation but has no color table.");
     }
     if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
     {
         throw new GdalException("Only RGB palette interpretation is currently supported by this " +
                                 " plug-in, " + ct.GetPaletteInterpretation() + " is not supported.");
     }
     int width = value.Width;
     int height = value.Height;
     BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height),
                                       ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
     int stride = Math.Abs(bData.Stride);
     byte[] r = new byte[stride * height];
     Marshal.Copy(bData.Scan0, r, 0, r.Length);
     value.UnlockBits(bData);
     byte[] vals = new byte[width * height];
     byte[][] colorTable = new byte[ct.GetCount()][];
     for (int i = 0; i < ct.GetCount(); i++)
     {
         ColorEntry ce = ct.GetColorEntry(i);
         colorTable[i] = new[]
                             {
                                 (byte) ce.c3, (byte) ce.c2, (byte) ce.c1,
                                 (byte) ce.c4
                             };
     }
     for (int row = 0; row < height; row++)
     {
         for (int col = 0; col < width; col++)
         {
             vals[row * width + col] = MatchColor(r, row * stride + col * 4, colorTable);
         }
     }
     first.WriteRaster(xOffset, yOffset, width, height, vals, width, height, 0, 0);
 }
Ejemplo n.º 22
0
        private byte[] ReadArgb(int startRow, int startColumn, int numRows, int numColumns, int overview)
        {
            if (_dataset.RasterCount < 4)
            {
                throw new GdalException("ARGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _alpha = _red;
            _red = _dataset.GetRasterBand(2);
            _green = _dataset.GetRasterBand(3);
            _blue = _dataset.GetRasterBand(4);

            if (overview > 0)
            {
                _red = _red.GetOverview(overview - 1);
                _alpha = _alpha.GetOverview(overview - 1);
                _green = _green.GetOverview(overview - 1);
                _blue = _blue.GetOverview(overview - 1);
            }

            int width = numColumns;
            int height = numRows;
            byte[] a = new byte[width * height];
            byte[] r = new byte[width * height];
            byte[] g = new byte[width * height];
            byte[] b = new byte[width * height];

            _alpha.ReadRaster(startColumn, startRow, width, height, a, width, height, 0, 0);
            _red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
            _green.ReadRaster(startColumn, startRow, width, height, g, width, height, 0, 0);
            _blue.ReadRaster(startColumn, startRow, width, height, b, width, height, 0, 0);

            byte[] vals = new byte[width * height * 4];
            const int bpp = 4;
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    vals[row * width * bpp + col * bpp] = b[row * width + col];
                    vals[row * width * bpp + col * bpp + 1] = g[row * width + col];
                    vals[row * width * bpp + col * bpp + 2] = r[row * width + col];
                    vals[row * width * bpp + col * bpp + 3] = a[row * width + col];
                }
            }
            return vals;
        }
Ejemplo n.º 23
0
        public static int DitherRGB2PCT(Band red, Band green, Band blue, Band target, ColorTable colors, Gdal.GDALProgressFuncDelegate callback, string callback_data)
        {
            int ret = GdalPINVOKE.DitherRGB2PCT(Band.getCPtr(red), Band.getCPtr(green), Band.getCPtr(blue), Band.getCPtr(target), ColorTable.getCPtr(colors), callback, callback_data);

            if (GdalPINVOKE.SWIGPendingException.Pending)
            {
                throw GdalPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 24
0
        public static int ComputeMedianCutPCT(Band red, Band green, Band blue, int num_colors, ColorTable colors, Gdal.GDALProgressFuncDelegate callback, string callback_data)
        {
            int ret = GdalPINVOKE.ComputeMedianCutPCT(Band.getCPtr(red), Band.getCPtr(green), Band.getCPtr(blue), num_colors, ColorTable.getCPtr(colors), callback, callback_data);

            if (GdalPINVOKE.SWIGPendingException.Pending)
            {
                throw GdalPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 25
0
        public static int SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness, string[] options, Gdal.GDALProgressFuncDelegate callback, string callback_data)
        {
            int ret = GdalPINVOKE.SieveFilter(Band.getCPtr(srcBand), Band.getCPtr(maskBand), Band.getCPtr(dstBand), threshold, connectedness, (options != null)? new GdalPINVOKE.StringListMarshal(options)._ar : null, callback, callback_data);

            if (GdalPINVOKE.SWIGPendingException.Pending)
            {
                throw GdalPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 26
0
 public static int RegenerateOverview(Band srcBand, Band overviewBand, string resampling, Gdal.GDALProgressFuncDelegate callback, string callback_data)
 {
     int ret = GdalPINVOKE.RegenerateOverview(Band.getCPtr(srcBand), Band.getCPtr(overviewBand), resampling, callback, callback_data);
     if (GdalPINVOKE.SWIGPendingException.Pending) throw GdalPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Ejemplo n.º 27
0
 public static int RegenerateOverviews(Band srcBand, int overviewBandCount, SWIGTYPE_p_p_GDALRasterBandShadow overviewBands, string resampling, Gdal.GDALProgressFuncDelegate callback, string callback_data)
 {
     int ret = GdalPINVOKE.RegenerateOverviews(Band.getCPtr(srcBand), overviewBandCount, SWIGTYPE_p_p_GDALRasterBandShadow.getCPtr(overviewBands), resampling, callback, callback_data);
     if (GdalPINVOKE.SWIGPendingException.Pending) throw GdalPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Ejemplo n.º 28
0
 /// <summary>
 /// Returns ARGB 32 bpp regardless of the fact that the original is palette buffered.
 /// </summary>
 private byte[] ReadPaletteBuffered(int startRow, int startColumn, int numRows, int numColumns, int overview)
 {
     ColorTable ct = _red.GetRasterColorTable();
     if (ct == null)
     {
         throw new GdalException("Image was stored with a palette interpretation but has no color table.");
     }
     if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
     {
         throw new GdalException("Only RGB palette interpreation is currently supported by this plugin, " + ct.GetPaletteInterpretation() + " is not supported.");
     }
     int width = numRows;
     int height = numColumns;
     byte[] r = new byte[width * height];
     _red.ReadRaster(startColumn, startRow, numColumns, numRows, r, width, height, 0, 0);
     if (overview > 0)
     {
         _red = _red.GetOverview(overview - 1);
     }
     const int bpp = 4;
     byte[] vals = new byte[width * height * 4];
     byte[][] colorTable = new byte[256][];
     for (int i = 0; i < 255; i++)
     {
         ColorEntry ce = ct.GetColorEntry(i);
         colorTable[i] = new[] { (byte)ce.c3, (byte)ce.c2, (byte)ce.c1, (byte)ce.c4 };
     }
     for (int row = 0; row < height; row++)
     {
         for (int col = 0; col < width; col++)
         {
             Array.Copy(colorTable[r[col + row * width]], 0, vals, row * width + col * bpp, 4);
         }
     }
     return vals;
 }
Ejemplo n.º 29
0
        private static void WriteGrayIndex(Bitmap value, int xOffset, int yOffset, Band first)
        {
            int width = value.Width;
            int height = value.Height;
            BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height),
                                ImageLockMode.ReadWrite,
                                PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);

            byte[] r = new byte[stride * height * 4];

            Marshal.Copy(bData.Scan0, r, 0, r.Length);

            byte[] vals = new byte[height * stride];

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    byte blue = r[row * stride + col * 4];
                    byte green = r[row * stride + col * 4 + 1];
                    byte red = r[row * stride + col * 4 + 2];
                    int gray = Convert.ToInt32(.3 * red + .59 * green + .11 * blue);
                    if (gray > 255) gray = 255;
                    if (gray < 0) gray = 0;
                    vals[row * width + col] = Convert.ToByte(gray);
                }
            }
            first.WriteRaster(xOffset, yOffset, width, height, vals, width, height, 0, 0);
        }
Ejemplo n.º 30
0
 private byte[] ReadGrayIndex(int startRow, int startColumn, int numRows, int numColumns, int overview)
 {
     int width = numColumns;
     int height = numRows;
     byte[] r = new byte[width * height];
     if (overview > 0)
     {
         _red = _red.GetOverview(overview - 1);
     }
     _red.ReadRaster(startColumn, startRow, width, height, r, width, height, 0, 0);
     byte[] vals = new byte[width * height * 4];
     const int bpp = 4;
     for (int row = 0; row < height; row++)
     {
         for (int col = 0; col < width; col++)
         {
             vals[row * width * bpp + col * bpp] = r[row * width + col];
             vals[row * width * bpp + col * bpp + 1] = r[row * width + col];
             vals[row * width * bpp + col * bpp + 2] = r[row * width + col];
             vals[row * width * bpp + col * bpp + 3] = 255;
         }
     }
     return vals;
 }
Ejemplo n.º 31
0
        private static void WriteRgb(Bitmap value, int xOffset, int yOffset, Band first, Dataset set)
        {
            if (set.RasterCount < 3)
            {
                throw new GdalException(
                    "RGB Format was indicated but there are only " +
                    set.RasterCount +
                    " bands!");
            }

            int width = value.Width;
            int height = value.Height;

            BitmapData bData = value.LockBits(new Rectangle(0, 0, width, height),
                                 ImageLockMode.ReadWrite,
                                 PixelFormat.Format24bppRgb);
            int stride = Math.Abs(bData.Stride);
            byte[] vals = new byte[stride * height];
            Marshal.Copy(bData.Scan0, vals, 0, vals.Length);
            value.UnlockBits(bData);
            byte[] r = new byte[width * height];
            byte[] g = new byte[width * height];
            byte[] b = new byte[width * height];

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    b[row * width + col] = vals[row * stride + col * 4];
                    g[row * width + col] = vals[row * stride + col * 4 + 1];
                    r[row * width + col] = vals[row * stride + col * 4 + 2];
                }
            }
            Band green = set.GetRasterBand(2);
            Band blue = set.GetRasterBand(3);
            first.WriteRaster(xOffset, yOffset, width, height, r, width, height, 0, 0);
            first.FlushCache();
            green.WriteRaster(xOffset, yOffset, width, height, g, width, height, 0, 0);
            green.FlushCache();
            blue.WriteRaster(xOffset, yOffset, width, height, b, width, height, 0, 0);
            blue.FlushCache();
            // first disposed in caller
            green.Dispose();
            blue.Dispose();
        }
Ejemplo n.º 32
0
 /// <inheritdocs/>
 protected override void Dispose(bool disposeManagedResources)
 {
     // All class variables are unmanaged.
     if (_dataset != null)
     {
         try
         {
             _dataset.FlushCache();
         }
         catch (Exception e)
         {
             System.Console.WriteLine(e.Message);
         }
         _dataset.Dispose();
     }
     _dataset = null;
     if (_image != null)
     {
         _image.Dispose();
     }
     _image = null;
     if (_red != null)
     {
         _red.Dispose();
     }
     _red = null;
     if (_blue != null)
     {
         _blue.Dispose();
     }
     _blue = null;
     if (_green != null)
     {
         _green.Dispose();
     }
     _green = null;
     if (_alpha != null)
     {
         _alpha.Dispose();
     }
     _alpha = null;
     base.Dispose(disposeManagedResources);
 }
Ejemplo n.º 33
0
        private ColorBlend GetColorBlend(Band band)
        {
            if (_colorBlend != null)
                return _colorBlend;

            int hasVal;

            //Get minimum raster value
            double dblMin;
            band.GetMinimum(out dblMin, out hasVal);
            if (hasVal == 0) dblMin = Double.NaN;

            //Get maximum raster value
            double dblMax;
            band.GetMaximum(out dblMax, out hasVal);
            if (hasVal == 0) dblMax = double.NaN;

            if (double.IsNaN(dblMin) || double.IsNaN(dblMax))
                return null;

            double dblMean, dblStdDev;
            band.GetStatistics(0, 1, out dblMin, out dblMax, out dblMean,
                                   out dblStdDev);
            // ToDo: Colorblend positions
            var minmax = new[]
                {
                    Convert.ToSingle(dblMin),
                    0.5f*Convert.ToSingle(dblMin + dblMax),
                    Convert.ToSingle(dblMax)
                };

            _colorBlend = new ColorBlend(new[] { Color.Blue, Color.Yellow, Color.Red }, minmax);
            
            return _colorBlend;

        }
Ejemplo n.º 34
0
        private Bitmap ReadPaletteBuffered(int xOffset, int yOffset, int xSize, int ySize, Band first)
        {
            ColorTable ct = first.GetRasterColorTable();
            if (ct == null)
            {
                throw new GdalException("Image was stored with a palette interpretation but has no color table.");
            }
            if (ct.GetPaletteInterpretation() != PaletteInterp.GPI_RGB)
            {
                throw new GdalException("Only RGB palette interpretation is currently supported by this " +
                                        " plug-in, " + ct.GetPaletteInterpretation() + " is not supported.");
            }
            Band first_o;
            int width = xSize;
            int height = ySize;
            byte[] r = new byte[width * height];
            if (first.GetOverviewCount() > 0 && _overview >= 0)
            {
                first_o = first.GetOverview(_overview);
            }
            else
            {
                first_o = first;
            }
            if (xOffset + width > first_o.XSize)
            {
                width = first_o.XSize - xOffset;
            }
            if (yOffset + height > first_o.YSize)
            {
                height = first_o.YSize - yOffset;
            }

            first_o.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0);

            Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            BitmapData bData = result.LockBits(new Rectangle(0, 0, width, height),
                                               ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);

            const int bpp = 4;
            byte[] vals = new byte[stride * height];
            byte[][] colorTable = new byte[ct.GetCount()][];
            for (int i = 0; i < ct.GetCount(); i++)
            {
                ColorEntry ce = ct.GetColorEntry(i);
                colorTable[i] = new[]
                                    {
                                        (byte) ce.c3, (byte) ce.c2, (byte) ce.c1,
                                        (byte) ce.c4
                                    };
            }
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    Array.Copy(colorTable[r[col + row * stride]], 0, vals,
                               row * stride + col * bpp, 4);
                }
            }
            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            result.UnlockBits(bData);
            return result;
        }
Ejemplo n.º 35
0
 public static int SieveFilter(Band srcBand, Band maskBand, Band dstBand, int threshold, int connectedness, string[] options, Gdal.GDALProgressFuncDelegate callback, string callback_data)
 {
     int ret = GdalPINVOKE.SieveFilter(Band.getCPtr(srcBand), Band.getCPtr(maskBand), Band.getCPtr(dstBand), threshold, connectedness, (options != null)? new GdalPINVOKE.StringListMarshal(options)._ar : null, callback, callback_data);
     if (GdalPINVOKE.SWIGPendingException.Pending) throw GdalPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Ejemplo n.º 36
0
        private Bitmap ReadGrayIndex(int xOffset, int yOffset, int xSize, int ySize, Band first)
        {
            Band first_o;
            int width = xSize;
            int height = ySize;
            if (first.GetOverviewCount() > 0 && _overview >= 0)
            {
                first_o = first.GetOverview(_overview);
            }
            else
            {
                first_o = first;
            }
            if (xOffset + width > first_o.XSize)
            {
                width = first_o.XSize - xOffset;
            }
            if (yOffset + height > first_o.YSize)
            {
                height = first_o.YSize - yOffset;
            }
            Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            byte[] r = new byte[width * height];
            first.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0);
            BitmapData bData =
                result.LockBits(new Rectangle(0, 0, xSize, ySize),
                                ImageLockMode.ReadWrite,
                                PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);

            byte[] vals = new byte[height * stride];

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    byte value = r[row * width + col];
                    vals[row * stride + col * 4] = value;
                    vals[row * stride + col * 4 + 1] = value;
                    vals[row * stride + col * 4 + 2] = value;
                    vals[row * stride + col * 4 + 3] = 255;
                }
            }
            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            result.UnlockBits(bData);
            return result;
        }
        private IRaster GetBand(string filename, Band band)
        {
            IRaster result = null;
            if (band.DataType == DataType.GDT_Int32)
            {
                result = new GdalIntRaster(filename, _dataset, band);
            }
            if (band.DataType == DataType.GDT_UInt16)
            {
                result = new GdalIntRaster(filename, _dataset, band);
            }
            if (band.DataType == DataType.GDT_Float32)
            {
                result = new GdalFloatRaster(filename, _dataset, band);
            }
            if (band.DataType == DataType.GDT_Int16)
            {
                result = new GdalShortRaster(filename, _dataset, band);
            }
            if (result != null)
            {
                result.Open();
            }

            return result;
        }
Ejemplo n.º 38
0
        private Bitmap ReadRgb(int xOffset, int yOffset, int xSize, int ySize, Band first, Dataset set)
        {
            if (set.RasterCount < 3)
            {
                throw new GdalException(
                    "RGB Format was indicated but there are only " +
                    set.RasterCount +
                    " bands!");
            }
            Band first_o;
            Band green_o;
            Band blue_o;
            Band green = set.GetRasterBand(2);
            Band blue = set.GetRasterBand(3);
            int width = xSize;
            int height = ySize;
            if (first.GetOverviewCount() > 0 && _overview >= 0)
            {
                first_o = first.GetOverview(_overview);
                green_o = green.GetOverview(_overview);
                blue_o = blue.GetOverview(_overview);
            }
            else
            {
                first_o = first;
                green_o = green;
                blue_o = blue;
            }
            if (xOffset + width > first_o.XSize)
            {
                width = first_o.XSize - xOffset;
            }
            if (yOffset + height > first_o.YSize)
            {
                height = first_o.YSize - yOffset;
            }

            Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb);
            //byte[] r;
            if (r == null || r.Length != width * height)
            {
                r = new byte[width * height];
            }
            if (g == null || g.Length != width * height)
            {
                g = new byte[width * height];
            }
            if (b == null || b.Length != width * height)
            {
                b = new byte[width * height];
            }
            if (vals == null || vals.Length != width * height * 4)
            {
                vals = new byte[width * height * 4];
            }
            first_o.ReadRaster(xOffset, yOffset, width, height, r, width, height, 0, 0);
            green_o.ReadRaster(xOffset, yOffset, width, height, g, width, height, 0, 0);
            blue_o.ReadRaster(xOffset, yOffset, width, height, b, width, height, 0, 0);
            /* alternative way to call gdal 
            unsafe
            {
                fixed (byte* p = r)
                {
                    IntPtr ptr = (IntPtr)p;
                    first_o.ReadRaster(xOffset, yOffset, width, height, ptr, width, height, DataType.GDT_Byte, 0, 0);
                }
                fixed (byte* p = g)
                {
                    IntPtr ptr = (IntPtr)p;
                    green_o.ReadRaster(xOffset, yOffset, width, height, ptr, width, height, DataType.GDT_Byte, 0, 0);
                }
                fixed (byte* p = b)
                {
                    IntPtr ptr = (IntPtr)p;
                    blue_o.ReadRaster(xOffset, yOffset, width, height, ptr, width, height, DataType.GDT_Byte, 0, 0);
                }
            }*/

            //first disposed in caller
            green.Dispose();
            blue.Dispose();

            BitmapData bData =
                result.LockBits(new Rectangle(0, 0, width, height),
                                ImageLockMode.ReadWrite,
                                PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    vals[row * stride + col * 4] = b[row * width + col];
                    vals[row * stride + col * 4 + 1] = g[row * width + col];
                    vals[row * stride + col * 4 + 2] = r[row * width + col];
                    vals[row * stride + col * 4 + 3] = 255;
                }
            }
            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            result.UnlockBits(bData);
            //vals = null;
            //r = null;
            //g = null;
            //b = null;
            return result;
        }
Ejemplo n.º 39
0
 public static HandleRef getCPtr(Band obj)
 {
     return((obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr);
 }
Ejemplo n.º 40
0
        private Bitmap ReadArgb(int xOffset, int yOffset, int xSize, int ySize, Band first, Dataset set)
        {
            if (set.RasterCount < 4)
            {
                throw new GdalException(
                    "ARGB Format was indicated but there are only " +
                    set.RasterCount +
                    " bands!");
            }
            Band first_o;
            Band red_o;
            Band green_o;
            Band blue_o;

            Band red = set.GetRasterBand(2);
            Band green = set.GetRasterBand(3);
            Band blue = set.GetRasterBand(4);

            int width = xSize;
            int height = ySize;

            if (first.GetOverviewCount() > 0 && _overview >= 0)
            {
                first_o = first.GetOverview(_overview);
                red_o = red.GetOverview(_overview);
                green_o = green.GetOverview(_overview);
                blue_o = blue.GetOverview(_overview);
            }
            else
            {
                first_o = first;
                red_o = red;
                green_o = green;
                blue_o = blue;
            }
            if (xOffset + width > first_o.XSize)
            {
                width = first_o.XSize - xOffset;
            }
            if (yOffset + height > first_o.YSize)
            {
                height = first_o.YSize - yOffset;
            }
            Bitmap result = new Bitmap(width, height, PixelFormat.Format32bppArgb);

            byte[] a = new byte[width * height];
            byte[] r = new byte[width * height];
            byte[] g = new byte[width * height];
            byte[] b = new byte[width * height];

            first_o.ReadRaster(0, 0, width, height, a, width, height, 0, 0);
            red_o.ReadRaster(0, 0, width, height, r, width, height, 0, 0);
            green_o.ReadRaster(0, 0, width, height, g, width, height, 0, 0);
            blue_o.ReadRaster(0, 0, width, height, b, width, height, 0, 0);
            // Alpha disposed in caller
            red.Dispose();
            green.Dispose();
            blue.Dispose();

            BitmapData bData =
                result.LockBits(new Rectangle(0, 0, width, height),
                                ImageLockMode.ReadWrite,
                                PixelFormat.Format32bppArgb);
            int stride = Math.Abs(bData.Stride);

            byte[] vals = new byte[height * stride];

            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    vals[row * stride + col * 4] =
                        b[row * width + col];
                    vals[row * stride + col * 4 + 1] =
                        g[row * width + col];
                    vals[row * stride + col * 4 + 2] =
                        r[row * width + col];
                    vals[row * stride + col * 4 + 3] =
                        a[row * width + col];
                }
            }
            Marshal.Copy(vals, 0, bData.Scan0, vals.Length);
            result.UnlockBits(bData);
            return result;
        }
Ejemplo n.º 41
0
        public int TransformGeolocations(Band xBand, Band yBand, Band zBand, Gdal.GDALProgressFuncDelegate callback, string callback_data, string[] options)
        {
            int ret = GdalPINVOKE.Transformer_TransformGeolocations(swigCPtr, Band.getCPtr(xBand), Band.getCPtr(yBand), Band.getCPtr(zBand), callback, callback_data, (options != null)? new GdalPINVOKE.StringListMarshal(options)._ar : null);

            if (GdalPINVOKE.SWIGPendingException.Pending)
            {
                throw GdalPINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Ejemplo n.º 42
0
        private void GetNonRotatedPreview(Dataset dataset, Size size, Graphics g,
                                          Envelope bbox, ProjectionInfo mapProjection)
#endif
        {
            double[] geoTrans = new double[6];
            dataset.GetGeoTransform(geoTrans);

            // default transform
            if (!_useRotation && !HaveSpot || (geoTrans[0] == 0 && geoTrans[3] == 0))
                geoTrans = new[] { 999.5, 1, 0, 1000.5, 0, -1 };
            Bitmap bitmap = null;
            var geoTransform = new GeoTransform(geoTrans);
            int DsWidth = 0;
            int DsHeight = 0;
            BitmapData bitmapData = null;
            double[] intVal = new double[Bands];
            int p_indx;
            double bitScalar = 1.0;

            double dblImginMapW = 0, dblImginMapH = 0, dblLocX = 0, dblLocY = 0;

            int iPixelSize = 3; //Format24bppRgb = byte[b,g,r] 

            if (dataset != null)
            {
                //check if image is in bounding box
                if ((bbox.MinX > _envelope.MaxX) || (bbox.MaxX < _envelope.MinX)
                    || (bbox.MaxY < _envelope.MinY) || (bbox.MinY > _envelope.MaxY))
                    return;

                DsWidth = _imageSize.Width;
                DsHeight = _imageSize.Height;

                Histogram = new List<int[]>();
                for (int i = 0; i < Bands + 1; i++)
                    Histogram.Add(new int[256]);

                double left = Math.Max(bbox.MinX, _envelope.MinX);
                double top = Math.Min(bbox.MaxY, _envelope.MaxY);
                double right = Math.Min(bbox.MaxX, _envelope.MaxX);
                double bottom = Math.Max(bbox.MinY, _envelope.MinY);

                double x1 = Math.Abs(geoTransform.PixelX(left));
                double y1 = Math.Abs(geoTransform.PixelY(top));
                double imgPixWidth = geoTransform.PixelXwidth(right - left);
                double imgPixHeight = geoTransform.PixelYwidth(bottom - top);

                //get screen pixels image should fill 
                double dblBBoxW = bbox.Width;
                double dblBBoxtoImgPixX = imgPixWidth / dblBBoxW;
                dblImginMapW = size.Width * dblBBoxtoImgPixX * geoTransform.HorizontalPixelResolution;


                double dblBBoxH = bbox.Height;
                double dblBBoxtoImgPixY = imgPixHeight / dblBBoxH;
                dblImginMapH = size.Height * dblBBoxtoImgPixY * -geoTransform.VerticalPixelResolution;

                if ((dblImginMapH == 0) || (dblImginMapW == 0))
                    return;

                // ratios of bounding box to image ground space
                double dblBBoxtoImgX = size.Width / dblBBoxW;
                double dblBBoxtoImgY = size.Height / dblBBoxH;

                // set where to display bitmap in Map
                if (bbox.MinX != left)
                {
                    if (bbox.MaxX != right)
                        dblLocX = (_envelope.MinX - bbox.MinX) * dblBBoxtoImgX;
                    else
                        dblLocX = size.Width - dblImginMapW;
                }
                if (bbox.MaxY != top)
                {
                    if (bbox.MinY != bottom)
                        dblLocY = (bbox.MaxY - _envelope.MaxY) * dblBBoxtoImgY;
                    else
                        dblLocY = size.Height - dblImginMapH;
                }

                bitScalar = GetBitScalar();

                try
                {
                    bitmap = new Bitmap((int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH),
                                        PixelFormat.Format24bppRgb);
                    bitmapData =
                        bitmap.LockBits(
                            new Rectangle(0, 0, (int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH)),
                            ImageLockMode.ReadWrite, bitmap.PixelFormat);

                    byte cr = _noDataInitColor.R;
                    byte cg = _noDataInitColor.G;
                    byte cb = _noDataInitColor.B;

                    //
                    Double[] noDataValues = new Double[Bands];
                    Double[] scales = new Double[Bands];

                    ColorTable colorTable = null;
                    unsafe
                    {
                        double[][] buffer = new double[Bands][];
                        Band[] band = new Band[Bands];
                        int[] ch = new int[Bands];
                        // get data from image
                        for (int i = 0; i < Bands; i++)
                        {
                            buffer[i] = new double[(int)Math.Round(dblImginMapW) * (int)Math.Round(dblImginMapH)];
                            band[i] = dataset.GetRasterBand(i + 1);

                            //get nodata value if present
                            Int32 hasVal = 0;
                            band[i].GetNoDataValue(out noDataValues[i], out hasVal);
                            if (hasVal == 0) noDataValues[i] = Double.NaN;
                            band[i].GetScale(out scales[i], out hasVal);
                            if (hasVal == 0) scales[i] = 1.0;

                            band[i].ReadRaster((int)Math.Round(x1), (int)Math.Round(y1), (int)Math.Round(imgPixWidth),
                                               (int)Math.Round(imgPixHeight),
                                               buffer[i], (int)Math.Round(dblImginMapW), (int)Math.Round(dblImginMapH),
                                               0, 0);

                            switch (band[i].GetRasterColorInterpretation())
                            {
                                case ColorInterp.GCI_BlueBand:
                                    ch[i] = 0;
                                    break;
                                case ColorInterp.GCI_GreenBand:
                                    ch[i] = 1;
                                    break;
                                case ColorInterp.GCI_RedBand:
                                    ch[i] = 2;
                                    break;
                                case ColorInterp.GCI_Undefined:
                                    if (Bands > 1)
                                        ch[i] = 3; // infrared
                                    else
                                    {
                                        ch[i] = 4;
                                        if (_colorBlend == null)
                                        {
                                            Double dblMin, dblMax;
                                            band[i].GetMinimum(out dblMin, out hasVal);
                                            if (hasVal == 0) dblMin = Double.NaN;
                                            band[i].GetMaximum(out dblMax, out hasVal);
                                            if (hasVal == 0) dblMax = double.NaN;
                                            if (Double.IsNaN(dblMin) || Double.IsNaN(dblMax))
                                            {
                                                double dblMean, dblStdDev;
                                                band[i].GetStatistics(0, 1, out dblMin, out dblMax, out dblMean, out dblStdDev);
                                                //double dblRange = dblMax - dblMin;
                                                //dblMin -= 0.1*dblRange;
                                                //dblMax += 0.1*dblRange;
                                            }
                                            Single[] minmax = new float[] { Convert.ToSingle(dblMin), 0.5f * Convert.ToSingle(dblMin + dblMax), Convert.ToSingle(dblMax) };
                                            Color[] colors = new Color[] { Color.Blue, Color.Yellow, Color.Red };
                                            _colorBlend = new ColorBlend(colors, minmax);
                                        }
                                        intVal = new Double[3];
                                    }
                                    break;
                                case ColorInterp.GCI_GrayIndex:
                                    ch[i] = 0;
                                    break;
                                case ColorInterp.GCI_PaletteIndex:
                                    colorTable = band[i].GetRasterColorTable();
                                    ch[i] = 5;
                                    intVal = new Double[3];
                                    break;
                                default:
                                    ch[i] = -1;
                                    break;
                            }
                        }

                        if (BitDepth == 32)
                            ch = new[] { 0, 1, 2 };

                        p_indx = 0;
                        for (int y = 0; y < Math.Round(dblImginMapH); y++)
                        {
                            byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
                            for (int x = 0; x < Math.Round(dblImginMapW); x++, p_indx++)
                            {
                                for (int i = 0; i < Bands; i++)
                                {
                                    intVal[i] = buffer[i][p_indx]/bitScalar;
                                    Double imageVal = intVal[i] = intVal[i]/bitScalar;
                                    if (ch[i] == 4)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            Color color = _colorBlend.GetColor(Convert.ToSingle(imageVal));
                                            intVal[0] = color.B;
                                            intVal[1] = color.G;
                                            intVal[2] = color.R;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }

                                    else if (ch[i] == 5 && colorTable != null)
                                    {
                                        if (imageVal != noDataValues[i])
                                        {
                                            ColorEntry ce = colorTable.GetColorEntry(Convert.ToInt32(imageVal));
                                            intVal[0] = ce.c3;
                                            intVal[1] = ce.c2;
                                            intVal[2] = ce.c1;
                                            //intVal[3] = ce.c4;
                                        }
                                        else
                                        {
                                            intVal[0] = cb;
                                            intVal[1] = cg;
                                            intVal[2] = cr;
                                        }
                                    }
                                    else
                                    {
                                        if (ColorCorrect)
                                        {
                                            intVal[i] = ApplyColorCorrection(intVal[i], 0, ch[i], 0, 0);

                                            if (Bands >= 3)
                                                Histogram[Bands][
                                                    (int) (intVal[2]*0.2126 + intVal[1]*0.7152 + intVal[0]*0.0722)]++;
                                        }
                                    }

                                    if (intVal[i] > 255)
                                        intVal[i] = 255;
                                }

                                WritePixel(x, intVal, iPixelSize, ch, row);
                            }
                        }
                    }
                }
                catch
                {
                    return;
                }
                finally
                {
                    if (bitmapData != null)
                        bitmap.UnlockBits(bitmapData);
                }
            }
            if (TransparentColor != Color.Empty)
                bitmap.MakeTransparent(TransparentColor);
            g.DrawImage(bitmap, new Point((int)Math.Round(dblLocX), (int)Math.Round(dblLocY)));
        }
Ejemplo n.º 43
0
 public static HandleRef getCPtr(Band obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Ejemplo n.º 44
0
        private void ReadRGB()
        {

            if (_dataset.RasterCount < 3)
            {
                throw new GdalException("RGB Format was indicated but there are only " + _dataset.RasterCount + " bands!");
            }
            _green = _dataset.GetRasterBand(2);
            _blue = _dataset.GetRasterBand(3);

            Width = _red.XSize;
            Height = _red.YSize;

            _image = new Bitmap(Width, Height, PixelFormat.Format32bppRgb);


            byte[] r = new byte[Width * Height];
            byte[] g = new byte[Width * Height];
            byte[] b = new byte[Width * Height];

            _red.ReadRaster(0, 0, Width, Height, r, Width, Height, 0, 0);
            _green.ReadRaster(0, 0, Width, Height, g, Width, Height, 0, 0);
            _blue.ReadRaster(0, 0, Width, Height, b, Width, Height, 0, 0);

            BitmapData bData = _image.LockBits(new Rectangle(0, 0, Width, Height), ImageLockMode.ReadWrite, PixelFormat.Format32bppArgb);
            Stride = bData.Stride;
            _image.UnlockBits(bData);
            byte[] vals = new byte[Width * Height * 4];
            BytesPerPixel = 4;
            int stride = Stride;
            int bpp = BytesPerPixel;
            int width = Width;
            int height = Height;
            for (int row = 0; row < height; row++)
            {
                for (int col = 0; col < width; col++)
                {
                    vals[row * stride + col * bpp] = b[row * width + col];
                    vals[row * stride + col * bpp + 1] = g[row * width + col];
                    vals[row * stride + col * bpp + 2] = r[row * width + col];
                    vals[row * stride + col * bpp + 3] = 255;
                }
            }
            Values = vals;
            WriteBytes();
        }
Ejemplo n.º 45
0
 /// <summary>
 ///  Returns the data from the file in the form of ARGB bytes, regardless of how the image
 ///  data is actually stored in the file.
 /// </summary>
 /// <param name="startRow">The zero based integer index of the first row (Y)</param>
 /// <param name="startColumn">The zero based integer index of the first column (X)</param>
 /// <param name="numRows">The number of rows to read</param>
 /// <param name="numColumns">The number of columns to read</param>
 /// <param name="overview">The integer overview.  0 for the original image.  Each successive index divides the length and height in half.  </param>
 /// <returns>A Byte of values in ARGB order and in row-major raster-scan sequence</returns>
 public byte[] ReadWindow(int startRow, int startColumn, int numRows, int numColumns, int overview)
 {
     EnsureDatasetOpen();
     _red = _dataset.GetRasterBand(1);
     byte[] result = null;
     if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_PaletteIndex)
     {
         result = ReadPaletteBuffered(startRow, startColumn, numRows, numColumns, overview);
     }
     if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex)
     {
         result = ReadGrayIndex(startRow, startColumn, numRows, numColumns, overview);
     }
     if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_RedBand)
     {
         result = ReadRgb(startRow, startColumn, numRows, numColumns, overview);
     }
     if (_red.GetRasterColorInterpretation() == ColorInterp.GCI_AlphaBand)
     {
         result = ReadArgb(startRow, startColumn, numRows, numColumns, overview);
     }
     return result;
 }
Ejemplo n.º 46
0
        /// <summary>
        /// 切分图像||
        /// 解决图像过大导致的计算缓慢||
        /// 输入图像路径,输出分幅路径||
        /// 重叠区根据图像分辨率确定,约为实地100~200米
        /// </summary>
        /// <param name="inPaht"></param>
        /// <returns></returns>
        public static List <string> getSubImg(string inPaht)
        {
            //注册插件
            OSGeo.GDAL.Gdal.AllRegister();
            OSGeo.GDAL.Driver gdalDriver = OSGeo.GDAL.Gdal.GetDriverByName("HFA");
            //读进数据
            OSGeo.GDAL.Dataset inDS = OSGeo.GDAL.Gdal.Open(inPaht, OSGeo.GDAL.Access.GA_ReadOnly);

            //根据栅格分辨率确定重叠区大小
            double[] dsTraansform = new double[6];
            inDS.GetGeoTransform(dsTraansform);
            if (dsTraansform[1] < 0.16)
            {
                xBuf = 1000; yBuf = 1000;
            }                            //1000*0.1=>100M
            if (dsTraansform[1] < 0.3)
            {
                xBuf = 500; yBuf = 500;
            }                          //500*0.25=>125M
            else if (dsTraansform[1] < 0.6)
            {
                xBuf = 300; yBuf = 300;
            }                          //300*0.5=>150M
            else if (dsTraansform[1] < 1.1)
            {
                xBuf = 200; yBuf = 150;
            }                          //150*1=>200M
            else if (dsTraansform[1] < 2.1)
            {
                xBuf = 100; yBuf = 100;
            }                          //100*2=>200M
            else
            {
                xBuf = 50; yBuf = 50;
            }                        //50*5=>250M


            //获取数据XY相元数量
            int oriXcount = inDS.RasterXSize;
            int oriYcount = inDS.RasterYSize;

            //用来返回的文件路径列表
            List <string> imgFilePaths = new List <string>();

            if (oriXcount > userSetX || oriYcount > userSetY)
            {
                //确定文件行列数
                int u, v;
                u = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(oriXcount) / userSetX)); //行文件数
                v = Convert.ToInt32(Math.Ceiling(Convert.ToDouble(oriYcount) / userSetY)); //列文件数

                //循环列
                for (int i = 0; i < v; i++)
                {
                    //循环行
                    for (int j = 0; j < u; j++)
                    {
                        ////////////  定义起点  /////////////
                        int offX = j * userSetX;
                        int offY = i * userSetY;

                        //////////////定义边缘栅格大小/////////////////
                        int thinkJ    = userSetX * (j + 1) + xBuf;
                        int thinkI    = userSetY * (i + 1) + yBuf;
                        int subXcount = oriXcount - thinkJ > 0 ? userSetX + xBuf : oriXcount - userSetX * j;
                        int subYcount = oriYcount - thinkI > 0 ? userSetY + yBuf : oriYcount - userSetY * i;

                        ////////////  把原栅格读进内存,内容为oriValue /////////////
                        OSGeo.GDAL.Band oriBand  = inDS.GetRasterBand(1);
                        double[]        oriValue = new double[subXcount * subYcount];

                        oriBand.ReadRaster
                        (
                            offX,      //起点X索引
                            offY,      //起点Y索引
                            subXcount, //X方向相元数量
                            subYcount, //Y方向相元数量
                            oriValue,  //各相元值
                            subXcount, //执行读入的X方向数量
                            subYcount, //执行读入的Y方向数量
                            0,         //执行读入的起点X索引
                            0          //执行读入的起点Y索引
                        );

                        ////////////  创建子栅格 /////////////
                        string             imgFilePath = StaticTools.tempFilePath("img", i.ToString() + "_" + j.ToString());
                        OSGeo.GDAL.Dataset subDs       = gdalDriver.Create
                                                         (
                            imgFilePath,
                            subXcount,
                            subYcount,
                            1,
                            OSGeo.GDAL.DataType.GDT_Float32,
                            null
                                                         );
                        subDs.SetProjection(inDS.GetProjectionRef());

                        //获取数据Transfrom
                        double[] oriTransFrom = new double[6];
                        inDS.GetGeoTransform(oriTransFrom);
                        oriTransFrom[0] = oriTransFrom[0] + offX * oriTransFrom[1] + offY * oriTransFrom[2];
                        oriTransFrom[3] = oriTransFrom[3] + offX * oriTransFrom[4] + offY * oriTransFrom[5];
                        subDs.SetGeoTransform(oriTransFrom);
                        ////////////  把值写入子栅格 /////////////
                        subDs.GetRasterBand(1).WriteRaster
                        (
                            0,
                            0,
                            subXcount,
                            subYcount,
                            oriValue,
                            subXcount,
                            subYcount,
                            0,
                            0
                        );

                        ///////////////// 返回子栅格路径 ////////////////////
                        imgFilePaths.Add(imgFilePath);
                        subDs.Dispose();
                    }
                }
            }
            else
            {
                imgFilePaths.Add(inPaht);
            }
            inDS.Dispose();
            return(imgFilePaths);
        }
Ejemplo n.º 47
0
        /// <summary>
        /// Gets the size of the whole image, but doesn't keep the image open unless it was already open.
        /// </summary>
        private void ReadHeader()
        {
            EnsureDatasetOpen();

            double[] test = new double[6];
            _dataset.GetGeoTransform(test);
            Bounds = new RasterBounds(_dataset.RasterYSize, _dataset.RasterXSize, test);
            _red = _dataset.GetRasterBand(1);
            _numOverviews = _red.GetOverviewCount();
            Close();
        }
Ejemplo n.º 48
0
 public int TransformGeolocations(Band xBand, Band yBand, Band zBand, Gdal.GDALProgressFuncDelegate callback, string callback_data, string[] options)
 {
     int ret = GdalPINVOKE.Transformer_TransformGeolocations(swigCPtr, Band.getCPtr(xBand), Band.getCPtr(yBand), Band.getCPtr(zBand), callback, callback_data, (options != null)? new GdalPINVOKE.StringListMarshal(options)._ar : null);
     if (GdalPINVOKE.SWIGPendingException.Pending) throw GdalPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Ejemplo n.º 49
0
        /// <summary>
        /// Retreives a chunk of the raster.
        /// </summary>
        /// <param name="srcX">A minimum X coordinate of the querying area</param>
        /// <param name="srcY">A minimum Y coordinate of the querying area</param>
        /// <param name="srcWidth">A width of the querying area</param>
        /// <param name="srcHeight">A height of the querying area</param>
        /// <param name="maxDestWidth">A maximum width in pixels of the resulting raster</param>
        /// <param name="maxDestHeight">A maximum height in pixels of the resulting raster</param>
        /// <param name="bounds">A bounds of querying area on the map</param>
        /// <param name="receiver">An object receiving raster</param>
        public void QueryRaster(int srcX, int srcY, int srcWidth, int srcHeight, int maxDestWidth, int maxDestHeight, MapAround.Geometry.BoundingRectangle bounds, MapAround.Mapping.IRasterReceiver receiver)
        {
            if (srcX < 0)
                throw new ArgumentException("Minimum X of the querying area should not be negative", "srcX");

            if (srcY < 0)
                throw new ArgumentException("Minimum Y of the querying area should not be negative", "srcY");

            if (srcWidth <= 0)
                throw new ArgumentException("A width of the querying area should be positive", "srcWidth");

            if (srcHeight <= 0)
                throw new ArgumentException("A height of the querying area should be positive", "srcHeight");

            Bitmap bitmap = null;
            BitmapData bitmapData = null;
            double[] intVal = new double[_bandCount];
            int pIndex;
            double bitScalar = 1.0;

            // scale
            if (_bitDepth == 12)
                bitScalar = 16.0;
            else if (_bitDepth == 16)
                bitScalar = 256.0;
            else if (_bitDepth == 32)
                bitScalar = 16777216.0;

            int iPixelSize = 3;

            try
            {
                bitmap = new Bitmap(Math.Max(maxDestWidth, 1), Math.Max(maxDestHeight, 1), PixelFormat.Format24bppRgb);
                bitmapData =
                    bitmap.LockBits(
                        new Rectangle(0, 0, Math.Max(maxDestWidth, 1), Math.Max(maxDestHeight, 1)), ImageLockMode.ReadWrite, bitmap.PixelFormat);

                unsafe
                {
                    double[][] buffer = new double[_bandCount][];
                    Band[] band = new Band[_bandCount];
                    int[] ch = new int[_bandCount];

                    // get data from image
                    for (int i = 0; i < _bandCount; i++)
                    {
                        buffer[i] = new double[maxDestWidth * maxDestHeight];
                        band[i] = _gdalDataset.GetRasterBand(i + 1);

                        band[i].ReadRaster(
                            srcX,          // xOff
                            srcY,          // yOff
                            srcWidth,      // xSize
                            srcHeight,     // ySize
                            buffer[i],     // buffer 
                            maxDestWidth,  // buf_xSize 
                            maxDestHeight, // buf_ySize
                            0,             // pixelSpace
                            0);            // lineSpace

                        if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_BlueBand) ch[i] = 0;
                        else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GreenBand) ch[i] = 1;
                        else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_RedBand) ch[i] = 2;
                        else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_Undefined)
                            ch[i] = 3; // infrared
                        else if (band[i].GetRasterColorInterpretation() == ColorInterp.GCI_GrayIndex) ch[i] = 4;
                        else ch[i] = -1;
                    }

                    if (_bitDepth == 32)
                        ch = new int[] { 0, 1, 2 };

                    pIndex = 0;
                    for (int y = 0; y < maxDestHeight; y++)
                    {
                        byte* row = (byte*)bitmapData.Scan0 + (y * bitmapData.Stride);
                        for (int x = 0; x < maxDestWidth; x++, pIndex++)
                        {
                            for (int i = 0; i < _bandCount; i++)
                            {
                                intVal[i] = buffer[i][pIndex] / bitScalar;

                                if (intVal[i] > 255)
                                    intVal[i] = 255;
                            }

                            writePixel(x, intVal, iPixelSize, ch, row);
                        }
                    }
                }
            }
            finally
            {
                if (bitmapData != null)
                    bitmap.UnlockBits(bitmapData);
            }

            receiver.AddRasterPreview(bitmap, bounds, Width, Height);
        }