Thanks Friedrich,
However, my knowledge of python is very limited, even though I think I
understood what you suggested I do not know how to get the shape (of
the figure?) for this part:
>>> fig.set_size_inches(float(shape[0]) / dpi, float(shape[1]) / dpi)
error is:
Traceback (most recent call last):
File "blueearth-map.py", line 108, in <module>
fig.set_size_inches(float(shape[0]) / dpi, float(shape[1]) / dpi)
TypeError: 'function' object is unsubscriptable
It seems that it ended up calling a function shape instead of a variable shape.
I'm sending attached the script if you are interested in looking at it.
Thanks again. Filipe.
On Sun, Mar 28, 2010 at 3:35 PM, Friedrich Romstedt
<friedrichromst...@gmail.com> wrote:
>
> 2010/3/28 Filipe Pires Alvarenga Fernandes <ocef...@gmail.com>:
> > 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:
>
> I think maybe you can make use of the Agg Backend to achieve a
> Python-only solution to obtain a PIL Image from a figure without
> bypassing over the HDD:
>
> Furthemore, if this doesn't work, maybe you can use a StringIO as
> "file", then seek() the StringIO and reread with PIL from the
> "file-like" StringIO, or something like that?
>
> #
> # Render the Figure to a PIL Image ...
> #
>
> # Prepare figure to be of pixel extent *shape* ...
>
> dpi = figure.dpi
> figure.set_size_inches(float(shape[0]) / dpi, float(shape[1]) / dpi)
>
> # Create the rendering Canvas ...
> #
> # We also convert the picture to an RGB string.
>
> canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(figure)
> canvas.draw()
> image_string = canvas.tostring_rgb()
>
> # Create a PIL Image from RGB string ...
>
> image = Image.fromstring("RGB", shape, image_string)
>
> # Now do whatever you want with the Image.
>
> Friedrich
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# blueearth-map.py
# update brazillian states database, this one is too old!!!!
import sys
import os
""" import basemap and pylab """
try:
from mpl_toolkits.basemap import Basemap
except ImportError:
print "Basemap not found."
try:
import matplotlib
matplotlib.use('Agg')
from pylab import *
except ImportError:
print "Matplotlib not found."
# parse args (ugly!)
if len(sys.argv) == 6:
lonmin = float(sys.argv[2])
lonmax = float(sys.argv[3])
latmin = float(sys.argv[4])
latmax = float(sys.argv[5])
lonlat = np.loadtxt(sys.argv[1])
lonpt = lonlat[:,0]
latpt = lonlat[:,1]
elif len(sys.argv) == 5:
lonmin = float(sys.argv[1])
lonmax = float(sys.argv[2])
latmin = float(sys.argv[3])
latmax = float(sys.argv[4])
else:
sys.exit("""\nMust provide at least 4 arguments!!!
A 2 column file with longitue and latitute of the points (optional)
and the lon lat limits for the map.
e.g.: blueearth-map lonlat.dat -87.5 -22.5 -59.5 14.5\n""")
m = Basemap( projection = 'merc',
llcrnrlat = latmin, urcrnrlat = latmax,
llcrnrlon = lonmin, urcrnrlon = lonmax,
resolution = 'c' ) # crude coastlines resolution
""" create figure and associate axes with Basemap """
fig = figure()
ax = fig.add_subplot(111)
m.ax = ax
m.drawstates()
m.drawcountries(linewidth=1.2)
m.bluemarble()
""" add a non bluearth alternative"""
#m.drawcoastlines()
#m.drawlsmask(land_color='grey',ocean_color='None', lakes=True)
""" plot points """
try:
lonpt
xc,yc = m(lonpt,latpt)
#m.plot(xc,yc,'ro', alpha = 0.5, markersize=2)
m.plot(xc,yc,'ro', markersize=2)
if lonpt.min() < lonmin:
print "\n some points are out of bounds (min longitude) \n"
if lonpt.max() > lonmax:
print "\n some points are out of bounds (max longitude) \n"
if latpt.min() < latmin:
print "\n some points are out of bounds (min latitude) \n"
if latpt.max() > latmax:
print "\n some points are out of bounds (max latitude) \n"
except:
print "\n No lon/lat file to plot \n"
savefig('blueearthmap.png', dpi=300)
""" trim method 1 """
from PIL import Image
im = Image.open("blueearthmap.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)
else:
# found no content
raise ValueError("cannot trim; image was empty")
im2=trim(im,'white')
show() # allow user to save to a different filename and format, but it won't be cropped!
im2.save('blueearthmap.png',format='png')
#---------------------------------------------------------
""" trim method 2 """
#os.system('convert -trim blueearthmap.png blueearthmap.png')
#show()
#---------------------------------------------------------
""" trim method 3 """
#Render the Figure to a PIL Image
# Prepare figure to be of pixel extent *shape*
dpi = fig.dpi
fig.set_size_inches(float(shape[0]) / dpi, float(shape[1]) / dpi)
# Create the rendering Canvas. We also convert the picture to an RGB string.
canvas = matplotlib.backends.backend_agg.FigureCanvasAgg(fig)
canvas.draw()
image_string = canvas.tostring_rgb()
# Create a PIL Image from RGB string ...
image = Image.fromstring("RGB", shape, image_string)
# Now do whatever you want with the Image.
im3 = trim(image, 'white')
------------------------------------------------------------------------------
Download Intel® Parallel Studio Eval
Try the new software tools for yourself. Speed compiling, find bugs
proactively, and fine-tune applications for parallel performance.
See why Intel Parallel Studio got high marks during beta.
http://p.sf.net/sfu/intel-sw-dev
_______________________________________________
Matplotlib-users mailing list
Matplotlib-users@lists.sourceforge.net
https://lists.sourceforge.net/lists/listinfo/matplotlib-users