python - 如何将geopandas图提取为由像素数值组成的numpy数组?
问题描述
我有一个 GeoDataFrame,我想获得一个对应于 GeoDataFrame.plot() 的 numpy 数组。
目前,我的代码如下所示:
import numpy as np
import geopandas as gpd
from shapely.geometry import Polygon
import matplotlib.pyplot as plt
from PIL import Image
# Create GeoDataFrame
poly_list = [Polygon([[0, 0], [1, 0], [1, 1], [0, 1]])]
polys_gdf = gpd.GeoDataFrame(geometry=poly_list)
# Save plot with matplotlib
plt.ioff()
polys_gdf.plot()
plt.savefig('plot.png')
plt.close()
# Open file and convert to array
img = Image.open('plot.png')
arr = np.array(img.getdata())
这是一个最小的工作示例。我的实际问题是我有一个包含数千个 GeoDataFrames 的列表,“list_of_gdf”。
我的第一个想法是循环运行它:
arr_list = []
for element in list_of_gdf:
plt.ioff()
element.plot()
plt.savefig('plot.png')
plt.close()
img = Image.open('plot.png')
arr_list.append(np.array(img.getdata()))
这似乎可以以更快的方式完成,而不是保存和打开每个 .png 文件。有任何想法吗?
解决方案
我为我找到了一个可行的解决方案。我没有将每张图片保存和打开为 .png,而是使用 matplotlib“后端 agg 将图形画布作为 RGB 字符串访问,然后将其转换为数组”(https://matplotlib.org/3.1.0/gallery/misc /agg_buffer.html )。
arr_list = []
for element in list_of_gdf:
plt.close('all')
fig, ax = plt.subplots()
ax.axis('off')
element.plot(ax = ax)
fig.canvas.draw()
arr = np.array(fig.canvas.renderer.buffer_rgba())
arr_list.append(arr)
推荐阅读
- javascript - Javascript从数组中搜索并删除多个对象
- python - 猜字游戏 - 每次循环运行时选择随机单词的问题
- swiftui - 如何使用@FocusedBinding
- javascript - jquery:如何更改列表中的跨度属性
- ios - Swift——UITextField 没有显示键盘,我无法编辑它
- javascript - 在条件三元中处理多个 useState
- terraform - 防止 Terraform 破坏特定资源
- javascript - 从javascript中的下拉列表创建文本框
- sql - 计算具有特定条件的出现次数
- node.js - AWS Lambda DynamoDB putItem 总是执行两次