0

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)}

Vince
  • 20,017
  • 15
  • 45
  • 64
  • https://gis.stackexchange.com/questions/190423/getting-pixel-values-at-single-point-using-rasterio – BERA Mar 20 '23 at 08:13

1 Answers1

1

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.

remi.braun
  • 423
  • 2
  • 6
  • Thanks for the assistance, Remi.braun! – GeoGraphical Mar 20 '23 at 20:08
  • I tried print(next(val)) and got the following response – GeoGraphical Mar 20 '23 at 20:08
  • Traceback (most recent call last): File "pixel_value.py", line 21, in print(next(val)) File "/......./site-packages/rasterio/sample.py", line 40, in sample_gen for x, y in xy: TypeError: cannot unpack non-iterable float object – GeoGraphical Mar 20 '23 at 20:09
  • I will look into what a generator is, and maybe the issue will become clear to me? I am quite new to python. Cheers – GeoGraphical Mar 20 '23 at 20:10
  • I have found the solution, thanks for the help!

    I needed to implement the for loop:

    for val in src.sample([(x, y)]): print(val)

    even though I only wanted a single value.

    I get the following output for my input .tif file:

    [2.364684 0. 0. ]

    – GeoGraphical Mar 20 '23 at 21:26
  • Sorry for not answering, I was sleeping ;) Glad you made it work! – remi.braun Mar 21 '23 at 09:15