python - Python:如何避免调用两个函数的循环?
问题描述
我从 worldpop.org 下载了一张包含海地人口的 geottif图像。
图片可以从这里下载
from osgeo import gdal
import matplotlib.pyplot as plt
from matplotlib import cm
fileO = 'HTI_ppp_v2b_2015_UNadj_32618.tif'
geo = gdal.Open(fileO)
topo = geo.ReadAsArray()
i, j = np.where(topo>0)
topo = topo[min(i):max(i)+1, min(j):max(j)+1]
topo[topo<0] = np.nan
fig = plt.figure(frameon=False)
plt.imshow(topo, cmap=cm.BrBG_r)
plt.axis('off')
cbar = plt.colorbar(shrink=0.75)
cbar.set_label('meters')
plt.show()
我想将每个值分配给一个坐标,即像素的质心坐标,并有一个如下所示的数据框
df_coord:
X_centr Y_centr Pop
0 650000 2050000 54
1 556000 2250000 NaN
这是我正在做的,但这个过程需要太多时间。
import affine
import pandas as pd
def retrieve_pixel_value(geo_coord, data_source):
"""Return floating-point value that corresponds to given point."""
x, y = geo_coord[0], geo_coord[1]
forward_transform = \
affine.Affine.from_gdal(*data_source.GetGeoTransform())
reverse_transform = ~forward_transform
px, py = reverse_transform * (x, y)
px, py = int(px + 0.5), int(py + 0.5)
pixel_coord = px, py
data_array = np.array(data_source.GetRasterBand(1).ReadAsArray())
return data_array[pixel_coord[0]][pixel_coord[1]]
def pixel2coord(col, row):
"""Returns global coordinates to pixel center using base-0 raster index"""
xp = a * col + b * row + a * 0.5 + b * 0.5 + c
yp = d * col + e * row + d * 0.5 + e * 0.5 + f
return(xp, yp)
fileO = 'HTI_ppp_v2b_2015_UNadj_32618.tif'
geo = gdal.Open(fileO)
topo = geo.ReadAsArray()
i, j = np.where(topo>0)
topo = topo[min(i):max(i)+1, min(j):max(j)+1]
x_coord = []
y_coord = []
val = []
for idx in range(0,len(i)):
ii = i[idx]
jj = j[idx]
coords = pixel2coord(ii, jj) ## find coordinates of the pixel
x_coord.append(coords[0])
y_coord.append(coords[1])
pop = retrieve_pixel_value(coords, geo) ## retrieve pixel value at given coordinates - coords
val.append(pop)
import pandas as pd
df_coord = pd.DataFrame()
df_coord['X_coord'] = ii
df_coord['Y_coord'] = jj
df_coord['Pop'] = val
不做循环是否可以做同样的事情?
解决方案
推荐阅读
- angular - 在 mat-dialog 中填充组件的输入
- php - 努力将数组结构转换为 PHP 中的递归树
- docker - 远程访问运行在 kubernetes 中的 Kafka
- node.js - 如何使用直接 url 访问 node.js 站点而不在 aws ubuntu、Apache2 中提及端口 8080
- c# - 无法通过 C# 保存 excel 文件
- sql-server - 访问 Azure SQL 数据库中的 AD 组
- c# - 如何在.NET Framework下通过autofac将'TeamSpecificConversationState'、'DropNonTeamsActivitiesMiddleware'和'TeamsMiddleware'注入Bot
- laravel - 执行项目时,laravel 应用程序首先运行哪个页面
- android - 我得到一个 Android.Content.Res.Resources+NotFoundException 试图启动应用程序
- qt - 无法添加QT版本