geoinfo
geoinfo

Reputation: 305

Get the Values of an image in Python

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

Answers (2)

Jessica
Jessica

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

xwhsky
xwhsky

Reputation: 141

use ReadAsArray instead.

//for float data type
scanline = band.ReadAsArray( 0, 0, band.XSize, band.YSize).astype(numpy.float)

refer to website : link

Upvotes: 1

Related Questions