Rasterio Sample – Get Pixel Values Using Rasterio.sample

coordinatespixelrasterrasteriosamplepoints

I would like to get the pixel values for a single point within a .tif file using rasterio. I have read several previous questions, and implemented the suggestions.

Here is the code that I am using:

with rasterio.open(filename) as src:
    x = (src.bounds.left + src.bounds.right) / 2.0
    y = (src.bounds.bottom + src.bounds.top) / 2.0

    val = src.sample((x, y))
    print(val)

output <generator object sample_gen at 0x7f290041f1d0>

How can I get the actual values, rather than the above output?

Here is the src.meta of the file I am using if this is at all useful:

{'driver': 'GTiff', 'dtype': 'float32', 'nodata': 999.0, 'width': 917, 'height': 871, 'count': 3, 'crs': CRS.from_epsg(32636), 'transform': Affine(80.0, 0.0, 248720.0,
0.0, -80.0, 4550640.0)}

Best Answer

Does print(next(val)) works ?

sampleoutputs a generator, so you should iterate through it to actually get the value.
But be aware that once iterated, you cannot access your values back !
If you don't have a lot of values (here only one), you can convert your generator to a list.