1

I would like to recover the values of the pixels of a GeoTIFF of a single band. First I get the x and y coordinates and I would like to use them to access the pixel value. Here is my code:

   raster = rasterio.open('.../g.tif')
   br_pixel = (raster.width * raster.height) 

   liste3 = []
   i = 0   
   while i <= nbr_pixel:
      (x,y) = raster.xy(i,i)
      listX.append(int(x))
      listY.append(int(y))
   i = i + 1 
   l = list(zip(listX,listY))
   liste3 = raster.sample(l)
   print(liste3)

   <generator object sample_gen at 0x7f7ef5821c50>
  • Welcome to Geographic Information Systems! Please use the edit link to add more information to your question, we need to know what happens when you run this, compared to what you expected to happen. – Ian Turton Jan 1 at 11:28
  • Your for loop looks exceeding strange. Pixel count is a product of rows and columns, so you're trying to tear along the diagonal far past the actual size of the image. Recovering the X and Y coordinates along with pixel value could make an extraordinarily large list; raster format is used to avoid this cost, so you're running against paradigm, which usually causes spectacular failures. You may be trapped in an XY Problem; what is your actual goal? – Vince Jan 1 at 13:18
  • my goal is to extract the x and y coordinates and the pixel values (ndvi) – zizou Jan 1 at 13:59
  • Your code does nothing like your stated goal. You try to walk the diagonal, but the while is incorrectly structured, so you infinitely sample the zero-zero pixel. You need to spend some more time on the Python code structure before this is a GIS question. Start with a pair of nested for loops using range iterators over width and height. – Vince Jan 1 at 16:19
0

My understanding is that you want to read in all of the pixel values of a single band so that you access them with x and y values. I would do this by getting the entire band as a numpy array, then use the x and y indices of the array:

import rasterio
band_id = 1  # this assumes you want the first band, change to match the band number you want

raster = rasterio.open('.../g.tif')
band_arr = raster.read(band_id)  # band_arr is a numpy array of shape (raster.width, raster.height)

If you then want to get the pixel value at specific x and y indices:

pixel_value = band_arr[x, y]

OP's comment: I want to have a array of all pixels coordinates and pixels value. because i want to insert in a database.

OK. Beginning with band_arr from above:

px_vals = []

for x in range(band_arr.shape[0]):
    for y in range(band_arr.shape[1]):
        px_vals.append({'x': x, 
                        'y': y,
                        'value': band_arr[x, y]})

The above will give you a list of dicts with keys 'x', 'y', and 'value' which you could then insert into the database.

|improve this answer|||||

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