使用 matplotlib 仅保存地图的一部分 python

save only an extent of the map using matplotlib python

我将 matplotlib 与底图一起使用,代码如下

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap,cm

#Map Center
core = (151.35,-23.92)

LAT = core[1]
LON = core[0]
zoom_scale = 5/111
#create a bounding box from the central co=ordinates
bbox = [LAT-zoom_scale,LAT+zoom_scale, LON-zoom_scale,LON+zoom_scale]

#create an instance of the basemap object
m = Basemap(epsg=4326,llcrnrlat=bbox[0],urcrnrlat=bbox[1],\
                 llcrnrlon=bbox[2],urcrnrlon=bbox[3],resolution='i')

#Add and arcgis basemap
m.arcgisimage(service="World_Imagery", xpixels=7000, verbose=False)   
t = Bbox.from_extents(151.324,-23.9414,151.357,-23.9117)

#save the image
plt.savefig(plotOutDir+'/'+ "new", bbox_inches = t,pad_inches = 0)

这是输出 Sample image

然而,这是将整个地图保存为图像。 有没有办法通过传入一个范围对象作为 plt.savefig 方法中的参数之一来将此地图的一小部分保存为 png? 或者还有其他方法可以实现吗?

嗯,这里有一个有点绕弯子的想法来解决这个问题。您可以通过指定要裁剪的像素来裁剪 PIL Image 对象:. The cropped image can then be saved to disk with Image.save(). You can also convert a matplotlib figure to PIL Image like so: .

结合这些想法,您可以将其插入现有代码中。您需要将 bbox 从英寸转换为像素。

# Import PIL
from PIL import Image

# Grab current figure object
fig = plt.gcf()

# Use code snippet from 2nd link to convert matplotlib fig to PIL Image
def fig2img(fig):
    """Convert a Matplotlib figure to a PIL Image and return it"""
    import io
    buf = io.BytesIO()
    fig.savefig(buf)
    buf.seek(0)
    img = Image.open(buf)
    return img

img = fig2img(fig)

# Use code from 1st link to crop and save
# Note: Fill in your bbox area in pixels here!!
area = (400, 400, 800, 800)
cropped_img = img.crop(area)
cropped_img.save(plotOutDir+'/'+ "new")