Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 3124bda

Browse files
committed
Small improvements to canvasagg example.
In particular, show how Pillow can be used to save images in formats not directly supported by Matplotlib. Also directly convert the buffer to an array (with only brief, in-passing mention of memoryviews), as memoryviews are rather technical.
1 parent 11258c2 commit 3124bda

File tree

1 file changed

+12
-8
lines changed

1 file changed

+12
-8
lines changed

examples/user_interfaces/canvasagg.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@
1414
the backend to "Agg" would be sufficient.
1515
1616
In this example, we show how to save the contents of the agg canvas to a file,
17-
and how to extract them to a string, which can in turn be passed off to PIL or
18-
put in a numpy array. The latter functionality allows e.g. to use Matplotlib
19-
inside a cgi-script *without* needing to write a figure to disk.
17+
and how to extract them to a numpy array, which can in turn be passed off
18+
to Pillow_. The latter functionality allows e.g. to use Matplotlib inside a
19+
cgi-script *without* needing to write a figure to disk, and to write images in
20+
any format supported by Pillow.
21+
22+
.. _Pillow: https://pillow.readthedocs.io/
2023
"""
2124

2225
from matplotlib.backends.backend_agg import FigureCanvasAgg
@@ -39,13 +42,14 @@
3942
# etc.).
4043
fig.savefig("test.png")
4144

42-
# Option 2: Retrieve a view on the renderer buffer...
45+
# Option 2: Retrieve a memoryview on the renderer buffer, and convert it to a
46+
# numpy array.
4347
canvas.draw()
44-
buf = canvas.buffer_rgba()
45-
# ... convert to a NumPy array ...
46-
X = np.asarray(buf)
48+
rgba = np.asarray(canvas.buffer_rgba())
4749
# ... and pass it to PIL.
48-
im = Image.fromarray(X)
50+
im = Image.fromarray(rgba)
51+
# This image can then be saved to any format supported by Pillow, e.g.:
52+
im.save("test.bmp")
4953

5054
# Uncomment this line to display the image using ImageMagick's `display` tool.
5155
# im.show()

0 commit comments

Comments
 (0)