我尝试使用点位置从光栅图像中提取值。
我的数据包括:
test_gdf
.from sklearn.model_selection import train_test_split
train_gdf, test_gdf = train_test_split(gdf, test_size=0.33, random_state=42)
Z
.首先,我使用
affine
库将点位置转换为像素坐标。然后使用 numpy 索引从点的像素坐标处的光栅图像中提取值。
import numpy as np
import pandas as pd
import geopandas as gpd
from affine import Affine
xmin, ymin, xmax, ymax = gdf.total_bounds
aff = Affine(10.0, 0.0, xmin, 0.0, -10.0, ymax)
# https://www.perrygeo.com/python-affine-transforms.html
test_gdf['col'], test_gdf['row'] = ~aff * (test_gdf.geometry.x, test_gdf.geometry.y)
test_gdf['NN_estimate'] = Z[test_gdf.row.astype(int), test_gdf.col.astype(int)]
然而,当我比较QGIS中的结果时,发现在Python中提取了错误的像素值。这是因为转换后的坐标
test_gdf.row.astype(int)
和 test_gdf.col.astype(int)
被逆时针翻转了 90 度,因此它们与错误的像素对齐。
下图显示:转换后的像素位置逆时针翻转90度(左); QGIS 中显示的真实位置(右)
然后我尝试交换
row
和col
.
test_gdf['row'], test_gdf['col'] = ~aff * (test_gdf.geometry.x, test_gdf.geometry.y)
test_gdf['NN_estimate'] = Z[test_gdf.col.astype(int), test_gdf.row.astype(int)]
但是颠倒了点位置并且也超出了图像范围...
现在我真的很困惑
affine
转换是如何工作的,不知道如何解决它。