首页 > 解决方案 > 如何将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 文件。有任何想法吗?

标签: pythonmatplotlibgeopandasshapely

解决方案


我为我找到了一个可行的解决方案。我没有将每张图片保存和打开为 .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)

推荐阅读