1

I am using matplotlib along with the basemap with the following code

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)

This is the output Sample image

However this is saving the whole map as an image. Is there is a way to save just a small extent of this map as a png by passing in an extent object as one of the arguments in the plt.savefig method? or is there any other way to achieve this?

1
  • Please, share more details about your code and what is / isn't happening. Commented Jul 14, 2020 at 11:54

1 Answer 1

0

Hmm, here's a somewhat roundabout idea to solve this problem. You can crop a PIL Image object, by specifying pixels to crop like so: https://stackoverflow.com/a/43591567/13095028. The cropped image can then be saved to disk with Image.save(). You can also convert a matplotlib figure to PIL Image like so: https://stackoverflow.com/a/61755066/13095028.

Combining these ideas gives the following which you can plug under your existing code. You'll need to convert your bbox from inches to pixels.

# 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")
Sign up to request clarification or add additional context in comments.

1 Comment

my bounding box is a geographic extent

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.