使用Rasterio将像素坐标转换为经纬度时遭遇IndexError索引越界问题求助
Hey there, I think I spot the exact issue here—it's all about the parameter order in Rasterio's xy() method! Let's break this down clearly:
- Your TIFF has a height of 462 (this refers to the number of rows, which maps to the vertical/pixel-y axis) and a width of 715 (number of columns, mapping to the horizontal/pixel-x axis).
- Rasterio's
xy(row, col)method expects row first, column second—meaning you need to pass yourpixel_y(vertical position) as the first argument, andpixel_x(horizontal position) as the second.
Right now, you're passing pixel_x as the first parameter. When you input a value like 525, you're telling Rasterio to access row 525—but your image only has 462 rows (indices range from 0 to 461), hence the IndexError saying the index is out of bounds for axis 0 (the row axis).
Fix the Parameter Order
Adjust your code to swap the arguments, and it should work as expected:
import rasterio with rasterio.open('rasters/raster.tif') as map_layer: # Swap pixel_x and pixel_y: pass pixel_y (row) first, pixel_x (col) second pixels2coords = map_layer.xy(pixel_y, pixel_x)
Quick Validation Tips
To confirm this fixes the issue, test with boundary values:
map_layer.xy(0, 0)should return the geographic coordinates of your raster's top-left corner.map_layer.xy(map_layer.height - 1, map_layer.width - 1)should return the bottom-right corner coordinates.
This mix-up is super common when switching between standard pixel coordinate conventions (x=horizontal, y=vertical) and raster data's row/column structure—don't beat yourself up over spending time on it!
内容的提问来源于stack exchange,提问作者nobody

