backend_agg.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. """
  2. An agg http://antigrain.com/ backend
  3. Features that are implemented
  4. * capstyles and join styles
  5. * dashes
  6. * linewidth
  7. * lines, rectangles, ellipses
  8. * clipping to a rectangle
  9. * output to RGBA and PNG, optionally JPEG and TIFF
  10. * alpha blending
  11. * DPI scaling properly - everything scales properly (dashes, linewidths, etc)
  12. * draw polygon
  13. * freetype2 w/ ft2font
  14. TODO:
  15. * integrate screen dpi w/ ppi and text
  16. """
  17. try:
  18. import threading
  19. except ImportError:
  20. import dummy_threading as threading
  21. try:
  22. from contextlib import nullcontext
  23. except ImportError:
  24. from contextlib import ExitStack as nullcontext # Py 3.6.
  25. from math import radians, cos, sin
  26. import numpy as np
  27. from matplotlib import cbook, rcParams, __version__
  28. from matplotlib.backend_bases import (
  29. _Backend, FigureCanvasBase, FigureManagerBase, RendererBase)
  30. from matplotlib.font_manager import findfont, get_font
  31. from matplotlib.ft2font import (LOAD_FORCE_AUTOHINT, LOAD_NO_HINTING,
  32. LOAD_DEFAULT, LOAD_NO_AUTOHINT)
  33. from matplotlib.mathtext import MathTextParser
  34. from matplotlib.path import Path
  35. from matplotlib.transforms import Bbox, BboxBase
  36. from matplotlib import colors as mcolors
  37. from matplotlib.backends._backend_agg import RendererAgg as _RendererAgg
  38. from matplotlib.backend_bases import _has_pil
  39. if _has_pil:
  40. from PIL import Image
  41. backend_version = 'v2.2'
  42. def get_hinting_flag():
  43. mapping = {
  44. True: LOAD_FORCE_AUTOHINT,
  45. False: LOAD_NO_HINTING,
  46. 'either': LOAD_DEFAULT,
  47. 'native': LOAD_NO_AUTOHINT,
  48. 'auto': LOAD_FORCE_AUTOHINT,
  49. 'none': LOAD_NO_HINTING
  50. }
  51. return mapping[rcParams['text.hinting']]
  52. class RendererAgg(RendererBase):
  53. """
  54. The renderer handles all the drawing primitives using a graphics
  55. context instance that controls the colors/styles
  56. """
  57. # we want to cache the fonts at the class level so that when
  58. # multiple figures are created we can reuse them. This helps with
  59. # a bug on windows where the creation of too many figures leads to
  60. # too many open file handles. However, storing them at the class
  61. # level is not thread safe. The solution here is to let the
  62. # FigureCanvas acquire a lock on the fontd at the start of the
  63. # draw, and release it when it is done. This allows multiple
  64. # renderers to share the cached fonts, but only one figure can
  65. # draw at time and so the font cache is used by only one
  66. # renderer at a time.
  67. lock = threading.RLock()
  68. def __init__(self, width, height, dpi):
  69. RendererBase.__init__(self)
  70. self.dpi = dpi
  71. self.width = width
  72. self.height = height
  73. self._renderer = _RendererAgg(int(width), int(height), dpi)
  74. self._filter_renderers = []
  75. self._update_methods()
  76. self.mathtext_parser = MathTextParser('Agg')
  77. self.bbox = Bbox.from_bounds(0, 0, self.width, self.height)
  78. def __getstate__(self):
  79. # We only want to preserve the init keywords of the Renderer.
  80. # Anything else can be re-created.
  81. return {'width': self.width, 'height': self.height, 'dpi': self.dpi}
  82. def __setstate__(self, state):
  83. self.__init__(state['width'], state['height'], state['dpi'])
  84. def _update_methods(self):
  85. self.draw_gouraud_triangle = self._renderer.draw_gouraud_triangle
  86. self.draw_gouraud_triangles = self._renderer.draw_gouraud_triangles
  87. self.draw_image = self._renderer.draw_image
  88. self.draw_markers = self._renderer.draw_markers
  89. self.draw_path_collection = self._renderer.draw_path_collection
  90. self.draw_quad_mesh = self._renderer.draw_quad_mesh
  91. self.copy_from_bbox = self._renderer.copy_from_bbox
  92. self.get_content_extents = self._renderer.get_content_extents
  93. def tostring_rgba_minimized(self):
  94. extents = self.get_content_extents()
  95. bbox = [[extents[0], self.height - (extents[1] + extents[3])],
  96. [extents[0] + extents[2], self.height - extents[1]]]
  97. region = self.copy_from_bbox(bbox)
  98. return np.array(region), extents
  99. def draw_path(self, gc, path, transform, rgbFace=None):
  100. # docstring inherited
  101. nmax = rcParams['agg.path.chunksize'] # here at least for testing
  102. npts = path.vertices.shape[0]
  103. if (nmax > 100 and npts > nmax and path.should_simplify and
  104. rgbFace is None and gc.get_hatch() is None):
  105. nch = np.ceil(npts / nmax)
  106. chsize = int(np.ceil(npts / nch))
  107. i0 = np.arange(0, npts, chsize)
  108. i1 = np.zeros_like(i0)
  109. i1[:-1] = i0[1:] - 1
  110. i1[-1] = npts
  111. for ii0, ii1 in zip(i0, i1):
  112. v = path.vertices[ii0:ii1, :]
  113. c = path.codes
  114. if c is not None:
  115. c = c[ii0:ii1]
  116. c[0] = Path.MOVETO # move to end of last chunk
  117. p = Path(v, c)
  118. try:
  119. self._renderer.draw_path(gc, p, transform, rgbFace)
  120. except OverflowError:
  121. raise OverflowError("Exceeded cell block limit (set "
  122. "'agg.path.chunksize' rcparam)")
  123. else:
  124. try:
  125. self._renderer.draw_path(gc, path, transform, rgbFace)
  126. except OverflowError:
  127. raise OverflowError("Exceeded cell block limit (set "
  128. "'agg.path.chunksize' rcparam)")
  129. def draw_mathtext(self, gc, x, y, s, prop, angle):
  130. """
  131. Draw the math text using matplotlib.mathtext
  132. """
  133. ox, oy, width, height, descent, font_image, used_characters = \
  134. self.mathtext_parser.parse(s, self.dpi, prop)
  135. xd = descent * sin(radians(angle))
  136. yd = descent * cos(radians(angle))
  137. x = round(x + ox + xd)
  138. y = round(y - oy + yd)
  139. self._renderer.draw_text_image(font_image, x, y + 1, angle, gc)
  140. def draw_text(self, gc, x, y, s, prop, angle, ismath=False, mtext=None):
  141. # docstring inherited
  142. if ismath:
  143. return self.draw_mathtext(gc, x, y, s, prop, angle)
  144. flags = get_hinting_flag()
  145. font = self._get_agg_font(prop)
  146. if font is None:
  147. return None
  148. # We pass '0' for angle here, since it will be rotated (in raster
  149. # space) in the following call to draw_text_image).
  150. font.set_text(s, 0, flags=flags)
  151. font.draw_glyphs_to_bitmap(antialiased=rcParams['text.antialiased'])
  152. d = font.get_descent() / 64.0
  153. # The descent needs to be adjusted for the angle.
  154. xo, yo = font.get_bitmap_offset()
  155. xo /= 64.0
  156. yo /= 64.0
  157. xd = d * sin(radians(angle))
  158. yd = d * cos(radians(angle))
  159. x = round(x + xo + xd)
  160. y = round(y + yo + yd)
  161. self._renderer.draw_text_image(font, x, y + 1, angle, gc)
  162. def get_text_width_height_descent(self, s, prop, ismath):
  163. # docstring inherited
  164. if ismath in ["TeX", "TeX!"]:
  165. # todo: handle props
  166. texmanager = self.get_texmanager()
  167. fontsize = prop.get_size_in_points()
  168. w, h, d = texmanager.get_text_width_height_descent(
  169. s, fontsize, renderer=self)
  170. return w, h, d
  171. if ismath:
  172. ox, oy, width, height, descent, fonts, used_characters = \
  173. self.mathtext_parser.parse(s, self.dpi, prop)
  174. return width, height, descent
  175. flags = get_hinting_flag()
  176. font = self._get_agg_font(prop)
  177. font.set_text(s, 0.0, flags=flags)
  178. w, h = font.get_width_height() # width and height of unrotated string
  179. d = font.get_descent()
  180. w /= 64.0 # convert from subpixels
  181. h /= 64.0
  182. d /= 64.0
  183. return w, h, d
  184. def draw_tex(self, gc, x, y, s, prop, angle, ismath='TeX!', mtext=None):
  185. # docstring inherited
  186. # todo, handle props, angle, origins
  187. size = prop.get_size_in_points()
  188. texmanager = self.get_texmanager()
  189. Z = texmanager.get_grey(s, size, self.dpi)
  190. Z = np.array(Z * 255.0, np.uint8)
  191. w, h, d = self.get_text_width_height_descent(s, prop, ismath)
  192. xd = d * sin(radians(angle))
  193. yd = d * cos(radians(angle))
  194. x = round(x + xd)
  195. y = round(y + yd)
  196. self._renderer.draw_text_image(Z, x, y, angle, gc)
  197. def get_canvas_width_height(self):
  198. # docstring inherited
  199. return self.width, self.height
  200. def _get_agg_font(self, prop):
  201. """
  202. Get the font for text instance t, caching for efficiency
  203. """
  204. fname = findfont(prop)
  205. font = get_font(fname)
  206. font.clear()
  207. size = prop.get_size_in_points()
  208. font.set_size(size, self.dpi)
  209. return font
  210. def points_to_pixels(self, points):
  211. # docstring inherited
  212. return points * self.dpi / 72
  213. def buffer_rgba(self):
  214. return memoryview(self._renderer)
  215. def tostring_argb(self):
  216. return np.asarray(self._renderer).take([3, 0, 1, 2], axis=2).tobytes()
  217. def tostring_rgb(self):
  218. return np.asarray(self._renderer).take([0, 1, 2], axis=2).tobytes()
  219. def clear(self):
  220. self._renderer.clear()
  221. def option_image_nocomposite(self):
  222. # docstring inherited
  223. # It is generally faster to composite each image directly to
  224. # the Figure, and there's no file size benefit to compositing
  225. # with the Agg backend
  226. return True
  227. def option_scale_image(self):
  228. # docstring inherited
  229. return False
  230. def restore_region(self, region, bbox=None, xy=None):
  231. """
  232. Restore the saved region. If bbox (instance of BboxBase, or
  233. its extents) is given, only the region specified by the bbox
  234. will be restored. *xy* (a pair of floats) optionally
  235. specifies the new position (the LLC of the original region,
  236. not the LLC of the bbox) where the region will be restored.
  237. >>> region = renderer.copy_from_bbox()
  238. >>> x1, y1, x2, y2 = region.get_extents()
  239. >>> renderer.restore_region(region, bbox=(x1+dx, y1, x2, y2),
  240. ... xy=(x1-dx, y1))
  241. """
  242. if bbox is not None or xy is not None:
  243. if bbox is None:
  244. x1, y1, x2, y2 = region.get_extents()
  245. elif isinstance(bbox, BboxBase):
  246. x1, y1, x2, y2 = bbox.extents
  247. else:
  248. x1, y1, x2, y2 = bbox
  249. if xy is None:
  250. ox, oy = x1, y1
  251. else:
  252. ox, oy = xy
  253. # The incoming data is float, but the _renderer type-checking wants
  254. # to see integers.
  255. self._renderer.restore_region(region, int(x1), int(y1),
  256. int(x2), int(y2), int(ox), int(oy))
  257. else:
  258. self._renderer.restore_region(region)
  259. def start_filter(self):
  260. """
  261. Start filtering. It simply create a new canvas (the old one is saved).
  262. """
  263. self._filter_renderers.append(self._renderer)
  264. self._renderer = _RendererAgg(int(self.width), int(self.height),
  265. self.dpi)
  266. self._update_methods()
  267. def stop_filter(self, post_processing):
  268. """
  269. Save the plot in the current canvas as a image and apply
  270. the *post_processing* function.
  271. def post_processing(image, dpi):
  272. # ny, nx, depth = image.shape
  273. # image (numpy array) has RGBA channels and has a depth of 4.
  274. ...
  275. # create a new_image (numpy array of 4 channels, size can be
  276. # different). The resulting image may have offsets from
  277. # lower-left corner of the original image
  278. return new_image, offset_x, offset_y
  279. The saved renderer is restored and the returned image from
  280. post_processing is plotted (using draw_image) on it.
  281. """
  282. width, height = int(self.width), int(self.height)
  283. buffer, (l, b, w, h) = self.tostring_rgba_minimized()
  284. self._renderer = self._filter_renderers.pop()
  285. self._update_methods()
  286. if w > 0 and h > 0:
  287. img = np.frombuffer(buffer, np.uint8)
  288. img, ox, oy = post_processing(img.reshape((h, w, 4)) / 255.,
  289. self.dpi)
  290. gc = self.new_gc()
  291. if img.dtype.kind == 'f':
  292. img = np.asarray(img * 255., np.uint8)
  293. img = img[::-1]
  294. self._renderer.draw_image(gc, l + ox, height - b - h + oy, img)
  295. class FigureCanvasAgg(FigureCanvasBase):
  296. """
  297. The canvas the figure renders into. Calls the draw and print fig
  298. methods, creates the renderers, etc...
  299. Attributes
  300. ----------
  301. figure : `matplotlib.figure.Figure`
  302. A high-level Figure instance
  303. """
  304. def copy_from_bbox(self, bbox):
  305. renderer = self.get_renderer()
  306. return renderer.copy_from_bbox(bbox)
  307. def restore_region(self, region, bbox=None, xy=None):
  308. renderer = self.get_renderer()
  309. return renderer.restore_region(region, bbox, xy)
  310. def draw(self):
  311. """
  312. Draw the figure using the renderer.
  313. """
  314. self.renderer = self.get_renderer(cleared=True)
  315. # Acquire a lock on the shared font cache.
  316. with RendererAgg.lock, \
  317. (self.toolbar._wait_cursor_for_draw_cm() if self.toolbar
  318. else nullcontext()):
  319. self.figure.draw(self.renderer)
  320. # A GUI class may be need to update a window using this draw, so
  321. # don't forget to call the superclass.
  322. super().draw()
  323. def get_renderer(self, cleared=False):
  324. l, b, w, h = self.figure.bbox.bounds
  325. key = w, h, self.figure.dpi
  326. reuse_renderer = (hasattr(self, "renderer")
  327. and getattr(self, "_lastKey", None) == key)
  328. if not reuse_renderer:
  329. self.renderer = RendererAgg(w, h, self.figure.dpi)
  330. self._lastKey = key
  331. elif cleared:
  332. self.renderer.clear()
  333. return self.renderer
  334. def tostring_rgb(self):
  335. """Get the image as an RGB byte string.
  336. `draw` must be called at least once before this function will work and
  337. to update the renderer for any subsequent changes to the Figure.
  338. Returns
  339. -------
  340. bytes
  341. """
  342. return self.renderer.tostring_rgb()
  343. def tostring_argb(self):
  344. """Get the image as an ARGB byte string.
  345. `draw` must be called at least once before this function will work and
  346. to update the renderer for any subsequent changes to the Figure.
  347. Returns
  348. -------
  349. bytes
  350. """
  351. return self.renderer.tostring_argb()
  352. def buffer_rgba(self):
  353. """Get the image as a memoryview to the renderer's buffer.
  354. `draw` must be called at least once before this function will work and
  355. to update the renderer for any subsequent changes to the Figure.
  356. Returns
  357. -------
  358. memoryview
  359. """
  360. return self.renderer.buffer_rgba()
  361. def print_raw(self, filename_or_obj, *args, **kwargs):
  362. FigureCanvasAgg.draw(self)
  363. renderer = self.get_renderer()
  364. with cbook.open_file_cm(filename_or_obj, "wb") as fh:
  365. fh.write(renderer.buffer_rgba())
  366. print_rgba = print_raw
  367. def print_png(self, filename_or_obj, *args,
  368. metadata=None, pil_kwargs=None,
  369. **kwargs):
  370. """
  371. Write the figure to a PNG file.
  372. Parameters
  373. ----------
  374. filename_or_obj : str or PathLike or file-like object
  375. The file to write to.
  376. metadata : dict, optional
  377. Metadata in the PNG file as key-value pairs of bytes or latin-1
  378. encodable strings.
  379. According to the PNG specification, keys must be shorter than 79
  380. chars.
  381. The `PNG specification`_ defines some common keywords that may be
  382. used as appropriate:
  383. - Title: Short (one line) title or caption for image.
  384. - Author: Name of image's creator.
  385. - Description: Description of image (possibly long).
  386. - Copyright: Copyright notice.
  387. - Creation Time: Time of original image creation
  388. (usually RFC 1123 format).
  389. - Software: Software used to create the image.
  390. - Disclaimer: Legal disclaimer.
  391. - Warning: Warning of nature of content.
  392. - Source: Device used to create the image.
  393. - Comment: Miscellaneous comment;
  394. conversion from other image format.
  395. Other keywords may be invented for other purposes.
  396. If 'Software' is not given, an autogenerated value for matplotlib
  397. will be used.
  398. For more details see the `PNG specification`_.
  399. .. _PNG specification: \
  400. https://www.w3.org/TR/2003/REC-PNG-20031110/#11keywords
  401. pil_kwargs : dict, optional
  402. If set to a non-None value, use Pillow to save the figure instead
  403. of Matplotlib's builtin PNG support, and pass these keyword
  404. arguments to `PIL.Image.save`.
  405. If the 'pnginfo' key is present, it completely overrides
  406. *metadata*, including the default 'Software' key.
  407. """
  408. from matplotlib import _png
  409. if metadata is None:
  410. metadata = {}
  411. default_metadata = {
  412. "Software":
  413. f"matplotlib version{__version__}, http://matplotlib.org/",
  414. }
  415. FigureCanvasAgg.draw(self)
  416. if pil_kwargs is not None:
  417. from PIL import Image
  418. from PIL.PngImagePlugin import PngInfo
  419. # Only use the metadata kwarg if pnginfo is not set, because the
  420. # semantics of duplicate keys in pnginfo is unclear.
  421. if "pnginfo" in pil_kwargs:
  422. if metadata:
  423. cbook._warn_external("'metadata' is overridden by the "
  424. "'pnginfo' entry in 'pil_kwargs'.")
  425. else:
  426. pnginfo = PngInfo()
  427. for k, v in {**default_metadata, **metadata}.items():
  428. pnginfo.add_text(k, v)
  429. pil_kwargs["pnginfo"] = pnginfo
  430. pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
  431. (Image.fromarray(np.asarray(self.buffer_rgba()))
  432. .save(filename_or_obj, format="png", **pil_kwargs))
  433. else:
  434. renderer = self.get_renderer()
  435. with cbook.open_file_cm(filename_or_obj, "wb") as fh:
  436. _png.write_png(renderer._renderer, fh, self.figure.dpi,
  437. metadata={**default_metadata, **metadata})
  438. def print_to_buffer(self):
  439. FigureCanvasAgg.draw(self)
  440. renderer = self.get_renderer()
  441. return (bytes(renderer.buffer_rgba()),
  442. (int(renderer.width), int(renderer.height)))
  443. if _has_pil:
  444. # Note that these methods should typically be called via savefig() and
  445. # print_figure(), and the latter ensures that `self.figure.dpi` already
  446. # matches the dpi kwarg (if any).
  447. @cbook._delete_parameter("3.2", "dryrun")
  448. def print_jpg(self, filename_or_obj, *args, dryrun=False,
  449. pil_kwargs=None, **kwargs):
  450. """
  451. Write the figure to a JPEG file.
  452. Parameters
  453. ----------
  454. filename_or_obj : str or PathLike or file-like object
  455. The file to write to.
  456. Other Parameters
  457. ----------------
  458. quality : int
  459. The image quality, on a scale from 1 (worst) to 100 (best).
  460. The default is :rc:`savefig.jpeg_quality`. Values above
  461. 95 should be avoided; 100 completely disables the JPEG
  462. quantization stage.
  463. optimize : bool
  464. If present, indicates that the encoder should
  465. make an extra pass over the image in order to select
  466. optimal encoder settings.
  467. progressive : bool
  468. If present, indicates that this image
  469. should be stored as a progressive JPEG file.
  470. pil_kwargs : dict, optional
  471. Additional keyword arguments that are passed to
  472. `PIL.Image.save` when saving the figure. These take precedence
  473. over *quality*, *optimize* and *progressive*.
  474. """
  475. FigureCanvasAgg.draw(self)
  476. if dryrun:
  477. return
  478. # The image is pasted onto a white background image to handle
  479. # transparency.
  480. image = Image.fromarray(np.asarray(self.buffer_rgba()))
  481. background = Image.new('RGB', image.size, "white")
  482. background.paste(image, image)
  483. if pil_kwargs is None:
  484. pil_kwargs = {}
  485. for k in ["quality", "optimize", "progressive"]:
  486. if k in kwargs:
  487. pil_kwargs.setdefault(k, kwargs[k])
  488. pil_kwargs.setdefault("quality", rcParams["savefig.jpeg_quality"])
  489. pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
  490. return background.save(
  491. filename_or_obj, format='jpeg', **pil_kwargs)
  492. print_jpeg = print_jpg
  493. @cbook._delete_parameter("3.2", "dryrun")
  494. def print_tif(self, filename_or_obj, *args, dryrun=False,
  495. pil_kwargs=None, **kwargs):
  496. FigureCanvasAgg.draw(self)
  497. if dryrun:
  498. return
  499. if pil_kwargs is None:
  500. pil_kwargs = {}
  501. pil_kwargs.setdefault("dpi", (self.figure.dpi, self.figure.dpi))
  502. return (Image.fromarray(np.asarray(self.buffer_rgba()))
  503. .save(filename_or_obj, format='tiff', **pil_kwargs))
  504. print_tiff = print_tif
  505. @_Backend.export
  506. class _BackendAgg(_Backend):
  507. FigureCanvas = FigureCanvasAgg
  508. FigureManager = FigureManagerBase