如何将 geopandas 图提取为由像素数值组成的 numpy 数组?
How to extract a geopandas plot as a numpy array that consists of numerical values of the pixels?
我有一个 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 "backend agg to acces the figure canvas as an RGB string and then convert it ot an array" (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)
我有一个 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 "backend agg to acces the figure canvas as an RGB string and then convert it ot an array" (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)