Skip to content

Instantly share code, notes, and snippets.

@sgillies
Last active April 6, 2020 12:53
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sgillies/061e78c649b6fc4a9f9a to your computer and use it in GitHub Desktop.
Save sgillies/061e78c649b6fc4a9f9a to your computer and use it in GitHub Desktop.
Get raster value at a point using a tiny window

A Rasterio dataset's index() method gives you the row, col index of the pixel containing the point x, y (in the dataset's CRS units).

Define a 1x1 pixel read window starting at that index (see the tiny_window() function below) and use it to read an ndarray. The one in this case has shape (3, 1, 1): 3 bands, 1 row, and 1 column. The values of the 3 bands at the point x, y for this case are 28, 29, and 27.

$ rio insp ~/code/rasterio/tests/data/RGB.byte.tif
Rasterio 0.17 Interactive Inspector (Python 2.7.9)
Type "src.meta", "src.read_band(1)", or "help(src)" for more information.
>>> x = (src.bounds.left + src.bounds.right)/2.0
>>> y = (src.bounds.bottom + src.bounds.top)/2.0
>>> src.index(x, y)
(359, 396)
>>> def tiny_window(dataset, x, y):
... r, c = dataset.index(x, y)
... return ((r, r+1), (c, c+1))
...
>>> data = src.read(window=tiny_window(src, x, y))
>>> list(data[:,0,0])
[28, 29, 27]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment