Hello list

I've trying for a while a "python only" solution to remove white spaces that Basemap generate to keep the aspect ratio. I found these two threads that explain  the issue better:


In the past I relied on  ImageMagick's "convert" command with the  "-trim white" option for the job. However, just recently I came across with this other list and a  PIL solution:


Here is how I'm doing:

savefig('mapa.png', dpi=300)

from PIL import Image
im = Image.open("mapa.png")

def trim(im, border):
  from PIL import ImageChops
  bg = Image.new(im.mode, im.size, border)
  diff = ImageChops.difference(im, bg)
  bbox = diff.getbbox()
  if bbox:
      return im.crop(bbox)
      # found no content
      raise ValueError("cannot trim; image was empty")


This works and the aspect ratio is preserved, but as you can see, it is not a very smart implementation.  I save and then reload it again... any suggestions to improve this are welcome.

Also, I have not tried this on figures with labels and annotations.

Thanks for any input.

Filipe Pires Alvarenga Fernandes

University of Massachusetts Dartmouth
200 Mill Road - Fairhaven, MA
Tel: (508) 910-6381
Email: falvarengafernandes@umassd.edu