Beispiel #1
0
        public static bool Translate(Dataset dataset, string outputFile, GDALTranslateOptions translateOptions,
                                     Gdal.GDALProgressFuncDelegate progressFuncDelegate)
        {
            bool result = false;

            Dataset newDs = null;

            try
            {
                Gdal.PushErrorHandler(new Gdal.GDALErrorHandlerDelegate(GdalHandlers.ErrorHandler));
                newDs = Gdal.wrapper_GDALTranslate(outputFile, dataset, translateOptions, progressFuncDelegate, null);
                Gdal.PopErrorHandler();
            }
            catch (Exception ex)
            {
                //LoggerManager.WriteErrorLog(ex.Message);
            }
            finally
            {
                if (newDs != null)
                {
                    newDs.FlushCache();
                    newDs.Dispose();

                    result = true;
                }
            }

            return(result);
        }
Beispiel #2
0
 public static bool Translate(
     string inputFile, string outputFile, string[] options)
 {
     using (Dataset inputds = Gdal.OpenEx(
                inputFile, (uint)GdalConst.OF_RASTER, null, null, null))
     {
         if (inputds == null)
         {
             return(false);
         }
         try
         {
             Dataset test = Gdal.wrapper_GDALTranslate(
                 outputFile, inputds,
                 new GDALTranslateOptions(options), null, null);
             if (test == null)
             {
                 inputds.Dispose();
                 return(false);
             }
             test.Dispose();
         }
         catch (Exception) { return(false); }
         finally
         {
             inputds.Dispose();
         }
     }
     return(true);
 }
Beispiel #3
0
        public void TranslateAction(List <string> files)
        {
            GDALTranslateOptions transOptions = new GDALTranslateOptions(new[] { "-of", "KMLSUPEROVERLAY", "-co", "format=png" });

            var vrtOptions = new GDALBuildVRTOptions(new[] { "-overwrite" });
            var vrtFile    = BuildVRT("tempVRT", files, vrtOptions);

            Gdal.wrapper_GDALTranslate(Path.Combine(OutputDirName, KMZFileName), vrtFile, transOptions, null, null);
        }
 /// <summary>
 /// Translation of raster format
 /// </summary>
 /// <param name="InputRaster"></param>
 /// <param name="OutputRaster"></param>
 /// <param name="OutputDriver">driver neme for the output file, from GDAL drivers list</param>
 public static void TranslateRasterFormat(string InputRaster, string OutputRaster, string OutputDriver)
 {
     try
     {
         var opts = new string[] { "-sds", "-of", OutputDriver };
         using (var ds = Gdal.Open(InputRaster, Access.GA_ReadOnly)) {
             var options = new GDALTranslateOptions(opts);
             using (var outputDS = Gdal.wrapper_GDALTranslate(OutputRaster, ds, options, (Gdal.GDALProgressFuncDelegate)GDalProgress, $"Translare {InputRaster} to {OutputRaster} ({OutputDriver})")) {
                 outputDS.FlushCache();
             }
         }
     }
     catch (Exception e)
     {
         Console.WriteLine("Application error: " + e.Message);
     }
 }
Beispiel #5
0
 //создаёт квиклук
 public void CreateImage()
 {
     if (format.Equals("tif"))
     {
         Dataset ds      = Gdal.Open(pathToPicture, Access.GA_ReadOnly);
         var     options =
             new GDALTranslateOptions(new[]
         {
             "-of", "GTiff",
             "-outsize", $"{percent}%", $"{percent}%",
             "-co", "WORLDFILE=YES",
         });
         try
         {
             Dataset newDs = Gdal.wrapper_GDALTranslate(outputFile, ds, options,
                                                        new Gdal.GDALProgressFuncDelegate(ProgressFunc), null);
             newDs.Dispose();
         }
         catch
         {
         }
     }
     else if (format.Equals("jpg"))
     {
         Dataset ds      = Gdal.Open(pathToPicture, Access.GA_ReadOnly);
         var     options =
             new GDALTranslateOptions(new[]
         {
             "-of", "JPEG",
             "-outsize", $"{percent}%", $"{percent}%",
             "-co", "WORLDFILE=YES",
         });
         try
         {
             Dataset newDs = Gdal.wrapper_GDALTranslate(outputFile, ds, options,
                                                        new Gdal.GDALProgressFuncDelegate(ProgressFunc), null);
             newDs.Dispose();
         }
         catch
         {
         }
     }
 }
Beispiel #6
0
        public static bool GdalTranslate(string srcPath, string dstPath, string[] options, Gdal.GDALProgressFuncDelegate callback = null)
        {
            Dataset result = null;

            using (Dataset inputDataset = Gdal.Open(srcPath, Access.GA_ReadOnly))
            {
                try
                {
                    result = Gdal.wrapper_GDALTranslate(dstPath, inputDataset, new GDALTranslateOptions(options), callback, null);
                }
                catch (Exception e)
                {
                    Debug.WriteLine(e.ToString());
                    return(false);
                }
                finally
                {
                    result.Dispose();
                }
                return(true);
            }
        }
Beispiel #7
0
        public void gdalMerge()
        {
            // Natural color(4,3,2)
            try {
                string[] options = new string[] { };
                Dataset  image   = getGeoTiffObject(5).gdalDataset;

                Band redBand   = GetBand(getGeoTiffObject(4).gdalDataset, ColorInterp.GCI_RedBand);
                Band greenBand = GetBand(getGeoTiffObject(3).gdalDataset, ColorInterp.GCI_GreenBand);
                Band blueBand  = GetBand(getGeoTiffObject(2).gdalDataset, ColorInterp.GCI_BlueBand);
                Band alphaBand = GetBand(image, ColorInterp.GCI_AlphaBand);

                int width  = redBand.XSize;
                int height = redBand.YSize;

                Dataset outImage = Gdal.GetDriverByName("GTiff").Create(
                    "out.tif", width, height, 4, DataType.GDT_Byte, null);
                // copy the projection and geographic informations of image
                double[] geoTransformerData = new double[6];
                image.GetGeoTransform(geoTransformerData);
                outImage.SetGeoTransform(geoTransformerData);
                outImage.SetProjection(image.GetProjection());


                Band outRedBand   = outImage.GetRasterBand(1);
                Band outGreenBand = outImage.GetRasterBand(2);
                Band outBlueBand  = outImage.GetRasterBand(3);
                Band outAlphaBand = outImage.GetRasterBand(4);

                for (int h = 0; h < height; h++)
                {
                    int[] red   = new int[width];
                    int[] green = new int[width];
                    int[] blue  = new int[width];
                    int[] alpha = new int[width];
                    // copy each matrix row of image to the above arrays
                    redBand.ReadRaster(0, h, width, 1, red, width, 1, 0, 0);
                    greenBand.ReadRaster(0, h, width, 1, green, width, 1, 0, 0);
                    blueBand.ReadRaster(0, h, width, 1, blue, width, 1, 0, 0);
                    alphaBand.ReadRaster(0, h, width, 1, alpha, width, 1, 0, 0);

                    for (int w = 0; w < width; w++)
                    {
                        red[w]   = red[w] + 1; // any process with each pixel
                        green[w] = green[w] + 1;
                        blue[w]  = blue[w] + 1;
                        alpha[w] = alpha[w] + 1;
                    }
                    // write image
                    outRedBand.WriteRaster(0, h, width, 1, red, width, 1, 0, 0);
                    outGreenBand.WriteRaster(0, h, width, 1, green, width, 1, 0, 0);
                    outBlueBand.WriteRaster(0, h, width, 1, blue, width, 1, 0, 0);
                    outAlphaBand.WriteRaster(0, h, width, 1, alpha, width, 1, 0, 0);
                }
                outImage.FlushCache();

                Gdal.wrapper_GDALTranslate("TrueColor.tif", outImage,
                                           new GDALTranslateOptions(new string[] { "-ot", "BYTE",
                                                                                   "-of", "GTiff", "-b", "1", "-b", "2", "-b", "3", "-a_nodata", "255", "-scale" }), null, null);

                m_tGeoTiffMerge = new GeoTiffObject("TrueColor.tif", -1);
            } catch (Exception ex) {
                m_ctrlLogger.Error(ex);
            } finally {
                GC.Collect();
            }
        }
Beispiel #8
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string datasourceFileLocation = string.Empty;

            DA.GetData <string>(0, ref datasourceFileLocation);

            string dstFileLocation = string.Empty;

            DA.GetData <string>(1, ref dstFileLocation);

            string options = string.Empty;

            DA.GetData <string>(2, ref options);

            var re = new System.Text.RegularExpressions.Regex("(?<=\")[^\"]*(?=\")|[^\" ]+");

            string[] translateOptions = re.Matches(options).Cast <Match>().Select(m => m.Value).ToArray();

            string datasourceInfo = string.Empty;
            string dstInfo        = string.Empty;
            string dstOutput      = string.Empty;

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdal_translate.html");

            if (!string.IsNullOrEmpty(datasourceFileLocation))
            {
                using (Dataset datasource = Gdal.Open(datasourceFileLocation, Access.GA_ReadOnly))
                {
                    if (datasource == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + datasourceFileLocation);
                    }

                    SpatialReference sr = new SpatialReference(datasource.GetProjection());

                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  " +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        //sr.SetWellKnownGeogCS("WGS84");
                    }

                    ///Get info about image
                    List <string> infoOptions = new List <string> {
                        "-stats"
                    };
                    datasourceInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            Dataset dst = Gdal.wrapper_GDALTranslate(dstFileLocation, datasource, new GDALTranslateOptions(translateOptions), null, null);
                            dstInfo = Gdal.GDALInfo(dst, new GDALInfoOptions(infoOptions.ToArray()));
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                    }
                    datasource.Dispose();
                }
            }

            DA.SetData(0, datasourceInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }
Beispiel #9
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string IMG_file = string.Empty;

            DA.GetData <string>(1, ref IMG_file);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            Dataset datasource = Gdal.Open(IMG_file, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();


            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }

            ///Get info about image
            string        srcInfo     = string.Empty;
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            Rectangle3d dsbox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));

            double pixelWidth  = dsbox.Width / width;
            double pixelHeight = dsbox.Height / height;

            ///Declare trees
            GH_Structure <GH_Point>   pointcloud = new GH_Structure <GH_Point>();
            GH_Structure <GH_Integer> rCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Integer> cCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Mesh>    tMesh      = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                Curve clippingBoundary = boundary[i];

                if (!clip)
                {
                    clippingBoundary = dsbox.ToNurbsCurve();
                }

                string clippedTopoFile = "/vsimem/topoclipped.tif";

                if (!(dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Min) && (dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Max))) && clip)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the topo dataset.");
                }

                ///Offsets to mesh/boundary based on pixel size
                Point3d clipperMinPreAdd  = clippingBoundary.GetBoundingBox(true).Corner(true, false, true);
                Point3d clipperMinPostAdd = new Point3d(clipperMinPreAdd.X, clipperMinPreAdd.Y, clipperMinPreAdd.Z);
                Point3d clipperMin        = Heron.Convert.XYZToWGS(clipperMinPostAdd);

                Point3d clipperMaxPreAdd = clippingBoundary.GetBoundingBox(true).Corner(false, true, true);
                ///add/subtract pixel width if desired to get closer to boundary
                Point3d clipperMaxPostAdd = new Point3d();
                Point3d clipperMax        = new Point3d();
                if (clip)
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X + pixelWidth, clipperMaxPreAdd.Y - pixelHeight, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }
                else
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X, clipperMaxPreAdd.Y, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }


                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    "-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedTopoFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Band band = clippedDataset.GetRasterBand(1);
                    width  = clippedDataset.RasterXSize;
                    height = clippedDataset.RasterYSize;
                    clippedDataset.GetGeoTransform(adfGeoTransform);
                    Gdal.InvGeoTransform(adfGeoTransform, invTransform);

                    rCount.Append(new GH_Integer(height), path);
                    cCount.Append(new GH_Integer(width), path);
                    Mesh           mesh  = new Mesh();
                    List <Point3d> verts = new List <Point3d>();
                    //var vertsParallel = new System.Collections.Concurrent.ConcurrentDictionary<double[][], Point3d>(Environment.ProcessorCount, ((Urow - 1) * (Lrow - 1)));

                    double[] bits = new double[width * height];
                    band.ReadRaster(0, 0, width, height, bits, width, height, 0, 0);

                    for (int col = 0; col < width; col++)
                    {
                        for (int row = 0; row < height; row++)
                        {
                            // equivalent to bits[col][row] if bits is 2-dimension array
                            double pixel = bits[col + row * width];
                            if (pixel < -10000)
                            {
                                pixel = 0;
                            }

                            double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * row;
                            double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * row;

                            ///convert to WGS84
                            double[] wgsPT = new double[3] {
                                gcol, grow, pixel
                            };
                            coordTransform.TransformPoint(wgsPT);
                            Point3d pt = new Point3d(wgsPT[0], wgsPT[1], wgsPT[2]);

                            verts.Add(Heron.Convert.WGSToXYZ(pt));
                        }

                        /*Parallel.For(Urow, Lrow - 1, rowP =>
                         *  {
                         *      // equivalent to bits[col][row] if bits is 2-dimension array
                         *      double pixel = bits[col + rowP * width];
                         *      if (pixel < -10000)
                         *      {
                         *          pixel = 0;
                         *      }
                         *
                         *      double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * rowP;
                         *      double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * rowP;
                         *
                         *      Point3d pt = new Point3d(gcol, grow, pixel);
                         *      vertsParallel[] = Heron.Convert.ToXYZ(pt);
                         *  });
                         * */
                    }

                    //Create meshes
                    //non Parallel
                    mesh.Vertices.AddVertices(verts);
                    //Parallel
                    //mesh.Vertices.AddVertices(vertsParallel.Values);

                    for (int u = 1; u < cCount[path][0].Value; u++)
                    {
                        for (int v = 1; v < rCount[path][0].Value; v++)
                        {
                            mesh.Faces.AddFace(v - 1 + (u - 1) * (height), v - 1 + u * (height), v - 1 + u * (height) + 1, v - 1 + (u - 1) * (height) + 1);
                            //(k - 1 + (j - 1) * num2, k - 1 + j * num2, k - 1 + j * num2 + 1, k - 1 + (j - 1) * num2 + 1)
                        }
                    }

                    //mesh.Flip(true, true, true);
                    tMesh.Append(new GH_Mesh(mesh), path);

                    band.Dispose();
                }
                Gdal.Unlink("/vsimem/topoclipped.tif");
            }

            datasource.Dispose();

            DA.SetDataTree(0, tMesh);
            DA.SetData(1, dsbox);
            DA.SetData(2, srcInfo);
        }
Beispiel #10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            string sourceFileLocation = string.Empty;

            DA.GetData <string>(1, ref sourceFileLocation);

            string clippedLocation = string.Empty;

            DA.GetData <string>(2, ref clippedLocation);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            ///Read in the raster data
            Dataset datasource = Gdal.Open(sourceFileLocation, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();

            string srcInfo = string.Empty;

            if (datasource == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The raster datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                return;
            }


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);

            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is missing.  SRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            ///Get info about image
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");
            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);
            Band band = datasource.GetRasterBand(1);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84.
            ///TODO: Allow for UserSRS
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            ///Get bounding box for entire raster data
            Rectangle3d datasourceBBox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));


            ///https://gis.stackexchange.com/questions/312440/gdal-translate-bilinear-interpolation
            ///set output to georeferenced tiff as a catch-all
            string clippedRasterFile = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_clipped.tif";
            string previewPNG        = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_preview.png";

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Original Resolution: " + datasource.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

            if (boundary != null)
            {
                Point3d clipperMin = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(true, false, true));
                Point3d clipperMax = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(false, true, true));

                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                ///GDALTranslate should also be its own component with full control over options
                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    //"-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedRasterFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, clippedDataset, null, null, null);

                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipped Resolution: " + clippedDataset.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

                    ///clean up
                    clippedDataset.FlushCache();
                    clippedDataset.Dispose();
                    previewDataset.FlushCache();
                    previewDataset.Dispose();

                    AddPreviewItem(previewPNG, BBoxToRect(boundary.GetBoundingBox(true)));
                }
            }

            else
            {
                Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, datasource, null, null, null);

                ///clean up
                previewDataset.FlushCache();
                previewDataset.Dispose();

                AddPreviewItem(previewPNG, datasourceBBox);
            }

            ///clean up
            datasource.FlushCache();
            datasource.Dispose();

            DA.SetData(0, srcInfo);
            DA.SetData(1, datasourceBBox);
            DA.SetData(2, clippedRasterFile);
        }
Beispiel #11
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            string srcFileLocation = string.Empty;

            DA.GetData <string>(0, ref srcFileLocation);

            string dstFileLocation = string.Empty;

            DA.GetData <string>(1, ref dstFileLocation);

            string options = string.Empty;

            DA.GetData <string>(2, ref options);

            string[] translateOptions = options.Split(' ');

            string srcInfo   = string.Empty;
            string dstInfo   = string.Empty;
            string dstOutput = string.Empty;

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Look for more information about options at:");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "https://gdal.org/programs/gdal_translate.html");

            if (!string.IsNullOrEmpty(srcFileLocation))
            {
                using (Dataset src = Gdal.Open(srcFileLocation, Access.GA_ReadOnly))
                {
                    if (src == null)
                    {
                        throw new Exception("Can't open GDAL dataset: " + srcFileLocation);
                    }

                    srcInfo = Gdal.GDALInfo(src, null);

                    if (!string.IsNullOrEmpty(dstFileLocation))
                    {
                        if (string.IsNullOrEmpty(options) && File.Exists(dstFileLocation))
                        {
                            Dataset dst = Gdal.Open(dstFileLocation, Access.GA_ReadOnly);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                        else
                        {
                            Dataset dst = Gdal.wrapper_GDALTranslate(dstFileLocation, src, new GDALTranslateOptions(translateOptions), null, null);
                            dstInfo = Gdal.GDALInfo(dst, null);
                            dst.Dispose();
                            dstOutput = dstFileLocation;
                        }
                    }
                    src.Dispose();
                }
            }

            DA.SetData(0, srcInfo);
            DA.SetData(1, dstInfo);
            DA.SetData(2, dstOutput);
        }