python - 如何将 geopandas 图提取为由像素数值组成的 numpy 数组?

标签 python matplotlib geopandas shapely

我有一个 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())

这是一个最小的工作示例。我的实际问题是我有一个包含数千个 GeoDataFrame 的列表,“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 将图形 Canvas 作为 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)

关于python - 如何将 geopandas 图提取为由像素数值组成的 numpy 数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57993200/

相关文章:

python - 想要胖错误栏

python - 旋转 Geoplot 多重图

python - 如何限制使用GeoPandas读取的特征数量?

python - 查找数据集中的异常值

python - 我如何找到字符串中多个子字符串的位置(Python 3.4.3 shell)

python - 将 OneHotEncoder 与 sklearn_pandas DataFrameMapper 结合使用

python - 如何使用 Matplotlib 在 Python 中将 for 循环中的自定义绘图添加/附加到单个子图?

python进程占用100% CPU

python - 使用 Seaborn 为 x 轴绘制超过 10K 的数据点作为时间戳

python - 如何解决 "GeoDataFrame object has not attribute..."错误