image.py 69 KB

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