1

I have have a code which will select some pixels from a raster. Further I want to get Latitude and Longitude information of these pixels and save it in .csv format.

import gdal
import numpy as np
np.set_printoptions(threshold=np.inf)
path="/home/vigna/Downloads/Mod_LSTS/class.tif"
img=gdal.Open(path)
array=img.ReadAsArray()
for j in range(img.RasterXSize-1):
    for i in  range(img.RasterYSize-1):       
        if array[i,j] == 4:
0

Using GDAL and OGR utilities as library functions:

from osgeo import gdal
import os

filename='myGTiff'
inDs = gdal.Open('{}.tif'.format(filename))
outDs = gdal.Translate('{}.xyz'.format(filename), inDs, format='XYZ', creationOptions=["ADD_HEADER_LINE=YES"])
outDs = None

try:
    os.remove('{}.csv'.format(filename))
except OSError:
    pass

os.rename('{}.xyz'.format(filename), '{}.csv'.format(filename))
inDs = gdal.OpenEx('{}.csv'.format(filename))
sql = "SELECT X, Y, CAST(Z AS float(15)) AS value FROM '{0}.csv'.{0} WHERE value > 0".format(filename)
outDs = gdal.VectorTranslate('{}_filtered.csv'.format(filename), inDs, format='CSV', SQLStatement=sql)
outDs = None

where the GeoTIFF is converted into the XYZ format (very close to CSV). Then, the .xyz file is renamed as a .csv one and finally the desired values (e.g. value > 0) are filtered from the CSV file.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.