Reputation: 63
I am trying to read pixel values and coordinates from landsat8 geotiff file but after reading the file as array it is only showing zeros for my geotiff file. I am using following code to read the file :
from osgeo import gdal
gtif = gdal.Open( "FileName.TIF" )
band = gtif.GetRasterBand(1)
print(band.ReadAsArray())
"FileName.TIF" is one of the band image of Landsat.
I also want to traverse the entire image and get coordinates so please suggest if there is any easy method to traverse the image. Here is the link of image I am using ::
https://drive.google.com/open?id=1SqJ2dQLzqsQFUM61vPWe2u2z_R6Zeqa0
Upvotes: 0
Views: 2092
Reputation: 5040
The way you read the image seems ok. However you can not validate if the image is all zeros by only printing it. It only prints the corners, hence you will only see zeros since your image has zero values around all corners.
You can validate that some value larger than 0 exists using numpy. Change your code to the following. Notice that now in the end it will print 39935 which is the max value of your raster (and which is not zero)
from osgeo import gdal
import numpy as np
gtif = gdal.Open( "test.tif" )
band = gtif.GetRasterBand(1)
bandArray = band.ReadAsArray()
print(bandArray)
print(np.max(bandArray))
In order to get the coordinate of a specific pixel you can use the same approach used to get the lower right corner coordinates of a raster.
ulx, xres, xskew, uly, yskew, yres = gtif.GetGeoTransform()
lrx = ulx + (gtif.RasterXSize * xres)
lry = uly + (gtif.RasterYSize * yres)
In the above code ulx
and uly
is the coordinates of the upper left corner. This can be extracted directly from the raster. The xres
and yres
is the size of each pixel. Given this the lower right corner coordinates lrx
and lry
can be calculated from the previous mentioned values.
Now in order to find the coordinate of any pixel within the image, you can simply replace gtif.RasterXSize
and gtif.RasterYSize
with the pixel entry you need the coordinate of.
ulx, xres, xskew, uly, yskew, yres = gtif.GetGeoTransform()
xCoord = ulx + (pixelX * xres)
yCoord = uly + (pixelY * yres)
So to traverese it an get each pixel coordinate you could do the following
ulx, xres, xskew, uly, yskew, yres = gtif.GetGeoTransform()
for x in range(0, gtif.RasterXSize):
for y in range(0, gtif.RasterYSize):
xCoord = ulx + (x * xres)
yCoord = uly + (y * yres)
# now do something with the coordinate
Upvotes: 1