Reputation: 305
I have a GeoTIFF
and I need to get the values of each pixel.
I proceeded this way :
import gdal
from gdalconst import *
im = gdal.Open("test.tif", GA_ReadOnly)
band = im.GetRasterBand(1)
bandtype = gdal.GetDataTypeName(band.DataType)
scanline = band.ReadRaster( 0, 0, band.XSize, 1,band.XSize, 1, band.DataType)
scanline contains uninterpretable values :
>>> scanline
'\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19
\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\x19\xfc\
x19\xfc\x19\xfc\x19...
I need to convert this data to readable values.
In other words, I need to get the values of the image in order to count the number of pixels having values greater than a specified threshold.
Upvotes: 0
Views: 544
Reputation: 535
From the gdal tutorial, "Note that the returned scanline is of type string, and contains xsize*4 bytes of raw binary floating point data. This can be converted to Python values using the struct module from the standard library:"
import struct
tuple_of_floats = struct.unpack('f' * b2.XSize, scanline)
Alternatively, depending on what you are ultimately trying to do with the data, you could read it in as an array (which opens the door to using numpy for computations).
import gdal
im = gdal.Open("test.tif", GA_ReadOnly)
data_array = im.GetRasterBand(1).ReadAsArray()
Upvotes: 1