Get the Values of an image in Python

Question:

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
'x19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19
xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfcx19xfc
x19xfcx19xfcx19...

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.

Asked By: geoinfo

||

Answers:

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()
Answered By: Jessica

use ReadAsArray instead.

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

refer to website : link

Answered By: xwhsky
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.