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

1

1 Answer 1

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.

6
  • Thanks for the assistance, Remi.braun! Mar 20, 2023 at 20:08
  • I tried print(next(val)) and got the following response Mar 20, 2023 at 20:08
  • Traceback (most recent call last): File "pixel_value.py", line 21, in <module> 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 Mar 20, 2023 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 Mar 20, 2023 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. ] Mar 20, 2023 at 21:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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