image.py 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786
  1. """
  2. The image module supports basic image loading, rescaling and display
  3. operations.
  4. """
  5. import math
  6. import os
  7. import logging
  8. from pathlib import Path
  9. import warnings
  10. import numpy as np
  11. import PIL.Image
  12. import PIL.PngImagePlugin
  13. import matplotlib as mpl
  14. from matplotlib import _api, cbook
  15. # For clarity, names from _image are given explicitly in this module
  16. from matplotlib import _image
  17. # For user convenience, the names from _image are also imported into
  18. # the image namespace
  19. from matplotlib._image import * # noqa: F401, F403
  20. import matplotlib.artist as martist
  21. import matplotlib.colorizer as mcolorizer
  22. from matplotlib.backend_bases import FigureCanvasBase
  23. import matplotlib.colors as mcolors
  24. from matplotlib.transforms import (
  25. Affine2D, BboxBase, Bbox, BboxTransform, BboxTransformTo,
  26. IdentityTransform, TransformedBbox)
  27. _log = logging.getLogger(__name__)
  28. # map interpolation strings to module constants
  29. _interpd_ = {
  30. 'auto': _image.NEAREST, # this will use nearest or Hanning...
  31. 'none': _image.NEAREST, # fall back to nearest when not supported
  32. 'nearest': _image.NEAREST,
  33. 'bilinear': _image.BILINEAR,
  34. 'bicubic': _image.BICUBIC,
  35. 'spline16': _image.SPLINE16,
  36. 'spline36': _image.SPLINE36,
  37. 'hanning': _image.HANNING,
  38. 'hamming': _image.HAMMING,
  39. 'hermite': _image.HERMITE,
  40. 'kaiser': _image.KAISER,
  41. 'quadric': _image.QUADRIC,
  42. 'catrom': _image.CATROM,
  43. 'gaussian': _image.GAUSSIAN,
  44. 'bessel': _image.BESSEL,
  45. 'mitchell': _image.MITCHELL,
  46. 'sinc': _image.SINC,
  47. 'lanczos': _image.LANCZOS,
  48. 'blackman': _image.BLACKMAN,
  49. 'antialiased': _image.NEAREST, # this will use nearest or Hanning...
  50. }
  51. interpolations_names = set(_interpd_)
  52. def composite_images(images, renderer, magnification=1.0):
  53. """
  54. Composite a number of RGBA images into one. The images are
  55. composited in the order in which they appear in the *images* list.
  56. Parameters
  57. ----------
  58. images : list of Images
  59. Each must have a `make_image` method. For each image,
  60. `can_composite` should return `True`, though this is not
  61. enforced by this function. Each image must have a purely
  62. affine transformation with no shear.
  63. renderer : `.RendererBase`
  64. magnification : float, default: 1
  65. The additional magnification to apply for the renderer in use.
  66. Returns
  67. -------
  68. image : (M, N, 4) `numpy.uint8` array
  69. The composited RGBA image.
  70. offset_x, offset_y : float
  71. The (left, bottom) offset where the composited image should be placed
  72. in the output figure.
  73. """
  74. if len(images) == 0:
  75. return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
  76. parts = []
  77. bboxes = []
  78. for image in images:
  79. data, x, y, trans = image.make_image(renderer, magnification)
  80. if data is not None:
  81. x *= magnification
  82. y *= magnification
  83. parts.append((data, x, y, image._get_scalar_alpha()))
  84. bboxes.append(
  85. Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
  86. if len(parts) == 0:
  87. return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
  88. bbox = Bbox.union(bboxes)
  89. output = np.zeros(
  90. (int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
  91. for data, x, y, alpha in parts:
  92. trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
  93. _image.resample(data, output, trans, _image.NEAREST,
  94. resample=False, alpha=alpha)
  95. return output, bbox.x0 / magnification, bbox.y0 / magnification
  96. def _draw_list_compositing_images(
  97. renderer, parent, artists, suppress_composite=None):
  98. """
  99. Draw a sorted list of artists, compositing images into a single
  100. image where possible.
  101. For internal Matplotlib use only: It is here to reduce duplication
  102. between `Figure.draw` and `Axes.draw`, but otherwise should not be
  103. generally useful.
  104. """
  105. has_images = any(isinstance(x, _ImageBase) for x in artists)
  106. # override the renderer default if suppressComposite is not None
  107. not_composite = (suppress_composite if suppress_composite is not None
  108. else renderer.option_image_nocomposite())
  109. if not_composite or not has_images:
  110. for a in artists:
  111. a.draw(renderer)
  112. else:
  113. # Composite any adjacent images together
  114. image_group = []
  115. mag = renderer.get_image_magnification()
  116. def flush_images():
  117. if len(image_group) == 1:
  118. image_group[0].draw(renderer)
  119. elif len(image_group) > 1:
  120. data, l, b = composite_images(image_group, renderer, mag)
  121. if data.size != 0:
  122. gc = renderer.new_gc()
  123. gc.set_clip_rectangle(parent.bbox)
  124. gc.set_clip_path(parent.get_clip_path())
  125. renderer.draw_image(gc, round(l), round(b), data)
  126. gc.restore()
  127. del image_group[:]
  128. for a in artists:
  129. if (isinstance(a, _ImageBase) and a.can_composite() and
  130. a.get_clip_on() and not a.get_clip_path()):
  131. image_group.append(a)
  132. else:
  133. flush_images()
  134. a.draw(renderer)
  135. flush_images()
  136. def _resample(
  137. image_obj, data, out_shape, transform, *, resample=None, alpha=1):
  138. """
  139. Convenience wrapper around `._image.resample` to resample *data* to
  140. *out_shape* (with a third dimension if *data* is RGBA) that takes care of
  141. allocating the output array and fetching the relevant properties from the
  142. Image object *image_obj*.
  143. """
  144. # AGG can only handle coordinates smaller than 24-bit signed integers,
  145. # so raise errors if the input data is larger than _image.resample can
  146. # handle.
  147. msg = ('Data with more than {n} cannot be accurately displayed. '
  148. 'Downsampling to less than {n} before displaying. '
  149. 'To remove this warning, manually downsample your data.')
  150. if data.shape[1] > 2**23:
  151. warnings.warn(msg.format(n='2**23 columns'))
  152. step = int(np.ceil(data.shape[1] / 2**23))
  153. data = data[:, ::step]
  154. transform = Affine2D().scale(step, 1) + transform
  155. if data.shape[0] > 2**24:
  156. warnings.warn(msg.format(n='2**24 rows'))
  157. step = int(np.ceil(data.shape[0] / 2**24))
  158. data = data[::step, :]
  159. transform = Affine2D().scale(1, step) + transform
  160. # decide if we need to apply anti-aliasing if the data is upsampled:
  161. # compare the number of displayed pixels to the number of
  162. # the data pixels.
  163. interpolation = image_obj.get_interpolation()
  164. if interpolation in ['antialiased', 'auto']:
  165. # don't antialias if upsampling by an integer number or
  166. # if zooming in more than a factor of 3
  167. pos = np.array([[0, 0], [data.shape[1], data.shape[0]]])
  168. disp = transform.transform(pos)
  169. dispx = np.abs(np.diff(disp[:, 0]))
  170. dispy = np.abs(np.diff(disp[:, 1]))
  171. if ((dispx > 3 * data.shape[1] or
  172. dispx == data.shape[1] or
  173. dispx == 2 * data.shape[1]) and
  174. (dispy > 3 * data.shape[0] or
  175. dispy == data.shape[0] or
  176. dispy == 2 * data.shape[0])):
  177. interpolation = 'nearest'
  178. else:
  179. interpolation = 'hanning'
  180. out = np.zeros(out_shape + data.shape[2:], data.dtype) # 2D->2D, 3D->3D.
  181. if resample is None:
  182. resample = image_obj.get_resample()
  183. _image.resample(data, out, transform,
  184. _interpd_[interpolation],
  185. resample,
  186. alpha,
  187. image_obj.get_filternorm(),
  188. image_obj.get_filterrad())
  189. return out
  190. def _rgb_to_rgba(A):
  191. """
  192. Convert an RGB image to RGBA, as required by the image resample C++
  193. extension.
  194. """
  195. rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
  196. rgba[:, :, :3] = A
  197. if rgba.dtype == np.uint8:
  198. rgba[:, :, 3] = 255
  199. else:
  200. rgba[:, :, 3] = 1.0
  201. return rgba
  202. class _ImageBase(mcolorizer.ColorizingArtist):
  203. """
  204. Base class for images.
  205. interpolation and cmap default to their rc settings
  206. cmap is a colors.Colormap instance
  207. norm is a colors.Normalize instance to map luminance to 0-1
  208. extent is data axes (left, right, bottom, top) for making image plots
  209. registered with data plots. Default is to label the pixel
  210. centers with the zero-based row and column indices.
  211. Additional kwargs are matplotlib.artist properties
  212. """
  213. zorder = 0
  214. def __init__(self, ax,
  215. cmap=None,
  216. norm=None,
  217. colorizer=None,
  218. interpolation=None,
  219. origin=None,
  220. filternorm=True,
  221. filterrad=4.0,
  222. resample=False,
  223. *,
  224. interpolation_stage=None,
  225. **kwargs
  226. ):
  227. super().__init__(self._get_colorizer(cmap, norm, colorizer))
  228. if origin is None:
  229. origin = mpl.rcParams['image.origin']
  230. _api.check_in_list(["upper", "lower"], origin=origin)
  231. self.origin = origin
  232. self.set_filternorm(filternorm)
  233. self.set_filterrad(filterrad)
  234. self.set_interpolation(interpolation)
  235. self.set_interpolation_stage(interpolation_stage)
  236. self.set_resample(resample)
  237. self.axes = ax
  238. self._imcache = None
  239. self._internal_update(kwargs)
  240. def __str__(self):
  241. try:
  242. shape = self.get_shape()
  243. return f"{type(self).__name__}(shape={shape!r})"
  244. except RuntimeError:
  245. return type(self).__name__
  246. def __getstate__(self):
  247. # Save some space on the pickle by not saving the cache.
  248. return {**super().__getstate__(), "_imcache": None}
  249. def get_size(self):
  250. """Return the size of the image as tuple (numrows, numcols)."""
  251. return self.get_shape()[:2]
  252. def get_shape(self):
  253. """
  254. Return the shape of the image as tuple (numrows, numcols, channels).
  255. """
  256. if self._A is None:
  257. raise RuntimeError('You must first set the image array')
  258. return self._A.shape
  259. def set_alpha(self, alpha):
  260. """
  261. Set the alpha value used for blending - not supported on all backends.
  262. Parameters
  263. ----------
  264. alpha : float or 2D array-like or None
  265. """
  266. martist.Artist._set_alpha_for_array(self, alpha)
  267. if np.ndim(alpha) not in (0, 2):
  268. raise TypeError('alpha must be a float, two-dimensional '
  269. 'array, or None')
  270. self._imcache = None
  271. def _get_scalar_alpha(self):
  272. """
  273. Get a scalar alpha value to be applied to the artist as a whole.
  274. If the alpha value is a matrix, the method returns 1.0 because pixels
  275. have individual alpha values (see `~._ImageBase._make_image` for
  276. details). If the alpha value is a scalar, the method returns said value
  277. to be applied to the artist as a whole because pixels do not have
  278. individual alpha values.
  279. """
  280. return 1.0 if self._alpha is None or np.ndim(self._alpha) > 0 \
  281. else self._alpha
  282. def changed(self):
  283. """
  284. Call this whenever the mappable is changed so observers can update.
  285. """
  286. self._imcache = None
  287. super().changed()
  288. def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
  289. unsampled=False, round_to_pixel_border=True):
  290. """
  291. Normalize, rescale, and colormap the image *A* from the given *in_bbox*
  292. (in data space), to the given *out_bbox* (in pixel space) clipped to
  293. the given *clip_bbox* (also in pixel space), and magnified by the
  294. *magnification* factor.
  295. Parameters
  296. ----------
  297. A : ndarray
  298. - a (M, N) array interpreted as scalar (greyscale) image,
  299. with one of the dtypes `~numpy.float32`, `~numpy.float64`,
  300. `~numpy.float128`, `~numpy.uint16` or `~numpy.uint8`.
  301. - (M, N, 4) RGBA image with a dtype of `~numpy.float32`,
  302. `~numpy.float64`, `~numpy.float128`, or `~numpy.uint8`.
  303. in_bbox : `~matplotlib.transforms.Bbox`
  304. out_bbox : `~matplotlib.transforms.Bbox`
  305. clip_bbox : `~matplotlib.transforms.Bbox`
  306. magnification : float, default: 1
  307. unsampled : bool, default: False
  308. If True, the image will not be scaled, but an appropriate
  309. affine transformation will be returned instead.
  310. round_to_pixel_border : bool, default: True
  311. If True, the output image size will be rounded to the nearest pixel
  312. boundary. This makes the images align correctly with the Axes.
  313. It should not be used if exact scaling is needed, such as for
  314. `.FigureImage`.
  315. Returns
  316. -------
  317. image : (M, N, 4) `numpy.uint8` array
  318. The RGBA image, resampled unless *unsampled* is True.
  319. x, y : float
  320. The upper left corner where the image should be drawn, in pixel
  321. space.
  322. trans : `~matplotlib.transforms.Affine2D`
  323. The affine transformation from image to pixel space.
  324. """
  325. if A is None:
  326. raise RuntimeError('You must first set the image '
  327. 'array or the image attribute')
  328. if A.size == 0:
  329. raise RuntimeError("_make_image must get a non-empty image. "
  330. "Your Artist's draw method must filter before "
  331. "this method is called.")
  332. clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
  333. if clipped_bbox is None:
  334. return None, 0, 0, None
  335. out_width_base = clipped_bbox.width * magnification
  336. out_height_base = clipped_bbox.height * magnification
  337. if out_width_base == 0 or out_height_base == 0:
  338. return None, 0, 0, None
  339. if self.origin == 'upper':
  340. # Flip the input image using a transform. This avoids the
  341. # problem with flipping the array, which results in a copy
  342. # when it is converted to contiguous in the C wrapper
  343. t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
  344. else:
  345. t0 = IdentityTransform()
  346. t0 += (
  347. Affine2D()
  348. .scale(
  349. in_bbox.width / A.shape[1],
  350. in_bbox.height / A.shape[0])
  351. .translate(in_bbox.x0, in_bbox.y0)
  352. + self.get_transform())
  353. t = (t0
  354. + (Affine2D()
  355. .translate(-clipped_bbox.x0, -clipped_bbox.y0)
  356. .scale(magnification)))
  357. # So that the image is aligned with the edge of the Axes, we want to
  358. # round up the output width to the next integer. This also means
  359. # scaling the transform slightly to account for the extra subpixel.
  360. if ((not unsampled) and t.is_affine and round_to_pixel_border and
  361. (out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)):
  362. out_width = math.ceil(out_width_base)
  363. out_height = math.ceil(out_height_base)
  364. extra_width = (out_width - out_width_base) / out_width_base
  365. extra_height = (out_height - out_height_base) / out_height_base
  366. t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height)
  367. else:
  368. out_width = int(out_width_base)
  369. out_height = int(out_height_base)
  370. out_shape = (out_height, out_width)
  371. if not unsampled:
  372. if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in (3, 4)):
  373. raise ValueError(f"Invalid shape {A.shape} for image data")
  374. # if antialiased, this needs to change as window sizes
  375. # change:
  376. interpolation_stage = self._interpolation_stage
  377. if interpolation_stage in ['antialiased', 'auto']:
  378. pos = np.array([[0, 0], [A.shape[1], A.shape[0]]])
  379. disp = t.transform(pos)
  380. dispx = np.abs(np.diff(disp[:, 0])) / A.shape[1]
  381. dispy = np.abs(np.diff(disp[:, 1])) / A.shape[0]
  382. if (dispx < 3) or (dispy < 3):
  383. interpolation_stage = 'rgba'
  384. else:
  385. interpolation_stage = 'data'
  386. if A.ndim == 2 and interpolation_stage == 'data':
  387. # if we are a 2D array, then we are running through the
  388. # norm + colormap transformation. However, in general the
  389. # input data is not going to match the size on the screen so we
  390. # have to resample to the correct number of pixels
  391. if A.dtype.kind == 'f': # Float dtype: scale to same dtype.
  392. scaled_dtype = np.dtype("f8" if A.dtype.itemsize > 4 else "f4")
  393. if scaled_dtype.itemsize < A.dtype.itemsize:
  394. _api.warn_external(f"Casting input data from {A.dtype}"
  395. f" to {scaled_dtype} for imshow.")
  396. else: # Int dtype, likely.
  397. # TODO slice input array first
  398. # Scale to appropriately sized float: use float32 if the
  399. # dynamic range is small, to limit the memory footprint.
  400. da = A.max().astype("f8") - A.min().astype("f8")
  401. scaled_dtype = "f8" if da > 1e8 else "f4"
  402. # resample the input data to the correct resolution and shape
  403. A_resampled = _resample(self, A.astype(scaled_dtype), out_shape, t)
  404. # if using NoNorm, cast back to the original datatype
  405. if isinstance(self.norm, mcolors.NoNorm):
  406. A_resampled = A_resampled.astype(A.dtype)
  407. # Compute out_mask (what screen pixels include "bad" data
  408. # pixels) and out_alpha (to what extent screen pixels are
  409. # covered by data pixels: 0 outside the data extent, 1 inside
  410. # (even for bad data), and intermediate values at the edges).
  411. mask = (np.where(A.mask, np.float32(np.nan), np.float32(1))
  412. if A.mask.shape == A.shape # nontrivial mask
  413. else np.ones_like(A, np.float32))
  414. # we always have to interpolate the mask to account for
  415. # non-affine transformations
  416. out_alpha = _resample(self, mask, out_shape, t, resample=True)
  417. del mask # Make sure we don't use mask anymore!
  418. out_mask = np.isnan(out_alpha)
  419. out_alpha[out_mask] = 1
  420. # Apply the pixel-by-pixel alpha values if present
  421. alpha = self.get_alpha()
  422. if alpha is not None and np.ndim(alpha) > 0:
  423. out_alpha *= _resample(self, alpha, out_shape, t, resample=True)
  424. # mask and run through the norm
  425. resampled_masked = np.ma.masked_array(A_resampled, out_mask)
  426. output = self.norm(resampled_masked)
  427. else:
  428. if A.ndim == 2: # interpolation_stage = 'rgba'
  429. self.norm.autoscale_None(A)
  430. A = self.to_rgba(A)
  431. alpha = self.get_alpha()
  432. if alpha is None: # alpha parameter not specified
  433. if A.shape[2] == 3: # image has no alpha channel
  434. output_alpha = 255 if A.dtype == np.uint8 else 1.0
  435. else:
  436. output_alpha = _resample( # resample alpha channel
  437. self, A[..., 3], out_shape, t)
  438. output = _resample( # resample rgb channels
  439. self, _rgb_to_rgba(A[..., :3]), out_shape, t)
  440. elif np.ndim(alpha) > 0: # Array alpha
  441. # user-specified array alpha overrides the existing alpha channel
  442. output_alpha = _resample(self, alpha, out_shape, t)
  443. output = _resample(
  444. self, _rgb_to_rgba(A[..., :3]), out_shape, t)
  445. else: # Scalar alpha
  446. if A.shape[2] == 3: # broadcast scalar alpha
  447. output_alpha = (255 * alpha) if A.dtype == np.uint8 else alpha
  448. else: # or apply scalar alpha to existing alpha channel
  449. output_alpha = _resample(self, A[..., 3], out_shape, t) * alpha
  450. output = _resample(
  451. self, _rgb_to_rgba(A[..., :3]), out_shape, t)
  452. output[..., 3] = output_alpha # recombine rgb and alpha
  453. # output is now either a 2D array of normed (int or float) data
  454. # or an RGBA array of re-sampled input
  455. output = self.to_rgba(output, bytes=True, norm=False)
  456. # output is now a correctly sized RGBA array of uint8
  457. # Apply alpha *after* if the input was greyscale without a mask
  458. if A.ndim == 2:
  459. alpha = self._get_scalar_alpha()
  460. alpha_channel = output[:, :, 3]
  461. alpha_channel[:] = ( # Assignment will cast to uint8.
  462. alpha_channel.astype(np.float32) * out_alpha * alpha)
  463. else:
  464. if self._imcache is None:
  465. self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
  466. output = self._imcache
  467. # Subset the input image to only the part that will be displayed.
  468. subset = TransformedBbox(clip_bbox, t0.inverted()).frozen()
  469. output = output[
  470. int(max(subset.ymin, 0)):
  471. int(min(subset.ymax + 1, output.shape[0])),
  472. int(max(subset.xmin, 0)):
  473. int(min(subset.xmax + 1, output.shape[1]))]
  474. t = Affine2D().translate(
  475. int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
  476. return output, clipped_bbox.x0, clipped_bbox.y0, t
  477. def make_image(self, renderer, magnification=1.0, unsampled=False):
  478. """
  479. Normalize, rescale, and colormap this image's data for rendering using
  480. *renderer*, with the given *magnification*.
  481. If *unsampled* is True, the image will not be scaled, but an
  482. appropriate affine transformation will be returned instead.
  483. Returns
  484. -------
  485. image : (M, N, 4) `numpy.uint8` array
  486. The RGBA image, resampled unless *unsampled* is True.
  487. x, y : float
  488. The upper left corner where the image should be drawn, in pixel
  489. space.
  490. trans : `~matplotlib.transforms.Affine2D`
  491. The affine transformation from image to pixel space.
  492. """
  493. raise NotImplementedError('The make_image method must be overridden')
  494. def _check_unsampled_image(self):
  495. """
  496. Return whether the image is better to be drawn unsampled.
  497. The derived class needs to override it.
  498. """
  499. return False
  500. @martist.allow_rasterization
  501. def draw(self, renderer):
  502. # if not visible, declare victory and return
  503. if not self.get_visible():
  504. self.stale = False
  505. return
  506. # for empty images, there is nothing to draw!
  507. if self.get_array().size == 0:
  508. self.stale = False
  509. return
  510. # actually render the image.
  511. gc = renderer.new_gc()
  512. self._set_gc_clip(gc)
  513. gc.set_alpha(self._get_scalar_alpha())
  514. gc.set_url(self.get_url())
  515. gc.set_gid(self.get_gid())
  516. if (renderer.option_scale_image() # Renderer supports transform kwarg.
  517. and self._check_unsampled_image()
  518. and self.get_transform().is_affine):
  519. im, l, b, trans = self.make_image(renderer, unsampled=True)
  520. if im is not None:
  521. trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
  522. renderer.draw_image(gc, l, b, im, trans)
  523. else:
  524. im, l, b, trans = self.make_image(
  525. renderer, renderer.get_image_magnification())
  526. if im is not None:
  527. renderer.draw_image(gc, l, b, im)
  528. gc.restore()
  529. self.stale = False
  530. def contains(self, mouseevent):
  531. """Test whether the mouse event occurred within the image."""
  532. if (self._different_canvas(mouseevent)
  533. # This doesn't work for figimage.
  534. or not self.axes.contains(mouseevent)[0]):
  535. return False, {}
  536. # TODO: make sure this is consistent with patch and patch
  537. # collection on nonlinear transformed coordinates.
  538. # TODO: consider returning image coordinates (shouldn't
  539. # be too difficult given that the image is rectilinear
  540. trans = self.get_transform().inverted()
  541. x, y = trans.transform([mouseevent.x, mouseevent.y])
  542. xmin, xmax, ymin, ymax = self.get_extent()
  543. # This checks xmin <= x <= xmax *or* xmax <= x <= xmin.
  544. inside = (x is not None and (x - xmin) * (x - xmax) <= 0
  545. and y is not None and (y - ymin) * (y - ymax) <= 0)
  546. return inside, {}
  547. def write_png(self, fname):
  548. """Write the image to png file *fname*."""
  549. im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
  550. bytes=True, norm=True)
  551. PIL.Image.fromarray(im).save(fname, format="png")
  552. @staticmethod
  553. def _normalize_image_array(A):
  554. """
  555. Check validity of image-like input *A* and normalize it to a format suitable for
  556. Image subclasses.
  557. """
  558. A = cbook.safe_masked_invalid(A, copy=True)
  559. if A.dtype != np.uint8 and not np.can_cast(A.dtype, float, "same_kind"):
  560. raise TypeError(f"Image data of dtype {A.dtype} cannot be "
  561. f"converted to float")
  562. if A.ndim == 3 and A.shape[-1] == 1:
  563. A = A.squeeze(-1) # If just (M, N, 1), assume scalar and apply colormap.
  564. if not (A.ndim == 2 or A.ndim == 3 and A.shape[-1] in [3, 4]):
  565. raise TypeError(f"Invalid shape {A.shape} for image data")
  566. if A.ndim == 3:
  567. # If the input data has values outside the valid range (after
  568. # normalisation), we issue a warning and then clip X to the bounds
  569. # - otherwise casting wraps extreme values, hiding outliers and
  570. # making reliable interpretation impossible.
  571. high = 255 if np.issubdtype(A.dtype, np.integer) else 1
  572. if A.min() < 0 or high < A.max():
  573. _log.warning(
  574. 'Clipping input data to the valid range for imshow with '
  575. 'RGB data ([0..1] for floats or [0..255] for integers). '
  576. 'Got range [%s..%s].',
  577. A.min(), A.max()
  578. )
  579. A = np.clip(A, 0, high)
  580. # Cast unsupported integer types to uint8
  581. if A.dtype != np.uint8 and np.issubdtype(A.dtype, np.integer):
  582. A = A.astype(np.uint8)
  583. return A
  584. def set_data(self, A):
  585. """
  586. Set the image array.
  587. Note that this function does *not* update the normalization used.
  588. Parameters
  589. ----------
  590. A : array-like or `PIL.Image.Image`
  591. """
  592. if isinstance(A, PIL.Image.Image):
  593. A = pil_to_array(A) # Needed e.g. to apply png palette.
  594. self._A = self._normalize_image_array(A)
  595. self._imcache = None
  596. self.stale = True
  597. def set_array(self, A):
  598. """
  599. Retained for backwards compatibility - use set_data instead.
  600. Parameters
  601. ----------
  602. A : array-like
  603. """
  604. # This also needs to be here to override the inherited
  605. # cm.ScalarMappable.set_array method so it is not invoked by mistake.
  606. self.set_data(A)
  607. def get_interpolation(self):
  608. """
  609. Return the interpolation method the image uses when resizing.
  610. One of 'auto', 'antialiased', 'nearest', 'bilinear', 'bicubic',
  611. 'spline16', 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser',
  612. 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos',
  613. or 'none'.
  614. """
  615. return self._interpolation
  616. def set_interpolation(self, s):
  617. """
  618. Set the interpolation method the image uses when resizing.
  619. If None, use :rc:`image.interpolation`. If 'none', the image is
  620. shown as is without interpolating. 'none' is only supported in
  621. agg, ps and pdf backends and will fall back to 'nearest' mode
  622. for other backends.
  623. Parameters
  624. ----------
  625. s : {'auto', 'nearest', 'bilinear', 'bicubic', 'spline16', \
  626. 'spline36', 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', \
  627. 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'} or None
  628. """
  629. s = mpl._val_or_rc(s, 'image.interpolation').lower()
  630. _api.check_in_list(interpolations_names, interpolation=s)
  631. self._interpolation = s
  632. self.stale = True
  633. def get_interpolation_stage(self):
  634. """
  635. Return when interpolation happens during the transform to RGBA.
  636. One of 'data', 'rgba', 'auto'.
  637. """
  638. return self._interpolation_stage
  639. def set_interpolation_stage(self, s):
  640. """
  641. Set when interpolation happens during the transform to RGBA.
  642. Parameters
  643. ----------
  644. s : {'data', 'rgba', 'auto'} or None
  645. Whether to apply up/downsampling interpolation in data or RGBA
  646. space. If None, use :rc:`image.interpolation_stage`.
  647. If 'auto' we will check upsampling rate and if less
  648. than 3 then use 'rgba', otherwise use 'data'.
  649. """
  650. s = mpl._val_or_rc(s, 'image.interpolation_stage')
  651. _api.check_in_list(['data', 'rgba', 'auto'], s=s)
  652. self._interpolation_stage = s
  653. self.stale = True
  654. def can_composite(self):
  655. """Return whether the image can be composited with its neighbors."""
  656. trans = self.get_transform()
  657. return (
  658. self._interpolation != 'none' and
  659. trans.is_affine and
  660. trans.is_separable)
  661. def set_resample(self, v):
  662. """
  663. Set whether image resampling is used.
  664. Parameters
  665. ----------
  666. v : bool or None
  667. If None, use :rc:`image.resample`.
  668. """
  669. v = mpl._val_or_rc(v, 'image.resample')
  670. self._resample = v
  671. self.stale = True
  672. def get_resample(self):
  673. """Return whether image resampling is used."""
  674. return self._resample
  675. def set_filternorm(self, filternorm):
  676. """
  677. Set whether the resize filter normalizes the weights.
  678. See help for `~.Axes.imshow`.
  679. Parameters
  680. ----------
  681. filternorm : bool
  682. """
  683. self._filternorm = bool(filternorm)
  684. self.stale = True
  685. def get_filternorm(self):
  686. """Return whether the resize filter normalizes the weights."""
  687. return self._filternorm
  688. def set_filterrad(self, filterrad):
  689. """
  690. Set the resize filter radius only applicable to some
  691. interpolation schemes -- see help for imshow
  692. Parameters
  693. ----------
  694. filterrad : positive float
  695. """
  696. r = float(filterrad)
  697. if r <= 0:
  698. raise ValueError("The filter radius must be a positive number")
  699. self._filterrad = r
  700. self.stale = True
  701. def get_filterrad(self):
  702. """Return the filterrad setting."""
  703. return self._filterrad
  704. class AxesImage(_ImageBase):
  705. """
  706. An image with pixels on a regular grid, attached to an Axes.
  707. Parameters
  708. ----------
  709. ax : `~matplotlib.axes.Axes`
  710. The Axes the image will belong to.
  711. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
  712. The Colormap instance or registered colormap name used to map scalar
  713. data to colors.
  714. norm : str or `~matplotlib.colors.Normalize`
  715. Maps luminance to 0-1.
  716. interpolation : str, default: :rc:`image.interpolation`
  717. Supported values are 'none', 'auto', 'nearest', 'bilinear',
  718. 'bicubic', 'spline16', 'spline36', 'hanning', 'hamming', 'hermite',
  719. 'kaiser', 'quadric', 'catrom', 'gaussian', 'bessel', 'mitchell',
  720. 'sinc', 'lanczos', 'blackman'.
  721. interpolation_stage : {'data', 'rgba'}, default: 'data'
  722. If 'data', interpolation
  723. is carried out on the data provided by the user. If 'rgba', the
  724. interpolation is carried out after the colormapping has been
  725. applied (visual interpolation).
  726. origin : {'upper', 'lower'}, default: :rc:`image.origin`
  727. Place the [0, 0] index of the array in the upper left or lower left
  728. corner of the Axes. The convention 'upper' is typically used for
  729. matrices and images.
  730. extent : tuple, optional
  731. The data axes (left, right, bottom, top) for making image plots
  732. registered with data plots. Default is to label the pixel
  733. centers with the zero-based row and column indices.
  734. filternorm : bool, default: True
  735. A parameter for the antigrain image resize filter
  736. (see the antigrain documentation).
  737. If filternorm is set, the filter normalizes integer values and corrects
  738. the rounding errors. It doesn't do anything with the source floating
  739. point values, it corrects only integers according to the rule of 1.0
  740. which means that any sum of pixel weights must be equal to 1.0. So,
  741. the filter function must produce a graph of the proper shape.
  742. filterrad : float > 0, default: 4
  743. The filter radius for filters that have a radius parameter, i.e. when
  744. interpolation is one of: 'sinc', 'lanczos' or 'blackman'.
  745. resample : bool, default: False
  746. When True, use a full resampling method. When False, only resample when
  747. the output image is larger than the input image.
  748. **kwargs : `~matplotlib.artist.Artist` properties
  749. """
  750. def __init__(self, ax,
  751. *,
  752. cmap=None,
  753. norm=None,
  754. colorizer=None,
  755. interpolation=None,
  756. origin=None,
  757. extent=None,
  758. filternorm=True,
  759. filterrad=4.0,
  760. resample=False,
  761. interpolation_stage=None,
  762. **kwargs
  763. ):
  764. self._extent = extent
  765. super().__init__(
  766. ax,
  767. cmap=cmap,
  768. norm=norm,
  769. colorizer=colorizer,
  770. interpolation=interpolation,
  771. origin=origin,
  772. filternorm=filternorm,
  773. filterrad=filterrad,
  774. resample=resample,
  775. interpolation_stage=interpolation_stage,
  776. **kwargs
  777. )
  778. def get_window_extent(self, renderer=None):
  779. x0, x1, y0, y1 = self._extent
  780. bbox = Bbox.from_extents([x0, y0, x1, y1])
  781. return bbox.transformed(self.get_transform())
  782. def make_image(self, renderer, magnification=1.0, unsampled=False):
  783. # docstring inherited
  784. trans = self.get_transform()
  785. # image is created in the canvas coordinate.
  786. x1, x2, y1, y2 = self.get_extent()
  787. bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
  788. transformed_bbox = TransformedBbox(bbox, trans)
  789. clip = ((self.get_clip_box() or self.axes.bbox) if self.get_clip_on()
  790. else self.get_figure(root=True).bbox)
  791. return self._make_image(self._A, bbox, transformed_bbox, clip,
  792. magnification, unsampled=unsampled)
  793. def _check_unsampled_image(self):
  794. """Return whether the image would be better drawn unsampled."""
  795. return self.get_interpolation() == "none"
  796. def set_extent(self, extent, **kwargs):
  797. """
  798. Set the image extent.
  799. Parameters
  800. ----------
  801. extent : 4-tuple of float
  802. The position and size of the image as tuple
  803. ``(left, right, bottom, top)`` in data coordinates.
  804. **kwargs
  805. Other parameters from which unit info (i.e., the *xunits*,
  806. *yunits*, *zunits* (for 3D Axes), *runits* and *thetaunits* (for
  807. polar Axes) entries are applied, if present.
  808. Notes
  809. -----
  810. This updates `.Axes.dataLim`, and, if autoscaling, sets `.Axes.viewLim`
  811. to tightly fit the image, regardless of `~.Axes.dataLim`. Autoscaling
  812. state is not changed, so a subsequent call to `.Axes.autoscale_view`
  813. will redo the autoscaling in accord with `~.Axes.dataLim`.
  814. """
  815. (xmin, xmax), (ymin, ymax) = self.axes._process_unit_info(
  816. [("x", [extent[0], extent[1]]),
  817. ("y", [extent[2], extent[3]])],
  818. kwargs)
  819. if kwargs:
  820. raise _api.kwarg_error("set_extent", kwargs)
  821. xmin = self.axes._validate_converted_limits(
  822. xmin, self.convert_xunits)
  823. xmax = self.axes._validate_converted_limits(
  824. xmax, self.convert_xunits)
  825. ymin = self.axes._validate_converted_limits(
  826. ymin, self.convert_yunits)
  827. ymax = self.axes._validate_converted_limits(
  828. ymax, self.convert_yunits)
  829. extent = [xmin, xmax, ymin, ymax]
  830. self._extent = extent
  831. corners = (xmin, ymin), (xmax, ymax)
  832. self.axes.update_datalim(corners)
  833. self.sticky_edges.x[:] = [xmin, xmax]
  834. self.sticky_edges.y[:] = [ymin, ymax]
  835. if self.axes.get_autoscalex_on():
  836. self.axes.set_xlim((xmin, xmax), auto=None)
  837. if self.axes.get_autoscaley_on():
  838. self.axes.set_ylim((ymin, ymax), auto=None)
  839. self.stale = True
  840. def get_extent(self):
  841. """Return the image extent as tuple (left, right, bottom, top)."""
  842. if self._extent is not None:
  843. return self._extent
  844. else:
  845. sz = self.get_size()
  846. numrows, numcols = sz
  847. if self.origin == 'upper':
  848. return (-0.5, numcols-0.5, numrows-0.5, -0.5)
  849. else:
  850. return (-0.5, numcols-0.5, -0.5, numrows-0.5)
  851. def get_cursor_data(self, event):
  852. """
  853. Return the image value at the event position or *None* if the event is
  854. outside the image.
  855. See Also
  856. --------
  857. matplotlib.artist.Artist.get_cursor_data
  858. """
  859. xmin, xmax, ymin, ymax = self.get_extent()
  860. if self.origin == 'upper':
  861. ymin, ymax = ymax, ymin
  862. arr = self.get_array()
  863. data_extent = Bbox([[xmin, ymin], [xmax, ymax]])
  864. array_extent = Bbox([[0, 0], [arr.shape[1], arr.shape[0]]])
  865. trans = self.get_transform().inverted()
  866. trans += BboxTransform(boxin=data_extent, boxout=array_extent)
  867. point = trans.transform([event.x, event.y])
  868. if any(np.isnan(point)):
  869. return None
  870. j, i = point.astype(int)
  871. # Clip the coordinates at array bounds
  872. if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
  873. return None
  874. else:
  875. return arr[i, j]
  876. class NonUniformImage(AxesImage):
  877. """
  878. An image with pixels on a rectilinear grid.
  879. In contrast to `.AxesImage`, where pixels are on a regular grid,
  880. NonUniformImage allows rows and columns with individual heights / widths.
  881. See also :doc:`/gallery/images_contours_and_fields/image_nonuniform`.
  882. """
  883. def __init__(self, ax, *, interpolation='nearest', **kwargs):
  884. """
  885. Parameters
  886. ----------
  887. ax : `~matplotlib.axes.Axes`
  888. The Axes the image will belong to.
  889. interpolation : {'nearest', 'bilinear'}, default: 'nearest'
  890. The interpolation scheme used in the resampling.
  891. **kwargs
  892. All other keyword arguments are identical to those of `.AxesImage`.
  893. """
  894. super().__init__(ax, **kwargs)
  895. self.set_interpolation(interpolation)
  896. def _check_unsampled_image(self):
  897. """Return False. Do not use unsampled image."""
  898. return False
  899. def make_image(self, renderer, magnification=1.0, unsampled=False):
  900. # docstring inherited
  901. if self._A is None:
  902. raise RuntimeError('You must first set the image array')
  903. if unsampled:
  904. raise ValueError('unsampled not supported on NonUniformImage')
  905. A = self._A
  906. if A.ndim == 2:
  907. if A.dtype != np.uint8:
  908. A = self.to_rgba(A, bytes=True)
  909. else:
  910. A = np.repeat(A[:, :, np.newaxis], 4, 2)
  911. A[:, :, 3] = 255
  912. else:
  913. if A.dtype != np.uint8:
  914. A = (255*A).astype(np.uint8)
  915. if A.shape[2] == 3:
  916. B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
  917. B[:, :, 0:3] = A
  918. B[:, :, 3] = 255
  919. A = B
  920. l, b, r, t = self.axes.bbox.extents
  921. width = int(((round(r) + 0.5) - (round(l) - 0.5)) * magnification)
  922. height = int(((round(t) + 0.5) - (round(b) - 0.5)) * magnification)
  923. invertedTransform = self.axes.transData.inverted()
  924. x_pix = invertedTransform.transform(
  925. [(x, b) for x in np.linspace(l, r, width)])[:, 0]
  926. y_pix = invertedTransform.transform(
  927. [(l, y) for y in np.linspace(b, t, height)])[:, 1]
  928. if self._interpolation == "nearest":
  929. x_mid = (self._Ax[:-1] + self._Ax[1:]) / 2
  930. y_mid = (self._Ay[:-1] + self._Ay[1:]) / 2
  931. x_int = x_mid.searchsorted(x_pix)
  932. y_int = y_mid.searchsorted(y_pix)
  933. # The following is equal to `A[y_int[:, None], x_int[None, :]]`,
  934. # but many times faster. Both casting to uint32 (to have an
  935. # effectively 1D array) and manual index flattening matter.
  936. im = (
  937. np.ascontiguousarray(A).view(np.uint32).ravel()[
  938. np.add.outer(y_int * A.shape[1], x_int)]
  939. .view(np.uint8).reshape((height, width, 4)))
  940. else: # self._interpolation == "bilinear"
  941. # Use np.interp to compute x_int/x_float has similar speed.
  942. x_int = np.clip(
  943. self._Ax.searchsorted(x_pix) - 1, 0, len(self._Ax) - 2)
  944. y_int = np.clip(
  945. self._Ay.searchsorted(y_pix) - 1, 0, len(self._Ay) - 2)
  946. idx_int = np.add.outer(y_int * A.shape[1], x_int)
  947. x_frac = np.clip(
  948. np.divide(x_pix - self._Ax[x_int], np.diff(self._Ax)[x_int],
  949. dtype=np.float32), # Downcasting helps with speed.
  950. 0, 1)
  951. y_frac = np.clip(
  952. np.divide(y_pix - self._Ay[y_int], np.diff(self._Ay)[y_int],
  953. dtype=np.float32),
  954. 0, 1)
  955. f00 = np.outer(1 - y_frac, 1 - x_frac)
  956. f10 = np.outer(y_frac, 1 - x_frac)
  957. f01 = np.outer(1 - y_frac, x_frac)
  958. f11 = np.outer(y_frac, x_frac)
  959. im = np.empty((height, width, 4), np.uint8)
  960. for chan in range(4):
  961. ac = A[:, :, chan].reshape(-1) # reshape(-1) avoids a copy.
  962. # Shifting the buffer start (`ac[offset:]`) avoids an array
  963. # addition (`ac[idx_int + offset]`).
  964. buf = f00 * ac[idx_int]
  965. buf += f10 * ac[A.shape[1]:][idx_int]
  966. buf += f01 * ac[1:][idx_int]
  967. buf += f11 * ac[A.shape[1] + 1:][idx_int]
  968. im[:, :, chan] = buf # Implicitly casts to uint8.
  969. return im, l, b, IdentityTransform()
  970. def set_data(self, x, y, A):
  971. """
  972. Set the grid for the pixel centers, and the pixel values.
  973. Parameters
  974. ----------
  975. x, y : 1D array-like
  976. Monotonic arrays of shapes (N,) and (M,), respectively, specifying
  977. pixel centers.
  978. A : array-like
  979. (M, N) `~numpy.ndarray` or masked array of values to be
  980. colormapped, or (M, N, 3) RGB array, or (M, N, 4) RGBA array.
  981. """
  982. A = self._normalize_image_array(A)
  983. x = np.array(x, np.float32)
  984. y = np.array(y, np.float32)
  985. if not (x.ndim == y.ndim == 1 and A.shape[:2] == y.shape + x.shape):
  986. raise TypeError("Axes don't match array shape")
  987. self._A = A
  988. self._Ax = x
  989. self._Ay = y
  990. self._imcache = None
  991. self.stale = True
  992. def set_array(self, *args):
  993. raise NotImplementedError('Method not supported')
  994. def set_interpolation(self, s):
  995. """
  996. Parameters
  997. ----------
  998. s : {'nearest', 'bilinear'} or None
  999. If None, use :rc:`image.interpolation`.
  1000. """
  1001. if s is not None and s not in ('nearest', 'bilinear'):
  1002. raise NotImplementedError('Only nearest neighbor and '
  1003. 'bilinear interpolations are supported')
  1004. super().set_interpolation(s)
  1005. def get_extent(self):
  1006. if self._A is None:
  1007. raise RuntimeError('Must set data first')
  1008. return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
  1009. def set_filternorm(self, filternorm):
  1010. pass
  1011. def set_filterrad(self, filterrad):
  1012. pass
  1013. def set_norm(self, norm):
  1014. if self._A is not None:
  1015. raise RuntimeError('Cannot change colors after loading data')
  1016. super().set_norm(norm)
  1017. def set_cmap(self, cmap):
  1018. if self._A is not None:
  1019. raise RuntimeError('Cannot change colors after loading data')
  1020. super().set_cmap(cmap)
  1021. def get_cursor_data(self, event):
  1022. # docstring inherited
  1023. x, y = event.xdata, event.ydata
  1024. if (x < self._Ax[0] or x > self._Ax[-1] or
  1025. y < self._Ay[0] or y > self._Ay[-1]):
  1026. return None
  1027. j = np.searchsorted(self._Ax, x) - 1
  1028. i = np.searchsorted(self._Ay, y) - 1
  1029. return self._A[i, j]
  1030. class PcolorImage(AxesImage):
  1031. """
  1032. Make a pcolor-style plot with an irregular rectangular grid.
  1033. This uses a variation of the original irregular image code,
  1034. and it is used by pcolorfast for the corresponding grid type.
  1035. """
  1036. def __init__(self, ax,
  1037. x=None,
  1038. y=None,
  1039. A=None,
  1040. *,
  1041. cmap=None,
  1042. norm=None,
  1043. colorizer=None,
  1044. **kwargs
  1045. ):
  1046. """
  1047. Parameters
  1048. ----------
  1049. ax : `~matplotlib.axes.Axes`
  1050. The Axes the image will belong to.
  1051. x, y : 1D array-like, optional
  1052. Monotonic arrays of length N+1 and M+1, respectively, specifying
  1053. rectangle boundaries. If not given, will default to
  1054. ``range(N + 1)`` and ``range(M + 1)``, respectively.
  1055. A : array-like
  1056. The data to be color-coded. The interpretation depends on the
  1057. shape:
  1058. - (M, N) `~numpy.ndarray` or masked array: values to be colormapped
  1059. - (M, N, 3): RGB array
  1060. - (M, N, 4): RGBA array
  1061. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
  1062. The Colormap instance or registered colormap name used to map
  1063. scalar data to colors.
  1064. norm : str or `~matplotlib.colors.Normalize`
  1065. Maps luminance to 0-1.
  1066. **kwargs : `~matplotlib.artist.Artist` properties
  1067. """
  1068. super().__init__(ax, norm=norm, cmap=cmap, colorizer=colorizer)
  1069. self._internal_update(kwargs)
  1070. if A is not None:
  1071. self.set_data(x, y, A)
  1072. def make_image(self, renderer, magnification=1.0, unsampled=False):
  1073. # docstring inherited
  1074. if self._A is None:
  1075. raise RuntimeError('You must first set the image array')
  1076. if unsampled:
  1077. raise ValueError('unsampled not supported on PColorImage')
  1078. if self._imcache is None:
  1079. A = self.to_rgba(self._A, bytes=True)
  1080. self._imcache = np.pad(A, [(1, 1), (1, 1), (0, 0)], "constant")
  1081. padded_A = self._imcache
  1082. bg = mcolors.to_rgba(self.axes.patch.get_facecolor(), 0)
  1083. bg = (np.array(bg) * 255).astype(np.uint8)
  1084. if (padded_A[0, 0] != bg).all():
  1085. padded_A[[0, -1], :] = padded_A[:, [0, -1]] = bg
  1086. l, b, r, t = self.axes.bbox.extents
  1087. width = (round(r) + 0.5) - (round(l) - 0.5)
  1088. height = (round(t) + 0.5) - (round(b) - 0.5)
  1089. width = round(width * magnification)
  1090. height = round(height * magnification)
  1091. vl = self.axes.viewLim
  1092. x_pix = np.linspace(vl.x0, vl.x1, width)
  1093. y_pix = np.linspace(vl.y0, vl.y1, height)
  1094. x_int = self._Ax.searchsorted(x_pix)
  1095. y_int = self._Ay.searchsorted(y_pix)
  1096. im = ( # See comment in NonUniformImage.make_image re: performance.
  1097. padded_A.view(np.uint32).ravel()[
  1098. np.add.outer(y_int * padded_A.shape[1], x_int)]
  1099. .view(np.uint8).reshape((height, width, 4)))
  1100. return im, l, b, IdentityTransform()
  1101. def _check_unsampled_image(self):
  1102. return False
  1103. def set_data(self, x, y, A):
  1104. """
  1105. Set the grid for the rectangle boundaries, and the data values.
  1106. Parameters
  1107. ----------
  1108. x, y : 1D array-like, optional
  1109. Monotonic arrays of length N+1 and M+1, respectively, specifying
  1110. rectangle boundaries. If not given, will default to
  1111. ``range(N + 1)`` and ``range(M + 1)``, respectively.
  1112. A : array-like
  1113. The data to be color-coded. The interpretation depends on the
  1114. shape:
  1115. - (M, N) `~numpy.ndarray` or masked array: values to be colormapped
  1116. - (M, N, 3): RGB array
  1117. - (M, N, 4): RGBA array
  1118. """
  1119. A = self._normalize_image_array(A)
  1120. x = np.arange(0., A.shape[1] + 1) if x is None else np.array(x, float).ravel()
  1121. y = np.arange(0., A.shape[0] + 1) if y is None else np.array(y, float).ravel()
  1122. if A.shape[:2] != (y.size - 1, x.size - 1):
  1123. raise ValueError(
  1124. "Axes don't match array shape. Got %s, expected %s." %
  1125. (A.shape[:2], (y.size - 1, x.size - 1)))
  1126. # For efficient cursor readout, ensure x and y are increasing.
  1127. if x[-1] < x[0]:
  1128. x = x[::-1]
  1129. A = A[:, ::-1]
  1130. if y[-1] < y[0]:
  1131. y = y[::-1]
  1132. A = A[::-1]
  1133. self._A = A
  1134. self._Ax = x
  1135. self._Ay = y
  1136. self._imcache = None
  1137. self.stale = True
  1138. def set_array(self, *args):
  1139. raise NotImplementedError('Method not supported')
  1140. def get_cursor_data(self, event):
  1141. # docstring inherited
  1142. x, y = event.xdata, event.ydata
  1143. if (x < self._Ax[0] or x > self._Ax[-1] or
  1144. y < self._Ay[0] or y > self._Ay[-1]):
  1145. return None
  1146. j = np.searchsorted(self._Ax, x) - 1
  1147. i = np.searchsorted(self._Ay, y) - 1
  1148. return self._A[i, j]
  1149. class FigureImage(_ImageBase):
  1150. """An image attached to a figure."""
  1151. zorder = 0
  1152. _interpolation = 'nearest'
  1153. def __init__(self, fig,
  1154. *,
  1155. cmap=None,
  1156. norm=None,
  1157. colorizer=None,
  1158. offsetx=0,
  1159. offsety=0,
  1160. origin=None,
  1161. **kwargs
  1162. ):
  1163. """
  1164. cmap is a colors.Colormap instance
  1165. norm is a colors.Normalize instance to map luminance to 0-1
  1166. kwargs are an optional list of Artist keyword args
  1167. """
  1168. super().__init__(
  1169. None,
  1170. norm=norm,
  1171. cmap=cmap,
  1172. colorizer=colorizer,
  1173. origin=origin
  1174. )
  1175. self.set_figure(fig)
  1176. self.ox = offsetx
  1177. self.oy = offsety
  1178. self._internal_update(kwargs)
  1179. self.magnification = 1.0
  1180. def get_extent(self):
  1181. """Return the image extent as tuple (left, right, bottom, top)."""
  1182. numrows, numcols = self.get_size()
  1183. return (-0.5 + self.ox, numcols-0.5 + self.ox,
  1184. -0.5 + self.oy, numrows-0.5 + self.oy)
  1185. def make_image(self, renderer, magnification=1.0, unsampled=False):
  1186. # docstring inherited
  1187. fig = self.get_figure(root=True)
  1188. fac = renderer.dpi/fig.dpi
  1189. # fac here is to account for pdf, eps, svg backends where
  1190. # figure.dpi is set to 72. This means we need to scale the
  1191. # image (using magnification) and offset it appropriately.
  1192. bbox = Bbox([[self.ox/fac, self.oy/fac],
  1193. [(self.ox/fac + self._A.shape[1]),
  1194. (self.oy/fac + self._A.shape[0])]])
  1195. width, height = fig.get_size_inches()
  1196. width *= renderer.dpi
  1197. height *= renderer.dpi
  1198. clip = Bbox([[0, 0], [width, height]])
  1199. return self._make_image(
  1200. self._A, bbox, bbox, clip, magnification=magnification / fac,
  1201. unsampled=unsampled, round_to_pixel_border=False)
  1202. def set_data(self, A):
  1203. """Set the image array."""
  1204. super().set_data(A)
  1205. self.stale = True
  1206. class BboxImage(_ImageBase):
  1207. """The Image class whose size is determined by the given bbox."""
  1208. def __init__(self, bbox,
  1209. *,
  1210. cmap=None,
  1211. norm=None,
  1212. colorizer=None,
  1213. interpolation=None,
  1214. origin=None,
  1215. filternorm=True,
  1216. filterrad=4.0,
  1217. resample=False,
  1218. **kwargs
  1219. ):
  1220. """
  1221. cmap is a colors.Colormap instance
  1222. norm is a colors.Normalize instance to map luminance to 0-1
  1223. kwargs are an optional list of Artist keyword args
  1224. """
  1225. super().__init__(
  1226. None,
  1227. cmap=cmap,
  1228. norm=norm,
  1229. colorizer=colorizer,
  1230. interpolation=interpolation,
  1231. origin=origin,
  1232. filternorm=filternorm,
  1233. filterrad=filterrad,
  1234. resample=resample,
  1235. **kwargs
  1236. )
  1237. self.bbox = bbox
  1238. def get_window_extent(self, renderer=None):
  1239. if renderer is None:
  1240. renderer = self.get_figure()._get_renderer()
  1241. if isinstance(self.bbox, BboxBase):
  1242. return self.bbox
  1243. elif callable(self.bbox):
  1244. return self.bbox(renderer)
  1245. else:
  1246. raise ValueError("Unknown type of bbox")
  1247. def contains(self, mouseevent):
  1248. """Test whether the mouse event occurred within the image."""
  1249. if self._different_canvas(mouseevent) or not self.get_visible():
  1250. return False, {}
  1251. x, y = mouseevent.x, mouseevent.y
  1252. inside = self.get_window_extent().contains(x, y)
  1253. return inside, {}
  1254. def make_image(self, renderer, magnification=1.0, unsampled=False):
  1255. # docstring inherited
  1256. width, height = renderer.get_canvas_width_height()
  1257. bbox_in = self.get_window_extent(renderer).frozen()
  1258. bbox_in._points /= [width, height]
  1259. bbox_out = self.get_window_extent(renderer)
  1260. clip = Bbox([[0, 0], [width, height]])
  1261. self._transform = BboxTransformTo(clip)
  1262. return self._make_image(
  1263. self._A,
  1264. bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
  1265. def imread(fname, format=None):
  1266. """
  1267. Read an image from a file into an array.
  1268. .. note::
  1269. This function exists for historical reasons. It is recommended to
  1270. use `PIL.Image.open` instead for loading images.
  1271. Parameters
  1272. ----------
  1273. fname : str or file-like
  1274. The image file to read: a filename, a URL or a file-like object opened
  1275. in read-binary mode.
  1276. Passing a URL is deprecated. Please open the URL
  1277. for reading and pass the result to Pillow, e.g. with
  1278. ``np.array(PIL.Image.open(urllib.request.urlopen(url)))``.
  1279. format : str, optional
  1280. The image file format assumed for reading the data. The image is
  1281. loaded as a PNG file if *format* is set to "png", if *fname* is a path
  1282. or opened file with a ".png" extension, or if it is a URL. In all
  1283. other cases, *format* is ignored and the format is auto-detected by
  1284. `PIL.Image.open`.
  1285. Returns
  1286. -------
  1287. `numpy.array`
  1288. The image data. The returned array has shape
  1289. - (M, N) for grayscale images.
  1290. - (M, N, 3) for RGB images.
  1291. - (M, N, 4) for RGBA images.
  1292. PNG images are returned as float arrays (0-1). All other formats are
  1293. returned as int arrays, with a bit depth determined by the file's
  1294. contents.
  1295. """
  1296. # hide imports to speed initial import on systems with slow linkers
  1297. from urllib import parse
  1298. if format is None:
  1299. if isinstance(fname, str):
  1300. parsed = parse.urlparse(fname)
  1301. # If the string is a URL (Windows paths appear as if they have a
  1302. # length-1 scheme), assume png.
  1303. if len(parsed.scheme) > 1:
  1304. ext = 'png'
  1305. else:
  1306. ext = Path(fname).suffix.lower()[1:]
  1307. elif hasattr(fname, 'geturl'): # Returned by urlopen().
  1308. # We could try to parse the url's path and use the extension, but
  1309. # returning png is consistent with the block above. Note that this
  1310. # if clause has to come before checking for fname.name as
  1311. # urlopen("file:///...") also has a name attribute (with the fixed
  1312. # value "<urllib response>").
  1313. ext = 'png'
  1314. elif hasattr(fname, 'name'):
  1315. ext = Path(fname.name).suffix.lower()[1:]
  1316. else:
  1317. ext = 'png'
  1318. else:
  1319. ext = format
  1320. img_open = (
  1321. PIL.PngImagePlugin.PngImageFile if ext == 'png' else PIL.Image.open)
  1322. if isinstance(fname, str) and len(parse.urlparse(fname).scheme) > 1:
  1323. # Pillow doesn't handle URLs directly.
  1324. raise ValueError(
  1325. "Please open the URL for reading and pass the "
  1326. "result to Pillow, e.g. with "
  1327. "``np.array(PIL.Image.open(urllib.request.urlopen(url)))``."
  1328. )
  1329. with img_open(fname) as image:
  1330. return (_pil_png_to_float_array(image)
  1331. if isinstance(image, PIL.PngImagePlugin.PngImageFile) else
  1332. pil_to_array(image))
  1333. def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
  1334. origin=None, dpi=100, *, metadata=None, pil_kwargs=None):
  1335. """
  1336. Colormap and save an array as an image file.
  1337. RGB(A) images are passed through. Single channel images will be
  1338. colormapped according to *cmap* and *norm*.
  1339. .. note::
  1340. If you want to save a single channel image as gray scale please use an
  1341. image I/O library (such as pillow, tifffile, or imageio) directly.
  1342. Parameters
  1343. ----------
  1344. fname : str or path-like or file-like
  1345. A path or a file-like object to store the image in.
  1346. If *format* is not set, then the output format is inferred from the
  1347. extension of *fname*, if any, and from :rc:`savefig.format` otherwise.
  1348. If *format* is set, it determines the output format.
  1349. arr : array-like
  1350. The image data. Accepts NumPy arrays or sequences
  1351. (e.g., lists or tuples). The shape can be one of
  1352. MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
  1353. vmin, vmax : float, optional
  1354. *vmin* and *vmax* set the color scaling for the image by fixing the
  1355. values that map to the colormap color limits. If either *vmin*
  1356. or *vmax* is None, that limit is determined from the *arr*
  1357. min/max value.
  1358. cmap : str or `~matplotlib.colors.Colormap`, default: :rc:`image.cmap`
  1359. A Colormap instance or registered colormap name. The colormap
  1360. maps scalar data to colors. It is ignored for RGB(A) data.
  1361. format : str, optional
  1362. The file format, e.g. 'png', 'pdf', 'svg', ... The behavior when this
  1363. is unset is documented under *fname*.
  1364. origin : {'upper', 'lower'}, default: :rc:`image.origin`
  1365. Indicates whether the ``(0, 0)`` index of the array is in the upper
  1366. left or lower left corner of the Axes.
  1367. dpi : float
  1368. The DPI to store in the metadata of the file. This does not affect the
  1369. resolution of the output image. Depending on file format, this may be
  1370. rounded to the nearest integer.
  1371. metadata : dict, optional
  1372. Metadata in the image file. The supported keys depend on the output
  1373. format, see the documentation of the respective backends for more
  1374. information.
  1375. Currently only supported for "png", "pdf", "ps", "eps", and "svg".
  1376. pil_kwargs : dict, optional
  1377. Keyword arguments passed to `PIL.Image.Image.save`. If the 'pnginfo'
  1378. key is present, it completely overrides *metadata*, including the
  1379. default 'Software' key.
  1380. """
  1381. from matplotlib.figure import Figure
  1382. # Normalizing input (e.g., list or tuples) to NumPy array if needed
  1383. arr = np.asanyarray(arr)
  1384. if isinstance(fname, os.PathLike):
  1385. fname = os.fspath(fname)
  1386. if format is None:
  1387. format = (Path(fname).suffix[1:] if isinstance(fname, str)
  1388. else mpl.rcParams["savefig.format"]).lower()
  1389. if format in ["pdf", "ps", "eps", "svg"]:
  1390. # Vector formats that are not handled by PIL.
  1391. if pil_kwargs is not None:
  1392. raise ValueError(
  1393. f"Cannot use 'pil_kwargs' when saving to {format}")
  1394. fig = Figure(dpi=dpi, frameon=False)
  1395. fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
  1396. resize=True)
  1397. fig.savefig(fname, dpi=dpi, format=format, transparent=True,
  1398. metadata=metadata)
  1399. else:
  1400. # Don't bother creating an image; this avoids rounding errors on the
  1401. # size when dividing and then multiplying by dpi.
  1402. if origin is None:
  1403. origin = mpl.rcParams["image.origin"]
  1404. else:
  1405. _api.check_in_list(('upper', 'lower'), origin=origin)
  1406. if origin == "lower":
  1407. arr = arr[::-1]
  1408. if (isinstance(arr, memoryview) and arr.format == "B"
  1409. and arr.ndim == 3 and arr.shape[-1] == 4):
  1410. # Such an ``arr`` would also be handled fine by sm.to_rgba below
  1411. # (after casting with asarray), but it is useful to special-case it
  1412. # because that's what backend_agg passes, and can be in fact used
  1413. # as is, saving a few operations.
  1414. rgba = arr
  1415. else:
  1416. sm = mcolorizer.Colorizer(cmap=cmap)
  1417. sm.set_clim(vmin, vmax)
  1418. rgba = sm.to_rgba(arr, bytes=True)
  1419. if pil_kwargs is None:
  1420. pil_kwargs = {}
  1421. else:
  1422. # we modify this below, so make a copy (don't modify caller's dict)
  1423. pil_kwargs = pil_kwargs.copy()
  1424. pil_shape = (rgba.shape[1], rgba.shape[0])
  1425. rgba = np.require(rgba, requirements='C')
  1426. image = PIL.Image.frombuffer(
  1427. "RGBA", pil_shape, rgba, "raw", "RGBA", 0, 1)
  1428. if format == "png":
  1429. # Only use the metadata kwarg if pnginfo is not set, because the
  1430. # semantics of duplicate keys in pnginfo is unclear.
  1431. if "pnginfo" in pil_kwargs:
  1432. if metadata:
  1433. _api.warn_external("'metadata' is overridden by the "
  1434. "'pnginfo' entry in 'pil_kwargs'.")
  1435. else:
  1436. metadata = {
  1437. "Software": (f"Matplotlib version{mpl.__version__}, "
  1438. f"https://matplotlib.org/"),
  1439. **(metadata if metadata is not None else {}),
  1440. }
  1441. pil_kwargs["pnginfo"] = pnginfo = PIL.PngImagePlugin.PngInfo()
  1442. for k, v in metadata.items():
  1443. if v is not None:
  1444. pnginfo.add_text(k, v)
  1445. elif metadata is not None:
  1446. raise ValueError(f"metadata not supported for format {format!r}")
  1447. if format in ["jpg", "jpeg"]:
  1448. format = "jpeg" # Pillow doesn't recognize "jpg".
  1449. facecolor = mpl.rcParams["savefig.facecolor"]
  1450. if cbook._str_equal(facecolor, "auto"):
  1451. facecolor = mpl.rcParams["figure.facecolor"]
  1452. color = tuple(int(x * 255) for x in mcolors.to_rgb(facecolor))
  1453. background = PIL.Image.new("RGB", pil_shape, color)
  1454. background.paste(image, image)
  1455. image = background
  1456. pil_kwargs.setdefault("format", format)
  1457. pil_kwargs.setdefault("dpi", (dpi, dpi))
  1458. image.save(fname, **pil_kwargs)
  1459. def pil_to_array(pilImage):
  1460. """
  1461. Load a `PIL image`_ and return it as a numpy int array.
  1462. .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
  1463. Returns
  1464. -------
  1465. numpy.array
  1466. The array shape depends on the image type:
  1467. - (M, N) for grayscale images.
  1468. - (M, N, 3) for RGB images.
  1469. - (M, N, 4) for RGBA images.
  1470. """
  1471. if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
  1472. # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
  1473. return np.asarray(pilImage)
  1474. elif pilImage.mode.startswith('I;16'):
  1475. # return MxN luminance array of uint16
  1476. raw = pilImage.tobytes('raw', pilImage.mode)
  1477. if pilImage.mode.endswith('B'):
  1478. x = np.frombuffer(raw, '>u2')
  1479. else:
  1480. x = np.frombuffer(raw, '<u2')
  1481. return x.reshape(pilImage.size[::-1]).astype('=u2')
  1482. else: # try to convert to an rgba image
  1483. try:
  1484. pilImage = pilImage.convert('RGBA')
  1485. except ValueError as err:
  1486. raise RuntimeError('Unknown image mode') from err
  1487. return np.asarray(pilImage) # return MxNx4 RGBA array
  1488. def _pil_png_to_float_array(pil_png):
  1489. """Convert a PIL `PNGImageFile` to a 0-1 float array."""
  1490. # Unlike pil_to_array this converts to 0-1 float32s for backcompat with the
  1491. # old libpng-based loader.
  1492. # The supported rawmodes are from PIL.PngImagePlugin._MODES. When
  1493. # mode == "RGB(A)", the 16-bit raw data has already been coarsened to 8-bit
  1494. # by Pillow.
  1495. mode = pil_png.mode
  1496. rawmode = pil_png.png.im_rawmode
  1497. if rawmode == "1": # Grayscale.
  1498. return np.asarray(pil_png, np.float32)
  1499. if rawmode == "L;2": # Grayscale.
  1500. return np.divide(pil_png, 2**2 - 1, dtype=np.float32)
  1501. if rawmode == "L;4": # Grayscale.
  1502. return np.divide(pil_png, 2**4 - 1, dtype=np.float32)
  1503. if rawmode == "L": # Grayscale.
  1504. return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
  1505. if rawmode == "I;16B": # Grayscale.
  1506. return np.divide(pil_png, 2**16 - 1, dtype=np.float32)
  1507. if mode == "RGB": # RGB.
  1508. return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
  1509. if mode == "P": # Palette.
  1510. return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
  1511. if mode == "LA": # Grayscale + alpha.
  1512. return np.divide(pil_png.convert("RGBA"), 2**8 - 1, dtype=np.float32)
  1513. if mode == "RGBA": # RGBA.
  1514. return np.divide(pil_png, 2**8 - 1, dtype=np.float32)
  1515. raise ValueError(f"Unknown PIL rawmode: {rawmode}")
  1516. def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
  1517. preview=False):
  1518. """
  1519. Make a thumbnail of image in *infile* with output filename *thumbfile*.
  1520. See :doc:`/gallery/misc/image_thumbnail_sgskip`.
  1521. Parameters
  1522. ----------
  1523. infile : str or file-like
  1524. The image file. Matplotlib relies on Pillow_ for image reading, and
  1525. thus supports a wide range of file formats, including PNG, JPG, TIFF
  1526. and others.
  1527. .. _Pillow: https://python-pillow.github.io
  1528. thumbfile : str or file-like
  1529. The thumbnail filename.
  1530. scale : float, default: 0.1
  1531. The scale factor for the thumbnail.
  1532. interpolation : str, default: 'bilinear'
  1533. The interpolation scheme used in the resampling. See the
  1534. *interpolation* parameter of `~.Axes.imshow` for possible values.
  1535. preview : bool, default: False
  1536. If True, the default backend (presumably a user interface
  1537. backend) will be used which will cause a figure to be raised if
  1538. `~matplotlib.pyplot.show` is called. If it is False, the figure is
  1539. created using `.FigureCanvasBase` and the drawing backend is selected
  1540. as `.Figure.savefig` would normally do.
  1541. Returns
  1542. -------
  1543. `.Figure`
  1544. The figure instance containing the thumbnail.
  1545. """
  1546. im = imread(infile)
  1547. rows, cols, depth = im.shape
  1548. # This doesn't really matter (it cancels in the end) but the API needs it.
  1549. dpi = 100
  1550. height = rows / dpi * scale
  1551. width = cols / dpi * scale
  1552. if preview:
  1553. # Let the UI backend do everything.
  1554. import matplotlib.pyplot as plt
  1555. fig = plt.figure(figsize=(width, height), dpi=dpi)
  1556. else:
  1557. from matplotlib.figure import Figure
  1558. fig = Figure(figsize=(width, height), dpi=dpi)
  1559. FigureCanvasBase(fig)
  1560. ax = fig.add_axes([0, 0, 1, 1], aspect='auto',
  1561. frameon=False, xticks=[], yticks=[])
  1562. ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
  1563. fig.savefig(thumbfile, dpi=dpi)
  1564. return fig