""" An agg http://antigrain.com/ backend
Features that are implemented
* capstyles and join styles * dashes * linewidth * lines, rectangles, ellipses * clipping to a rectangle * output to RGBA and PNG, optionally JPEG and TIFF * alpha blending * DPI scaling properly - everything scales properly (dashes, linewidths, etc) * draw polygon * freetype2 w/ ft2font
TODO:
* integrate screen dpi w/ ppi and text
""" except ImportError: import dummy_threading as threading _Backend, FigureCanvasBase, FigureManagerBase, RendererBase) LOAD_DEFAULT, LOAD_NO_AUTOHINT)
True: LOAD_FORCE_AUTOHINT, False: LOAD_NO_HINTING, 'either': LOAD_DEFAULT, 'native': LOAD_NO_AUTOHINT, 'auto': LOAD_FORCE_AUTOHINT, 'none': LOAD_NO_HINTING }
""" The renderer handles all the drawing primitives using a graphics context instance that controls the colors/styles """
# we want to cache the fonts at the class level so that when # multiple figures are created we can reuse them. This helps with # a bug on windows where the creation of too many figures leads to # too many open file handles. However, storing them at the class # level is not thread safe. The solution here is to let the # FigureCanvas acquire a lock on the fontd at the start of the # draw, and release it when it is done. This allows multiple # renderers to share the cached fonts, but only one figure can # draw at time and so the font cache is used by only one # renderer at a time.
# We only want to preserve the init keywords of the Renderer. # Anything else can be re-created. return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
self.__init__(state['width'], state['height'], state['dpi'])
extents = self.get_content_extents() bbox = [[extents[0], self.height - (extents[1] + extents[3])], [extents[0] + extents[2], self.height - extents[1]]] region = self.copy_from_bbox(bbox) return np.array(region), extents
""" Draw the path """
rgbFace is None and gc.get_hatch() is None): nch = np.ceil(npts / nmax) chsize = int(np.ceil(npts / nch)) i0 = np.arange(0, npts, chsize) i1 = np.zeros_like(i0) i1[:-1] = i0[1:] - 1 i1[-1] = npts for ii0, ii1 in zip(i0, i1): v = path.vertices[ii0:ii1, :] c = path.codes if c is not None: c = c[ii0:ii1] c[0] = Path.MOVETO # move to end of last chunk p = Path(v, c) try: self._renderer.draw_path(gc, p, transform, rgbFace) except OverflowError: raise OverflowError("Exceeded cell block limit (set " "'agg.path.chunksize' rcparam)") else: except OverflowError: raise OverflowError("Exceeded cell block limit (set " "'agg.path.chunksize' rcparam)")
""" Draw the math text using matplotlib.mathtext """ self.mathtext_parser.parse(s, self.dpi, prop)
""" Render the text """
return None font.load_char(ord(s), flags=flags) else: # We pass '0' for angle here, since it will be rotated (in raster # space) in the following call to draw_text_image). # The descent needs to be adjusted for the angle.
font, np.round(x - xd + xo), np.round(y + yd + yo) + 1, angle, gc)
""" Get the width, height, and descent (offset from the bottom to the baseline), in display coords, of the string *s* with :class:`~matplotlib.font_manager.FontProperties` *prop* """ # todo: handle props size = prop.get_size_in_points() texmanager = self.get_texmanager() fontsize = prop.get_size_in_points() w, h, d = texmanager.get_text_width_height_descent( s, fontsize, renderer=self) return w, h, d
self.mathtext_parser.parse(s, self.dpi, prop)
# todo, handle props, angle, origins size = prop.get_size_in_points()
texmanager = self.get_texmanager()
Z = texmanager.get_grey(s, size, self.dpi) Z = np.array(Z * 255.0, np.uint8)
w, h, d = self.get_text_width_height_descent(s, prop, ismath) xd = d * sin(radians(angle)) yd = d * cos(radians(angle)) x = np.round(x + xd) y = np.round(y + yd)
self._renderer.draw_text_image(Z, x, y, angle, gc)
'return the canvas width and height in display coords'
""" Get the font for text instance t, caching for efficiency """
""" convert point measures to pixes using dpi and the pixels per inch of the display """
return self._renderer.tostring_rgb()
return self._renderer.tostring_argb()
return self._renderer.buffer_rgba()
# It is generally faster to composite each image directly to # the Figure, and there's no file size benefit to compositing # with the Agg backend
""" agg backend doesn't support arbitrary scaling of image. """ return False
""" Restore the saved region. If bbox (instance of BboxBase, or its extents) is given, only the region specified by the bbox will be restored. *xy* (a tuple of two floasts) optionally specifies the new position (the LLC of the original region, not the LLC of the bbox) where the region will be restored.
>>> region = renderer.copy_from_bbox() >>> x1, y1, x2, y2 = region.get_extents() >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2), ... xy=(x1-dx, y1))
""" if bbox is not None or xy is not None: if bbox is None: x1, y1, x2, y2 = region.get_extents() elif isinstance(bbox, BboxBase): x1, y1, x2, y2 = bbox.extents else: x1, y1, x2, y2 = bbox
if xy is None: ox, oy = x1, y1 else: ox, oy = xy
# The incoming data is float, but the _renderer type-checking wants # to see integers. self._renderer.restore_region(region, int(x1), int(y1), int(x2), int(y2), int(ox), int(oy))
else: self._renderer.restore_region(region)
""" Start filtering. It simply create a new canvas (the old one is saved). """ self._filter_renderers.append(self._renderer) self._renderer = _RendererAgg(int(self.width), int(self.height), self.dpi) self._update_methods()
""" Save the plot in the current canvas as a image and apply the *post_processing* function.
def post_processing(image, dpi): # ny, nx, depth = image.shape # image (numpy array) has RGBA channels and has a depth of 4. ... # create a new_image (numpy array of 4 channels, size can be # different). The resulting image may have offsets from # lower-left corner of the original image return new_image, offset_x, offset_y
The saved renderer is restored and the returned image from post_processing is plotted (using draw_image) on it. """
width, height = int(self.width), int(self.height)
buffer, (l, b, w, h) = self.tostring_rgba_minimized()
self._renderer = self._filter_renderers.pop() self._update_methods()
if w > 0 and h > 0: img = np.fromstring(buffer, np.uint8) img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255., self.dpi) gc = self.new_gc() if img.dtype.kind == 'f': img = np.asarray(img * 255., np.uint8) img = img[::-1] self._renderer.draw_image(gc, l + ox, height - b - h + oy, img)
""" The canvas the figure renders into. Calls the draw and print fig methods, creates the renderers, etc...
Attributes ---------- figure : `matplotlib.figure.Figure` A high-level Figure instance
"""
renderer = self.get_renderer() return renderer.copy_from_bbox(bbox)
renderer = self.get_renderer() return renderer.restore_region(region, bbox, xy)
""" Draw the figure using the renderer. """ # acquire a lock on the shared font cache
# A GUI class may be need to update a window using this draw, so # don't forget to call the superclass. finally:
'''Get the image as an RGB byte string.
`draw` must be called at least once before this function will work and to update the renderer for any subsequent changes to the Figure.
Returns ------- bytes ''' return self.renderer.tostring_rgb()
'''Get the image as an ARGB byte string
`draw` must be called at least once before this function will work and to update the renderer for any subsequent changes to the Figure.
Returns ------- bytes
''' return self.renderer.tostring_argb()
'''Get the image as an RGBA byte string.
`draw` must be called at least once before this function will work and to update the renderer for any subsequent changes to the Figure.
Returns ------- bytes ''' return self.renderer.buffer_rgba()
FigureCanvasAgg.draw(self) renderer = self.get_renderer() with cbook._setattr_cm(renderer, dpi=self.figure.dpi), \ cbook.open_file_cm(filename_or_obj, "wb") as fh: fh.write(renderer._renderer.buffer_rgba())
""" Write the figure to a PNG file.
Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to.
metadata : dict, optional Metadata in the PNG file as key-value pairs of bytes or latin-1 encodable strings. According to the PNG specification, keys must be shorter than 79 chars.
The `PNG specification`_ defines some common keywords that may be used as appropriate:
- Title: Short (one line) title or caption for image. - Author: Name of image's creator. - Description: Description of image (possibly long). - Copyright: Copyright notice. - Creation Time: Time of original image creation (usually RFC 1123 format). - Software: Software used to create the image. - Disclaimer: Legal disclaimer. - Warning: Warning of nature of content. - Source: Device used to create the image. - Comment: Miscellaneous comment; conversion from other image format.
Other keywords may be invented for other purposes.
If 'Software' is not given, an autogenerated value for matplotlib will be used.
For more details see the `PNG specification`_.
.. _PNG specification: \ https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
"""
'matplotlib version ' + __version__ + ', http://matplotlib.org/') metadata.update(user_metadata)
cbook.open_file_cm(filename_or_obj, "wb") as fh: self.figure.dpi, metadata=metadata)
FigureCanvasAgg.draw(self) renderer = self.get_renderer() with cbook._setattr_cm(renderer, dpi=self.figure.dpi): return (renderer._renderer.buffer_rgba(), (int(renderer.width), int(renderer.height)))
# add JPEG support """ Write the figure to a JPEG file.
Parameters ---------- filename_or_obj : str or PathLike or file-like object The file to write to.
Other Parameters ---------------- quality : int The image quality, on a scale from 1 (worst) to 100 (best). The default is :rc:`savefig.jpeg_quality`. Values above 95 should be avoided; 100 completely disables the JPEG quantization stage.
optimize : bool If present, indicates that the encoder should make an extra pass over the image in order to select optimal encoder settings.
progressive : bool If present, indicates that this image should be stored as a progressive JPEG file. """ buf, size = self.print_to_buffer() if dryrun: return # The image is "pasted" onto a white background image to safely # handle any transparency image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) rgba = mcolors.to_rgba(rcParams['savefig.facecolor']) color = tuple([int(x * 255) for x in rgba[:3]]) background = Image.new('RGB', size, color) background.paste(image, image) options = {k: kwargs[k] for k in ['quality', 'optimize', 'progressive', 'dpi'] if k in kwargs} options.setdefault('quality', rcParams['savefig.jpeg_quality']) if 'dpi' in options: # Set the same dpi in both x and y directions options['dpi'] = (options['dpi'], options['dpi'])
return background.save(filename_or_obj, format='jpeg', **options)
# add TIFF support buf, size = self.print_to_buffer() if dryrun: return image = Image.frombuffer('RGBA', size, buf, 'raw', 'RGBA', 0, 1) dpi = (self.figure.dpi, self.figure.dpi) return image.save(filename_or_obj, format='tiff', dpi=dpi)
|