1

Suppose I have a GeoTIFF image img with dimensions (1,3,3).

img = np.array([[[1.0, 2.3, 3.3],
                 [2.4, 2.6, 2.7],
                 [3.4, 4.2, 8.9]]])

I want to know the geographic coordinates(longitude and latitude) of the pixel whose value is 2.7 within the img.

Expected output:

coordinates = (98.4567, 16.2888)
Gun
  • 556
  • 6
  • 21
  • Does this answer your question ? https://stackoverflow.com/a/27913113 (the second part of the answer uses `rasterio`) – mgc May 12 '20 at 21:05
  • @mgc Thanks for sharing. However, it doesn't really answer my question. – Gun May 13 '20 at 05:00

1 Answers1

2

Your question is having the tag rasterio so i will consider you opened your geotiff with rasterio in that vein :

import rasterio as rio
import numpy as np

dataset = rio.open('file.tif', 'r')
img = dataset.read(1)
# array([[1. , 2.3, 3.3],
#       [2.4, 2.6, 2.7],
#       [3.4, 4.2, 8.9]])

You have to retrieve the indexes (row and column) that correspond to the value you are looking for:

cell_coords = np.where(img == 2.7)
# (array([1]), array([2]))

Then use the transform attribute of your dataset (it contains the affine transformation matrix, using affine python package, allowing to map pixel coordinates to real world coordinates) like this :

coordinates = rio.transform.xy(
    dataset.transform,
    cell_coords[0],
    cell_coords[1],
    offset='center',
)
# (98.4567, 16.2888) in your example
mgc
  • 5,223
  • 1
  • 24
  • 37
  • 2
    The idea worked. I made a small change, used ````rio.transform.xy```` to get the coordinates directly. Thanks! – Gun May 13 '20 at 14:04