Quantcast
Channel: Question and Answer » gdal
Viewing all articles
Browse latest Browse all 397

Is there any way to fast read pixel value using gdal in C#

$
0
0

I create with C# a series of lat/lon value pair in the code(using i, j loop) and I want to extract the pixel value based on either lat/lon pair or pixel location (i, j).

I know there is one gdal utility called gdallocationinfo which can read pixel value very fast. But it is written in python.

I am wondering whether there is a way to use this gdal utility in my C# code, or other methods that can extract pixel value in a faster manor. Thank you in advance!

Update with final solution:

static void Main(string[] args)
    {
        Console.WriteLine(DateTime.Now.ToString());
        Gdal.AllRegister(); //Register all gdal data drives
        List<int> resolutionId = new List<int>() { 9 };

        Dataset ds = Gdal.Open("D:/SKnoZero.tif", Access.GA_ReadOnly);   //Read raster
        double[] gt = new double[6];
        ds.GetGeoTransform(gt); //Read geo transform info into array
        int Rows = ds.RasterYSize;  //Get the number of rows 
        int Cols = ds.RasterXSize;  //Get the number of columns
        Band band = ds.GetRasterBand(1);    //Read band 1
        double startX = gt[0];  //Upper left lon
        double startY = gt[3];  //Upper left lat
        double interval = gt[1];    //Cell size
        double x, y;    //Current lon and lat

        var filePath = "D:/SKcsv.csv";
        using (StreamWriter csv = new StreamWriter(filePath))
        {
            for (int k = 0; k < Rows; k++)  //read one line at a time
            {
                y = startY - k * interval;  //current lat
                int[] buf = new int[Cols];
                //ReadRaster parameters are StartCol, StartRow, ColumnsToRead, RowsToRead, BufferToStoreInto, BufferColumns, BufferRows, 0, 0
                band.ReadRaster(0, k, Cols, 1, buf,Cols,1,0,0);
                //iterate each item in one line
                for (int r = 0; r < Cols; r++)  
                {
                    if (buf[r] != -32768)   //if pixel value is not NoData value
                    {
                        x = startX + r * interval;  //current lon                             
                        var geoidpair = GetVrgId(x, y, resolutionId);   //get geoid
                        var temp = geoidpair;
                        var newLine = string.Format("{0},{1},{2},{3}{4}", x, y, buf[r], temp[0], Environment.NewLine);
                        csv.Write(newLine);           
                     }
                 }
         }
         Console.WriteLine(DateTime.Now.ToString());
         Console.WriteLine("Press any key");
         Console.ReadLine();
    }

Viewing all articles
Browse latest Browse all 397

Trending Articles