简体   繁体   English

像素/阵列位置到纬度长 gdal Python

[英]pixel/array position to lat long gdal Python

I am trying to convert positions in a raster representing a .tif to the corresponding global coordinates.我正在尝试将表示 .tif 的栅格中的位置转换为相应的全局坐标。 Converting the whole array to a tif and load it to QGIS everything is referenced fine, but using the below calculation method for single points there is a slight offset (to east-north-east in the resulting coordinates....将整个数组转换为 tif 并将其加载到 QGIS 一切都很好,但是使用下面的单点计算方法有轻微的偏移(结果坐标中的东西向......

raster.tif uses ETRS 89 UTM Zone 32N raster.tif 使用 ETRS 89 UTM Zone 32N

Does anyone has an idea?有没有人有想法?

from osgeo import ogr, gdal, osr
import numpy as np


raster = gdal.Open("rasters/raster.tif")
raster_array = np.array(raster.ReadAsArray())


def pixel2coord(x, y):
     xoff, a, b, yoff, d, e = raster.GetGeoTransform()
     xp = a * x + b * y + xoff
     yp = d * x + e * y + yoff
     return(xp, yp)


print(pixel2cood(500,598))

I think the issue might be that the xoff and yoff contain coordinates of the upper left corner of the most upper left pixel, and you need to calculate coordinates of the pixel's center.我认为问题可能是 xoff 和 yoff 包含最左上角像素左上角的坐标,您需要计算像素中心的坐标。

def pixel2coord(x, y):
    xoff, a, b, yoff, d, e = raster.GetGeoTransform()

    xp = a * x + b * y + a * 0.5 + b * 0.5 + xoff
    yp = d * x + e * y + d * 0.5 + e * 0.5 + yoff
    return(xp, yp)

There is no reason to do this manually.没有理由手动执行此操作。 You just need to install rasterio, a python library based on GDAL and numpy.你只需要安装rasterio,一个基于GDAL和numpy的python库。 Even if the image has an offset/rotation rasterio will take care of it.即使图像具有偏移/旋转光栅也会处理它。

You just have to do:你只需要这样做:

import rasterio

with rasterio.open('rasters/raster.tif') as map_layer:
    coords2pixels = map_layer.index(235059.32,810006.31) #input lon,lat
    pixels2coords = map_layer.xy(500,598)  #input px, py

Both functions return a tuple of the pixels and coordinates respectively.这两个函数分别返回像素和坐标的元组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM