You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1530 lines
53 KiB

4 years ago
  1. """
  2. The image module supports basic image loading, rescaling and display
  3. operations.
  4. """
  5. from io import BytesIO
  6. from math import ceil
  7. import os
  8. import logging
  9. import urllib.parse
  10. import urllib.request
  11. import warnings
  12. import numpy as np
  13. from matplotlib import rcParams
  14. import matplotlib.artist as martist
  15. from matplotlib.artist import allow_rasterization
  16. from matplotlib.backend_bases import FigureCanvasBase
  17. import matplotlib.colors as mcolors
  18. import matplotlib.cm as cm
  19. import matplotlib.cbook as cbook
  20. # For clarity, names from _image are given explicitly in this module:
  21. import matplotlib._image as _image
  22. import matplotlib._png as _png
  23. # For user convenience, the names from _image are also imported into
  24. # the image namespace:
  25. from matplotlib._image import *
  26. from matplotlib.transforms import (Affine2D, BboxBase, Bbox, BboxTransform,
  27. IdentityTransform, TransformedBbox)
  28. _log = logging.getLogger(__name__)
  29. # map interpolation strings to module constants
  30. _interpd_ = {
  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. }
  50. interpolations_names = set(_interpd_)
  51. def composite_images(images, renderer, magnification=1.0):
  52. """
  53. Composite a number of RGBA images into one. The images are
  54. composited in the order in which they appear in the `images` list.
  55. Parameters
  56. ----------
  57. images : list of Images
  58. Each must have a `make_image` method. For each image,
  59. `can_composite` should return `True`, though this is not
  60. enforced by this function. Each image must have a purely
  61. affine transformation with no shear.
  62. renderer : RendererBase instance
  63. magnification : float
  64. The additional magnification to apply for the renderer in use.
  65. Returns
  66. -------
  67. tuple : image, offset_x, offset_y
  68. Returns the tuple:
  69. - image: A numpy array of the same type as the input images.
  70. - offset_x, offset_y: The offset of the image (left, bottom)
  71. in the output figure.
  72. """
  73. if len(images) == 0:
  74. return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
  75. parts = []
  76. bboxes = []
  77. for image in images:
  78. data, x, y, trans = image.make_image(renderer, magnification)
  79. if data is not None:
  80. x *= magnification
  81. y *= magnification
  82. parts.append((data, x, y, image.get_alpha() or 1.0))
  83. bboxes.append(
  84. Bbox([[x, y], [x + data.shape[1], y + data.shape[0]]]))
  85. if len(parts) == 0:
  86. return np.empty((0, 0, 4), dtype=np.uint8), 0, 0
  87. bbox = Bbox.union(bboxes)
  88. output = np.zeros(
  89. (int(bbox.height), int(bbox.width), 4), dtype=np.uint8)
  90. for data, x, y, alpha in parts:
  91. trans = Affine2D().translate(x - bbox.x0, y - bbox.y0)
  92. _image.resample(data, output, trans, _image.NEAREST,
  93. resample=False, alpha=alpha)
  94. return output, bbox.x0 / magnification, bbox.y0 / magnification
  95. def _draw_list_compositing_images(
  96. renderer, parent, artists, suppress_composite=None):
  97. """
  98. Draw a sorted list of artists, compositing images into a single
  99. image where possible.
  100. For internal matplotlib use only: It is here to reduce duplication
  101. between `Figure.draw` and `Axes.draw`, but otherwise should not be
  102. generally useful.
  103. """
  104. has_images = any(isinstance(x, _ImageBase) for x in artists)
  105. # override the renderer default if suppressComposite is not None
  106. not_composite = (suppress_composite if suppress_composite is not None
  107. else renderer.option_image_nocomposite())
  108. if not_composite or not has_images:
  109. for a in artists:
  110. a.draw(renderer)
  111. else:
  112. # Composite any adjacent images together
  113. image_group = []
  114. mag = renderer.get_image_magnification()
  115. def flush_images():
  116. if len(image_group) == 1:
  117. image_group[0].draw(renderer)
  118. elif len(image_group) > 1:
  119. data, l, b = composite_images(image_group, renderer, mag)
  120. if data.size != 0:
  121. gc = renderer.new_gc()
  122. gc.set_clip_rectangle(parent.bbox)
  123. gc.set_clip_path(parent.get_clip_path())
  124. renderer.draw_image(gc, np.round(l), np.round(b), data)
  125. gc.restore()
  126. del image_group[:]
  127. for a in artists:
  128. if isinstance(a, _ImageBase) and a.can_composite():
  129. image_group.append(a)
  130. else:
  131. flush_images()
  132. a.draw(renderer)
  133. flush_images()
  134. def _rgb_to_rgba(A):
  135. """
  136. Convert an RGB image to RGBA, as required by the image resample C++
  137. extension.
  138. """
  139. rgba = np.zeros((A.shape[0], A.shape[1], 4), dtype=A.dtype)
  140. rgba[:, :, :3] = A
  141. if rgba.dtype == np.uint8:
  142. rgba[:, :, 3] = 255
  143. else:
  144. rgba[:, :, 3] = 1.0
  145. return rgba
  146. class _ImageBase(martist.Artist, cm.ScalarMappable):
  147. zorder = 0
  148. def __str__(self):
  149. return "AxesImage(%g,%g;%gx%g)" % tuple(self.axes.bbox.bounds)
  150. def __init__(self, ax,
  151. cmap=None,
  152. norm=None,
  153. interpolation=None,
  154. origin=None,
  155. filternorm=True,
  156. filterrad=4.0,
  157. resample=False,
  158. **kwargs
  159. ):
  160. """
  161. interpolation and cmap default to their rc settings
  162. cmap is a colors.Colormap instance
  163. norm is a colors.Normalize instance to map luminance to 0-1
  164. extent is data axes (left, right, bottom, top) for making image plots
  165. registered with data plots. Default is to label the pixel
  166. centers with the zero-based row and column indices.
  167. Additional kwargs are matplotlib.artist properties
  168. """
  169. martist.Artist.__init__(self)
  170. cm.ScalarMappable.__init__(self, norm, cmap)
  171. self._mouseover = True
  172. if origin is None:
  173. origin = rcParams['image.origin']
  174. self.origin = origin
  175. self.set_filternorm(filternorm)
  176. self.set_filterrad(filterrad)
  177. self.set_interpolation(interpolation)
  178. self.set_resample(resample)
  179. self.axes = ax
  180. self._imcache = None
  181. self.update(kwargs)
  182. def __getstate__(self):
  183. state = super().__getstate__()
  184. # We can't pickle the C Image cached object.
  185. state['_imcache'] = None
  186. return state
  187. def get_size(self):
  188. """Get the numrows, numcols of the input image"""
  189. if self._A is None:
  190. raise RuntimeError('You must first set the image array')
  191. return self._A.shape[:2]
  192. def set_alpha(self, alpha):
  193. """
  194. Set the alpha value used for blending - not supported on all backends.
  195. Parameters
  196. ----------
  197. alpha : float
  198. """
  199. martist.Artist.set_alpha(self, alpha)
  200. self._imcache = None
  201. def changed(self):
  202. """
  203. Call this whenever the mappable is changed so observers can
  204. update state
  205. """
  206. self._imcache = None
  207. self._rgbacache = None
  208. cm.ScalarMappable.changed(self)
  209. def _make_image(self, A, in_bbox, out_bbox, clip_bbox, magnification=1.0,
  210. unsampled=False, round_to_pixel_border=True):
  211. """
  212. Normalize, rescale and color the image `A` from the given
  213. in_bbox (in data space), to the given out_bbox (in pixel
  214. space) clipped to the given clip_bbox (also in pixel space),
  215. and magnified by the magnification factor.
  216. `A` may be a greyscale image (MxN) with a dtype of `float32`,
  217. `float64`, `float128`, `uint16` or `uint8`, or an RGBA image (MxNx4)
  218. with a dtype of `float32`, `float64`, `float128`, or `uint8`.
  219. If `unsampled` is True, the image will not be scaled, but an
  220. appropriate affine transformation will be returned instead.
  221. If `round_to_pixel_border` is True, the output image size will
  222. be rounded to the nearest pixel boundary. This makes the
  223. images align correctly with the axes. It should not be used
  224. in cases where you want exact scaling, however, such as
  225. FigureImage.
  226. Returns the resulting (image, x, y, trans), where (x, y) is
  227. the upper left corner of the result in pixel space, and
  228. `trans` is the affine transformation from the image to pixel
  229. space.
  230. """
  231. if A is None:
  232. raise RuntimeError('You must first set the image '
  233. 'array or the image attribute')
  234. if A.size == 0:
  235. raise RuntimeError("_make_image must get a non-empty image. "
  236. "Your Artist's draw method must filter before "
  237. "this method is called.")
  238. clipped_bbox = Bbox.intersection(out_bbox, clip_bbox)
  239. if clipped_bbox is None:
  240. return None, 0, 0, None
  241. out_width_base = clipped_bbox.width * magnification
  242. out_height_base = clipped_bbox.height * magnification
  243. if out_width_base == 0 or out_height_base == 0:
  244. return None, 0, 0, None
  245. if self.origin == 'upper':
  246. # Flip the input image using a transform. This avoids the
  247. # problem with flipping the array, which results in a copy
  248. # when it is converted to contiguous in the C wrapper
  249. t0 = Affine2D().translate(0, -A.shape[0]).scale(1, -1)
  250. else:
  251. t0 = IdentityTransform()
  252. t0 += (
  253. Affine2D()
  254. .scale(
  255. in_bbox.width / A.shape[1],
  256. in_bbox.height / A.shape[0])
  257. .translate(in_bbox.x0, in_bbox.y0)
  258. + self.get_transform())
  259. t = (t0
  260. + Affine2D().translate(
  261. -clipped_bbox.x0,
  262. -clipped_bbox.y0)
  263. .scale(magnification, magnification))
  264. # So that the image is aligned with the edge of the axes, we want
  265. # to round up the output width to the next integer. This also
  266. # means scaling the transform just slightly to account for the
  267. # extra subpixel.
  268. if (t.is_affine and round_to_pixel_border and
  269. (out_width_base % 1.0 != 0.0 or out_height_base % 1.0 != 0.0)):
  270. out_width = int(ceil(out_width_base))
  271. out_height = int(ceil(out_height_base))
  272. extra_width = (out_width - out_width_base) / out_width_base
  273. extra_height = (out_height - out_height_base) / out_height_base
  274. t += Affine2D().scale(1.0 + extra_width, 1.0 + extra_height)
  275. else:
  276. out_width = int(out_width_base)
  277. out_height = int(out_height_base)
  278. if not unsampled:
  279. if A.ndim not in (2, 3):
  280. raise ValueError("Invalid dimensions, got {}".format(A.shape))
  281. if A.ndim == 2:
  282. # if we are a 2D array, then we are running through the
  283. # norm + colormap transformation. However, in general the
  284. # input data is not going to match the size on the screen so we
  285. # have to resample to the correct number of pixels
  286. # need to
  287. # TODO slice input array first
  288. inp_dtype = A.dtype
  289. a_min = A.min()
  290. a_max = A.max()
  291. # figure out the type we should scale to. For floats,
  292. # leave as is. For integers cast to an appropriate-sized
  293. # float. Small integers get smaller floats in an attempt
  294. # to keep the memory footprint reasonable.
  295. if a_min is np.ma.masked:
  296. # all masked, so values don't matter
  297. a_min, a_max = np.int32(0), np.int32(1)
  298. if inp_dtype.kind == 'f':
  299. scaled_dtype = A.dtype
  300. # Cast to float64
  301. if A.dtype not in (np.float32, np.float16):
  302. if A.dtype != np.float64:
  303. warnings.warn(
  304. "Casting input data from '{0}' to 'float64'"
  305. "for imshow".format(A.dtype))
  306. scaled_dtype = np.float64
  307. else:
  308. # probably an integer of some type.
  309. da = a_max.astype(np.float64) - a_min.astype(np.float64)
  310. if da > 1e8:
  311. # give more breathing room if a big dynamic range
  312. scaled_dtype = np.float64
  313. else:
  314. scaled_dtype = np.float32
  315. # scale the input data to [.1, .9]. The Agg
  316. # interpolators clip to [0, 1] internally, use a
  317. # smaller input scale to identify which of the
  318. # interpolated points need to be should be flagged as
  319. # over / under.
  320. # This may introduce numeric instabilities in very broadly
  321. # scaled data
  322. A_scaled = np.empty(A.shape, dtype=scaled_dtype)
  323. A_scaled[:] = A
  324. # clip scaled data around norm if necessary.
  325. # This is necessary for big numbers at the edge of
  326. # float64's ability to represent changes. Applying
  327. # a norm first would be good, but ruins the interpolation
  328. # of over numbers.
  329. self.norm.autoscale_None(A)
  330. dv = (np.float64(self.norm.vmax) -
  331. np.float64(self.norm.vmin))
  332. vmid = self.norm.vmin + dv / 2
  333. fact = 1e7 if scaled_dtype == np.float64 else 1e4
  334. newmin = vmid - dv * fact
  335. if newmin < a_min:
  336. newmin = None
  337. else:
  338. a_min = np.float64(newmin)
  339. newmax = vmid + dv * fact
  340. if newmax > a_max:
  341. newmax = None
  342. else:
  343. a_max = np.float64(newmax)
  344. if newmax is not None or newmin is not None:
  345. A_scaled = np.clip(A_scaled, newmin, newmax)
  346. A_scaled -= a_min
  347. # a_min and a_max might be ndarray subclasses so use
  348. # item to avoid errors
  349. a_min = a_min.astype(scaled_dtype).item()
  350. a_max = a_max.astype(scaled_dtype).item()
  351. if a_min != a_max:
  352. A_scaled /= ((a_max - a_min) / 0.8)
  353. A_scaled += 0.1
  354. A_resampled = np.zeros((out_height, out_width),
  355. dtype=A_scaled.dtype)
  356. # resample the input data to the correct resolution and shape
  357. _image.resample(A_scaled, A_resampled,
  358. t,
  359. _interpd_[self.get_interpolation()],
  360. self.get_resample(), 1.0,
  361. self.get_filternorm(),
  362. self.get_filterrad())
  363. # we are done with A_scaled now, remove from namespace
  364. # to be sure!
  365. del A_scaled
  366. # un-scale the resampled data to approximately the
  367. # original range things that interpolated to above /
  368. # below the original min/max will still be above /
  369. # below, but possibly clipped in the case of higher order
  370. # interpolation + drastically changing data.
  371. A_resampled -= 0.1
  372. if a_min != a_max:
  373. A_resampled *= ((a_max - a_min) / 0.8)
  374. A_resampled += a_min
  375. # if using NoNorm, cast back to the original datatype
  376. if isinstance(self.norm, mcolors.NoNorm):
  377. A_resampled = A_resampled.astype(A.dtype)
  378. mask = np.empty(A.shape, dtype=np.float32)
  379. if A.mask.shape == A.shape:
  380. # this is the case of a nontrivial mask
  381. mask[:] = np.where(A.mask, np.float32(np.nan),
  382. np.float32(1))
  383. else:
  384. mask[:] = 1
  385. # we always have to interpolate the mask to account for
  386. # non-affine transformations
  387. out_mask = np.zeros((out_height, out_width),
  388. dtype=mask.dtype)
  389. _image.resample(mask, out_mask,
  390. t,
  391. _interpd_[self.get_interpolation()],
  392. True, 1,
  393. self.get_filternorm(),
  394. self.get_filterrad())
  395. # we are done with the mask, delete from namespace to be sure!
  396. del mask
  397. # Agg updates the out_mask in place. If the pixel has
  398. # no image data it will not be updated (and still be 0
  399. # as we initialized it), if input data that would go
  400. # into that output pixel than it will be `nan`, if all
  401. # the input data for a pixel is good it will be 1, and
  402. # if there is _some_ good data in that output pixel it
  403. # will be between [0, 1] (such as a rotated image).
  404. out_alpha = np.array(out_mask)
  405. out_mask = np.isnan(out_mask)
  406. out_alpha[out_mask] = 1
  407. # mask and run through the norm
  408. output = self.norm(np.ma.masked_array(A_resampled, out_mask))
  409. else:
  410. # Always convert to RGBA, even if only RGB input
  411. if A.shape[2] == 3:
  412. A = _rgb_to_rgba(A)
  413. elif A.shape[2] != 4:
  414. raise ValueError("Invalid dimensions, got %s" % (A.shape,))
  415. output = np.zeros((out_height, out_width, 4), dtype=A.dtype)
  416. alpha = self.get_alpha()
  417. if alpha is None:
  418. alpha = 1.0
  419. _image.resample(
  420. A, output, t, _interpd_[self.get_interpolation()],
  421. self.get_resample(), alpha,
  422. self.get_filternorm(), self.get_filterrad())
  423. # at this point output is either a 2D array of normed data
  424. # (of int or float)
  425. # or an RGBA array of re-sampled input
  426. output = self.to_rgba(output, bytes=True, norm=False)
  427. # output is now a correctly sized RGBA array of uint8
  428. # Apply alpha *after* if the input was greyscale without a mask
  429. if A.ndim == 2:
  430. alpha = self.get_alpha()
  431. if alpha is None:
  432. alpha = 1
  433. alpha_channel = output[:, :, 3]
  434. alpha_channel[:] = np.asarray(
  435. np.asarray(alpha_channel, np.float32) * out_alpha * alpha,
  436. np.uint8)
  437. else:
  438. if self._imcache is None:
  439. self._imcache = self.to_rgba(A, bytes=True, norm=(A.ndim == 2))
  440. output = self._imcache
  441. # Subset the input image to only the part that will be
  442. # displayed
  443. subset = TransformedBbox(
  444. clip_bbox, t0.frozen().inverted()).frozen()
  445. output = output[
  446. int(max(subset.ymin, 0)):
  447. int(min(subset.ymax + 1, output.shape[0])),
  448. int(max(subset.xmin, 0)):
  449. int(min(subset.xmax + 1, output.shape[1]))]
  450. t = Affine2D().translate(
  451. int(max(subset.xmin, 0)), int(max(subset.ymin, 0))) + t
  452. return output, clipped_bbox.x0, clipped_bbox.y0, t
  453. def make_image(self, renderer, magnification=1.0, unsampled=False):
  454. raise RuntimeError('The make_image method must be overridden.')
  455. def _draw_unsampled_image(self, renderer, gc):
  456. """
  457. draw unsampled image. The renderer should support a draw_image method
  458. with scale parameter.
  459. """
  460. im, l, b, trans = self.make_image(renderer, unsampled=True)
  461. if im is None:
  462. return
  463. trans = Affine2D().scale(im.shape[1], im.shape[0]) + trans
  464. renderer.draw_image(gc, l, b, im, trans)
  465. def _check_unsampled_image(self, renderer):
  466. """
  467. return True if the image is better to be drawn unsampled.
  468. The derived class needs to override it.
  469. """
  470. return False
  471. @allow_rasterization
  472. def draw(self, renderer, *args, **kwargs):
  473. # if not visible, declare victory and return
  474. if not self.get_visible():
  475. self.stale = False
  476. return
  477. # for empty images, there is nothing to draw!
  478. if self.get_array().size == 0:
  479. self.stale = False
  480. return
  481. # actually render the image.
  482. gc = renderer.new_gc()
  483. self._set_gc_clip(gc)
  484. gc.set_alpha(self.get_alpha())
  485. gc.set_url(self.get_url())
  486. gc.set_gid(self.get_gid())
  487. if (self._check_unsampled_image(renderer) and
  488. self.get_transform().is_affine):
  489. self._draw_unsampled_image(renderer, gc)
  490. else:
  491. im, l, b, trans = self.make_image(
  492. renderer, renderer.get_image_magnification())
  493. if im is not None:
  494. renderer.draw_image(gc, l, b, im)
  495. gc.restore()
  496. self.stale = False
  497. def contains(self, mouseevent):
  498. """
  499. Test whether the mouse event occurred within the image.
  500. """
  501. if callable(self._contains):
  502. return self._contains(self, mouseevent)
  503. # TODO: make sure this is consistent with patch and patch
  504. # collection on nonlinear transformed coordinates.
  505. # TODO: consider returning image coordinates (shouldn't
  506. # be too difficult given that the image is rectilinear
  507. x, y = mouseevent.xdata, mouseevent.ydata
  508. xmin, xmax, ymin, ymax = self.get_extent()
  509. if xmin > xmax:
  510. xmin, xmax = xmax, xmin
  511. if ymin > ymax:
  512. ymin, ymax = ymax, ymin
  513. if x is not None and y is not None:
  514. inside = (xmin <= x <= xmax) and (ymin <= y <= ymax)
  515. else:
  516. inside = False
  517. return inside, {}
  518. def write_png(self, fname):
  519. """Write the image to png file with fname"""
  520. im = self.to_rgba(self._A[::-1] if self.origin == 'lower' else self._A,
  521. bytes=True, norm=True)
  522. _png.write_png(im, fname)
  523. def set_data(self, A):
  524. """
  525. Set the image array.
  526. Note that this function does *not* update the normalization used.
  527. Parameters
  528. ----------
  529. A : array-like
  530. """
  531. # check if data is PIL Image without importing Image
  532. if hasattr(A, 'getpixel'):
  533. if A.mode == 'L':
  534. # greyscale image, but our logic assumes rgba:
  535. self._A = pil_to_array(A.convert('RGBA'))
  536. else:
  537. self._A = pil_to_array(A)
  538. else:
  539. self._A = cbook.safe_masked_invalid(A, copy=True)
  540. if (self._A.dtype != np.uint8 and
  541. not np.can_cast(self._A.dtype, float, "same_kind")):
  542. raise TypeError("Image data cannot be converted to float")
  543. if not (self._A.ndim == 2
  544. or self._A.ndim == 3 and self._A.shape[-1] in [3, 4]):
  545. raise TypeError("Invalid dimensions for image data")
  546. if self._A.ndim == 3:
  547. # If the input data has values outside the valid range (after
  548. # normalisation), we issue a warning and then clip X to the bounds
  549. # - otherwise casting wraps extreme values, hiding outliers and
  550. # making reliable interpretation impossible.
  551. high = 255 if np.issubdtype(self._A.dtype, np.integer) else 1
  552. if self._A.min() < 0 or high < self._A.max():
  553. _log.warning(
  554. 'Clipping input data to the valid range for imshow with '
  555. 'RGB data ([0..1] for floats or [0..255] for integers).'
  556. )
  557. self._A = np.clip(self._A, 0, high)
  558. # Cast unsupported integer types to uint8
  559. if self._A.dtype != np.uint8 and np.issubdtype(self._A.dtype,
  560. np.integer):
  561. self._A = self._A.astype(np.uint8)
  562. self._imcache = None
  563. self._rgbacache = None
  564. self.stale = True
  565. def set_array(self, A):
  566. """
  567. Retained for backwards compatibility - use set_data instead.
  568. Parameters
  569. ----------
  570. A : array-like
  571. """
  572. # This also needs to be here to override the inherited
  573. # cm.ScalarMappable.set_array method so it is not invoked by mistake.
  574. self.set_data(A)
  575. def get_interpolation(self):
  576. """
  577. Return the interpolation method the image uses when resizing.
  578. One of 'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36',
  579. 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom',
  580. 'gaussian', 'bessel', 'mitchell', 'sinc', 'lanczos', or 'none'.
  581. """
  582. return self._interpolation
  583. def set_interpolation(self, s):
  584. """
  585. Set the interpolation method the image uses when resizing.
  586. if None, use a value from rc setting. If 'none', the image is
  587. shown as is without interpolating. 'none' is only supported in
  588. agg, ps and pdf backends and will fall back to 'nearest' mode
  589. for other backends.
  590. Parameters
  591. ----------
  592. s : {'nearest', 'bilinear', 'bicubic', 'spline16', 'spline36', \
  593. 'hanning', 'hamming', 'hermite', 'kaiser', 'quadric', 'catrom', 'gaussian', \
  594. 'bessel', 'mitchell', 'sinc', 'lanczos', 'none'}
  595. """
  596. if s is None:
  597. s = rcParams['image.interpolation']
  598. s = s.lower()
  599. if s not in _interpd_:
  600. raise ValueError('Illegal interpolation string')
  601. self._interpolation = s
  602. self.stale = True
  603. def can_composite(self):
  604. """
  605. Returns `True` if the image can be composited with its neighbors.
  606. """
  607. trans = self.get_transform()
  608. return (
  609. self._interpolation != 'none' and
  610. trans.is_affine and
  611. trans.is_separable)
  612. def set_resample(self, v):
  613. """
  614. Set whether or not image resampling is used.
  615. Parameters
  616. ----------
  617. v : bool
  618. """
  619. if v is None:
  620. v = rcParams['image.resample']
  621. self._resample = v
  622. self.stale = True
  623. def get_resample(self):
  624. """Return the image resample boolean."""
  625. return self._resample
  626. def set_filternorm(self, filternorm):
  627. """
  628. Set whether the resize filter normalizes the weights.
  629. See help for `~.Axes.imshow`.
  630. Parameters
  631. ----------
  632. filternorm : bool
  633. """
  634. self._filternorm = bool(filternorm)
  635. self.stale = True
  636. def get_filternorm(self):
  637. """Return whether the resize filter normalizes the weights."""
  638. return self._filternorm
  639. def set_filterrad(self, filterrad):
  640. """
  641. Set the resize filter radius only applicable to some
  642. interpolation schemes -- see help for imshow
  643. Parameters
  644. ----------
  645. filterrad : positive float
  646. """
  647. r = float(filterrad)
  648. if r <= 0:
  649. raise ValueError("The filter radius must be a positive number")
  650. self._filterrad = r
  651. self.stale = True
  652. def get_filterrad(self):
  653. """Return the filterrad setting."""
  654. return self._filterrad
  655. class AxesImage(_ImageBase):
  656. def __str__(self):
  657. return "AxesImage(%g,%g;%gx%g)" % tuple(self.axes.bbox.bounds)
  658. def __init__(self, ax,
  659. cmap=None,
  660. norm=None,
  661. interpolation=None,
  662. origin=None,
  663. extent=None,
  664. filternorm=1,
  665. filterrad=4.0,
  666. resample=False,
  667. **kwargs
  668. ):
  669. """
  670. interpolation and cmap default to their rc settings
  671. cmap is a colors.Colormap instance
  672. norm is a colors.Normalize instance to map luminance to 0-1
  673. extent is data axes (left, right, bottom, top) for making image plots
  674. registered with data plots. Default is to label the pixel
  675. centers with the zero-based row and column indices.
  676. Additional kwargs are matplotlib.artist properties
  677. """
  678. self._extent = extent
  679. super().__init__(
  680. ax,
  681. cmap=cmap,
  682. norm=norm,
  683. interpolation=interpolation,
  684. origin=origin,
  685. filternorm=filternorm,
  686. filterrad=filterrad,
  687. resample=resample,
  688. **kwargs
  689. )
  690. def get_window_extent(self, renderer=None):
  691. x0, x1, y0, y1 = self._extent
  692. bbox = Bbox.from_extents([x0, y0, x1, y1])
  693. return bbox.transformed(self.axes.transData)
  694. def make_image(self, renderer, magnification=1.0, unsampled=False):
  695. trans = self.get_transform()
  696. # image is created in the canvas coordinate.
  697. x1, x2, y1, y2 = self.get_extent()
  698. bbox = Bbox(np.array([[x1, y1], [x2, y2]]))
  699. transformed_bbox = TransformedBbox(bbox, trans)
  700. return self._make_image(
  701. self._A, bbox, transformed_bbox, self.axes.bbox, magnification,
  702. unsampled=unsampled)
  703. def _check_unsampled_image(self, renderer):
  704. """
  705. Return whether the image would be better drawn unsampled.
  706. """
  707. return (self.get_interpolation() == "none"
  708. and renderer.option_scale_image())
  709. def set_extent(self, extent):
  710. """
  711. extent is data axes (left, right, bottom, top) for making image plots
  712. This updates ax.dataLim, and, if autoscaling, sets viewLim
  713. to tightly fit the image, regardless of dataLim. Autoscaling
  714. state is not changed, so following this with ax.autoscale_view
  715. will redo the autoscaling in accord with dataLim.
  716. """
  717. self._extent = xmin, xmax, ymin, ymax = extent
  718. corners = (xmin, ymin), (xmax, ymax)
  719. self.axes.update_datalim(corners)
  720. self.sticky_edges.x[:] = [xmin, xmax]
  721. self.sticky_edges.y[:] = [ymin, ymax]
  722. if self.axes._autoscaleXon:
  723. self.axes.set_xlim((xmin, xmax), auto=None)
  724. if self.axes._autoscaleYon:
  725. self.axes.set_ylim((ymin, ymax), auto=None)
  726. self.stale = True
  727. def get_extent(self):
  728. """Get the image extent: left, right, bottom, top"""
  729. if self._extent is not None:
  730. return self._extent
  731. else:
  732. sz = self.get_size()
  733. numrows, numcols = sz
  734. if self.origin == 'upper':
  735. return (-0.5, numcols-0.5, numrows-0.5, -0.5)
  736. else:
  737. return (-0.5, numcols-0.5, -0.5, numrows-0.5)
  738. def get_cursor_data(self, event):
  739. """Get the cursor data for a given event"""
  740. xmin, xmax, ymin, ymax = self.get_extent()
  741. if self.origin == 'upper':
  742. ymin, ymax = ymax, ymin
  743. arr = self.get_array()
  744. data_extent = Bbox([[ymin, xmin], [ymax, xmax]])
  745. array_extent = Bbox([[0, 0], arr.shape[:2]])
  746. trans = BboxTransform(boxin=data_extent, boxout=array_extent)
  747. y, x = event.ydata, event.xdata
  748. point = trans.transform_point([y, x])
  749. if any(np.isnan(point)):
  750. return None
  751. i, j = point.astype(int)
  752. # Clip the coordinates at array bounds
  753. if not (0 <= i < arr.shape[0]) or not (0 <= j < arr.shape[1]):
  754. return None
  755. else:
  756. return arr[i, j]
  757. class NonUniformImage(AxesImage):
  758. def __init__(self, ax, *, interpolation='nearest', **kwargs):
  759. """
  760. kwargs are identical to those for AxesImage, except
  761. that 'nearest' and 'bilinear' are the only supported 'interpolation'
  762. options.
  763. """
  764. super().__init__(ax, **kwargs)
  765. self.set_interpolation(interpolation)
  766. def _check_unsampled_image(self, renderer):
  767. """
  768. return False. Do not use unsampled image.
  769. """
  770. return False
  771. def make_image(self, renderer, magnification=1.0, unsampled=False):
  772. if self._A is None:
  773. raise RuntimeError('You must first set the image array')
  774. if unsampled:
  775. raise ValueError('unsampled not supported on NonUniformImage')
  776. A = self._A
  777. if A.ndim == 2:
  778. if A.dtype != np.uint8:
  779. A = self.to_rgba(A, bytes=True)
  780. self.is_grayscale = self.cmap.is_gray()
  781. else:
  782. A = np.repeat(A[:, :, np.newaxis], 4, 2)
  783. A[:, :, 3] = 255
  784. self.is_grayscale = True
  785. else:
  786. if A.dtype != np.uint8:
  787. A = (255*A).astype(np.uint8)
  788. if A.shape[2] == 3:
  789. B = np.zeros(tuple([*A.shape[0:2], 4]), np.uint8)
  790. B[:, :, 0:3] = A
  791. B[:, :, 3] = 255
  792. A = B
  793. self.is_grayscale = False
  794. x0, y0, v_width, v_height = self.axes.viewLim.bounds
  795. l, b, r, t = self.axes.bbox.extents
  796. width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
  797. height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
  798. width *= magnification
  799. height *= magnification
  800. im = _image.pcolor(self._Ax, self._Ay, A,
  801. int(height), int(width),
  802. (x0, x0+v_width, y0, y0+v_height),
  803. _interpd_[self._interpolation])
  804. return im, l, b, IdentityTransform()
  805. def set_data(self, x, y, A):
  806. """
  807. Set the grid for the pixel centers, and the pixel values.
  808. *x* and *y* are monotonic 1-D ndarrays of lengths N and M,
  809. respectively, specifying pixel centers
  810. *A* is an (M,N) ndarray or masked array of values to be
  811. colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
  812. array.
  813. """
  814. x = np.array(x, np.float32)
  815. y = np.array(y, np.float32)
  816. A = cbook.safe_masked_invalid(A, copy=True)
  817. if not (x.ndim == y.ndim == 1 and A.shape[0:2] == y.shape + x.shape):
  818. raise TypeError("Axes don't match array shape")
  819. if A.ndim not in [2, 3]:
  820. raise TypeError("Can only plot 2D or 3D data")
  821. if A.ndim == 3 and A.shape[2] not in [1, 3, 4]:
  822. raise TypeError("3D arrays must have three (RGB) "
  823. "or four (RGBA) color components")
  824. if A.ndim == 3 and A.shape[2] == 1:
  825. A.shape = A.shape[0:2]
  826. self._A = A
  827. self._Ax = x
  828. self._Ay = y
  829. self._imcache = None
  830. self.stale = True
  831. def set_array(self, *args):
  832. raise NotImplementedError('Method not supported')
  833. def set_interpolation(self, s):
  834. """
  835. Parameters
  836. ----------
  837. s : str, None
  838. Either 'nearest', 'bilinear', or ``None``.
  839. """
  840. if s is not None and s not in ('nearest', 'bilinear'):
  841. raise NotImplementedError('Only nearest neighbor and '
  842. 'bilinear interpolations are supported')
  843. AxesImage.set_interpolation(self, s)
  844. def get_extent(self):
  845. if self._A is None:
  846. raise RuntimeError('Must set data first')
  847. return self._Ax[0], self._Ax[-1], self._Ay[0], self._Ay[-1]
  848. def set_filternorm(self, s):
  849. pass
  850. def set_filterrad(self, s):
  851. pass
  852. def set_norm(self, norm):
  853. if self._A is not None:
  854. raise RuntimeError('Cannot change colors after loading data')
  855. super().set_norm(norm)
  856. def set_cmap(self, cmap):
  857. if self._A is not None:
  858. raise RuntimeError('Cannot change colors after loading data')
  859. super().set_cmap(cmap)
  860. class PcolorImage(AxesImage):
  861. """
  862. Make a pcolor-style plot with an irregular rectangular grid.
  863. This uses a variation of the original irregular image code,
  864. and it is used by pcolorfast for the corresponding grid type.
  865. """
  866. def __init__(self, ax,
  867. x=None,
  868. y=None,
  869. A=None,
  870. cmap=None,
  871. norm=None,
  872. **kwargs
  873. ):
  874. """
  875. cmap defaults to its rc setting
  876. cmap is a colors.Colormap instance
  877. norm is a colors.Normalize instance to map luminance to 0-1
  878. Additional kwargs are matplotlib.artist properties
  879. """
  880. super().__init__(ax, norm=norm, cmap=cmap)
  881. self.update(kwargs)
  882. if A is not None:
  883. self.set_data(x, y, A)
  884. def make_image(self, renderer, magnification=1.0, unsampled=False):
  885. if self._A is None:
  886. raise RuntimeError('You must first set the image array')
  887. if unsampled:
  888. raise ValueError('unsampled not supported on PColorImage')
  889. fc = self.axes.patch.get_facecolor()
  890. bg = mcolors.to_rgba(fc, 0)
  891. bg = (np.array(bg)*255).astype(np.uint8)
  892. l, b, r, t = self.axes.bbox.extents
  893. width = (np.round(r) + 0.5) - (np.round(l) - 0.5)
  894. height = (np.round(t) + 0.5) - (np.round(b) - 0.5)
  895. # The extra cast-to-int is only needed for python2
  896. width = int(np.round(width * magnification))
  897. height = int(np.round(height * magnification))
  898. if self._rgbacache is None:
  899. A = self.to_rgba(self._A, bytes=True)
  900. self._rgbacache = A
  901. if self._A.ndim == 2:
  902. self.is_grayscale = self.cmap.is_gray()
  903. else:
  904. A = self._rgbacache
  905. vl = self.axes.viewLim
  906. im = _image.pcolor2(self._Ax, self._Ay, A,
  907. height,
  908. width,
  909. (vl.x0, vl.x1, vl.y0, vl.y1),
  910. bg)
  911. return im, l, b, IdentityTransform()
  912. def _check_unsampled_image(self, renderer):
  913. return False
  914. def set_data(self, x, y, A):
  915. """
  916. Set the grid for the rectangle boundaries, and the data values.
  917. *x* and *y* are monotonic 1-D ndarrays of lengths N+1 and M+1,
  918. respectively, specifying rectangle boundaries. If None,
  919. they will be created as uniform arrays from 0 through N
  920. and 0 through M, respectively.
  921. *A* is an (M,N) ndarray or masked array of values to be
  922. colormapped, or a (M,N,3) RGB array, or a (M,N,4) RGBA
  923. array.
  924. """
  925. A = cbook.safe_masked_invalid(A, copy=True)
  926. if x is None:
  927. x = np.arange(0, A.shape[1]+1, dtype=np.float64)
  928. else:
  929. x = np.array(x, np.float64).ravel()
  930. if y is None:
  931. y = np.arange(0, A.shape[0]+1, dtype=np.float64)
  932. else:
  933. y = np.array(y, np.float64).ravel()
  934. if A.shape[:2] != (y.size-1, x.size-1):
  935. raise ValueError(
  936. "Axes don't match array shape. Got %s, expected %s." %
  937. (A.shape[:2], (y.size - 1, x.size - 1)))
  938. if A.ndim not in [2, 3]:
  939. raise ValueError("A must be 2D or 3D")
  940. if A.ndim == 3 and A.shape[2] == 1:
  941. A.shape = A.shape[:2]
  942. self.is_grayscale = False
  943. if A.ndim == 3:
  944. if A.shape[2] in [3, 4]:
  945. if ((A[:, :, 0] == A[:, :, 1]).all() and
  946. (A[:, :, 0] == A[:, :, 2]).all()):
  947. self.is_grayscale = True
  948. else:
  949. raise ValueError("3D arrays must have RGB or RGBA as last dim")
  950. # For efficient cursor readout, ensure x and y are increasing.
  951. if x[-1] < x[0]:
  952. x = x[::-1]
  953. A = A[:, ::-1]
  954. if y[-1] < y[0]:
  955. y = y[::-1]
  956. A = A[::-1]
  957. self._A = A
  958. self._Ax = x
  959. self._Ay = y
  960. self._rgbacache = None
  961. self.stale = True
  962. def set_array(self, *args):
  963. raise NotImplementedError('Method not supported')
  964. def get_cursor_data(self, event):
  965. """Get the cursor data for a given event"""
  966. x, y = event.xdata, event.ydata
  967. if (x < self._Ax[0] or x > self._Ax[-1] or
  968. y < self._Ay[0] or y > self._Ay[-1]):
  969. return None
  970. j = np.searchsorted(self._Ax, x) - 1
  971. i = np.searchsorted(self._Ay, y) - 1
  972. try:
  973. return self._A[i, j]
  974. except IndexError:
  975. return None
  976. class FigureImage(_ImageBase):
  977. zorder = 0
  978. _interpolation = 'nearest'
  979. def __init__(self, fig,
  980. cmap=None,
  981. norm=None,
  982. offsetx=0,
  983. offsety=0,
  984. origin=None,
  985. **kwargs
  986. ):
  987. """
  988. cmap is a colors.Colormap instance
  989. norm is a colors.Normalize instance to map luminance to 0-1
  990. kwargs are an optional list of Artist keyword args
  991. """
  992. super().__init__(
  993. None,
  994. norm=norm,
  995. cmap=cmap,
  996. origin=origin
  997. )
  998. self.figure = fig
  999. self.ox = offsetx
  1000. self.oy = offsety
  1001. self.update(kwargs)
  1002. self.magnification = 1.0
  1003. def get_extent(self):
  1004. """Get the image extent: left, right, bottom, top"""
  1005. numrows, numcols = self.get_size()
  1006. return (-0.5 + self.ox, numcols-0.5 + self.ox,
  1007. -0.5 + self.oy, numrows-0.5 + self.oy)
  1008. def make_image(self, renderer, magnification=1.0, unsampled=False):
  1009. fac = renderer.dpi/self.figure.dpi
  1010. # fac here is to account for pdf, eps, svg backends where
  1011. # figure.dpi is set to 72. This means we need to scale the
  1012. # image (using magification) and offset it appropriately.
  1013. bbox = Bbox([[self.ox/fac, self.oy/fac],
  1014. [(self.ox/fac + self._A.shape[1]),
  1015. (self.oy/fac + self._A.shape[0])]])
  1016. width, height = self.figure.get_size_inches()
  1017. width *= renderer.dpi
  1018. height *= renderer.dpi
  1019. clip = Bbox([[0, 0], [width, height]])
  1020. return self._make_image(
  1021. self._A, bbox, bbox, clip, magnification=magnification / fac,
  1022. unsampled=unsampled, round_to_pixel_border=False)
  1023. def set_data(self, A):
  1024. """Set the image array."""
  1025. cm.ScalarMappable.set_array(self,
  1026. cbook.safe_masked_invalid(A, copy=True))
  1027. self.stale = True
  1028. class BboxImage(_ImageBase):
  1029. """The Image class whose size is determined by the given bbox."""
  1030. def __init__(self, bbox,
  1031. cmap=None,
  1032. norm=None,
  1033. interpolation=None,
  1034. origin=None,
  1035. filternorm=1,
  1036. filterrad=4.0,
  1037. resample=False,
  1038. interp_at_native=True,
  1039. **kwargs
  1040. ):
  1041. """
  1042. cmap is a colors.Colormap instance
  1043. norm is a colors.Normalize instance to map luminance to 0-1
  1044. interp_at_native is a flag that determines whether or not
  1045. interpolation should still be applied when the image is
  1046. displayed at its native resolution. A common use case for this
  1047. is when displaying an image for annotational purposes; it is
  1048. treated similarly to Photoshop (interpolation is only used when
  1049. displaying the image at non-native resolutions).
  1050. kwargs are an optional list of Artist keyword args
  1051. """
  1052. super().__init__(
  1053. None,
  1054. cmap=cmap,
  1055. norm=norm,
  1056. interpolation=interpolation,
  1057. origin=origin,
  1058. filternorm=filternorm,
  1059. filterrad=filterrad,
  1060. resample=resample,
  1061. **kwargs
  1062. )
  1063. self.bbox = bbox
  1064. self.interp_at_native = interp_at_native
  1065. self._transform = IdentityTransform()
  1066. def get_transform(self):
  1067. return self._transform
  1068. def get_window_extent(self, renderer=None):
  1069. if renderer is None:
  1070. renderer = self.get_figure()._cachedRenderer
  1071. if isinstance(self.bbox, BboxBase):
  1072. return self.bbox
  1073. elif callable(self.bbox):
  1074. return self.bbox(renderer)
  1075. else:
  1076. raise ValueError("unknown type of bbox")
  1077. def contains(self, mouseevent):
  1078. """Test whether the mouse event occurred within the image."""
  1079. if callable(self._contains):
  1080. return self._contains(self, mouseevent)
  1081. if not self.get_visible(): # or self.get_figure()._renderer is None:
  1082. return False, {}
  1083. x, y = mouseevent.x, mouseevent.y
  1084. inside = self.get_window_extent().contains(x, y)
  1085. return inside, {}
  1086. def make_image(self, renderer, magnification=1.0, unsampled=False):
  1087. width, height = renderer.get_canvas_width_height()
  1088. bbox_in = self.get_window_extent(renderer).frozen()
  1089. bbox_in._points /= [width, height]
  1090. bbox_out = self.get_window_extent(renderer)
  1091. clip = Bbox([[0, 0], [width, height]])
  1092. self._transform = BboxTransform(Bbox([[0, 0], [1, 1]]), clip)
  1093. return self._make_image(
  1094. self._A,
  1095. bbox_in, bbox_out, clip, magnification, unsampled=unsampled)
  1096. def imread(fname, format=None):
  1097. """
  1098. Read an image from a file into an array.
  1099. Parameters
  1100. ----------
  1101. fname : str or file-like
  1102. The image file to read. This can be a filename, a URL or a Python
  1103. file-like object opened in read-binary mode.
  1104. format : str, optional
  1105. The image file format assumed for reading the data. If not
  1106. given, the format is deduced from the filename. If nothing can
  1107. be deduced, PNG is tried.
  1108. Returns
  1109. -------
  1110. imagedata : :class:`numpy.array`
  1111. The image data. The returned array has shape
  1112. - (M, N) for grayscale images.
  1113. - (M, N, 3) for RGB images.
  1114. - (M, N, 4) for RGBA images.
  1115. Notes
  1116. -----
  1117. Matplotlib can only read PNGs natively. Further image formats are
  1118. supported via the optional dependency on Pillow. Note, URL strings
  1119. are not compatible with Pillow. Check the `Pillow documentation`_
  1120. for more information.
  1121. .. _Pillow documentation: http://pillow.readthedocs.io/en/latest/
  1122. """
  1123. handlers = {'png': _png.read_png, }
  1124. if format is None:
  1125. if isinstance(fname, str):
  1126. parsed = urllib.parse.urlparse(fname)
  1127. # If the string is a URL, assume png
  1128. if len(parsed.scheme) > 1:
  1129. ext = 'png'
  1130. else:
  1131. basename, ext = os.path.splitext(fname)
  1132. ext = ext.lower()[1:]
  1133. elif hasattr(fname, 'name'):
  1134. basename, ext = os.path.splitext(fname.name)
  1135. ext = ext.lower()[1:]
  1136. else:
  1137. ext = 'png'
  1138. else:
  1139. ext = format
  1140. if ext not in handlers: # Try to load the image with PIL.
  1141. try:
  1142. from PIL import Image
  1143. except ImportError:
  1144. raise ValueError('Only know how to handle extensions: %s; '
  1145. 'with Pillow installed matplotlib can handle '
  1146. 'more images' % list(handlers))
  1147. with Image.open(fname) as image:
  1148. return pil_to_array(image)
  1149. handler = handlers[ext]
  1150. # To handle Unicode filenames, we pass a file object to the PNG
  1151. # reader extension, since Python handles them quite well, but it's
  1152. # tricky in C.
  1153. if isinstance(fname, str):
  1154. parsed = urllib.parse.urlparse(fname)
  1155. # If fname is a URL, download the data
  1156. if len(parsed.scheme) > 1:
  1157. fd = BytesIO(urllib.request.urlopen(fname).read())
  1158. return handler(fd)
  1159. else:
  1160. with open(fname, 'rb') as fd:
  1161. return handler(fd)
  1162. else:
  1163. return handler(fname)
  1164. def imsave(fname, arr, vmin=None, vmax=None, cmap=None, format=None,
  1165. origin=None, dpi=100):
  1166. """
  1167. Save an array as in image file.
  1168. The output formats available depend on the backend being used.
  1169. Parameters
  1170. ----------
  1171. fname : str or file-like
  1172. The filename or a Python file-like object to store the image in.
  1173. The necessary output format is inferred from the filename extension
  1174. but may be explicitly overwritten using *format*.
  1175. arr : array-like
  1176. The image data. The shape can be one of
  1177. MxN (luminance), MxNx3 (RGB) or MxNx4 (RGBA).
  1178. vmin, vmax : scalar, optional
  1179. *vmin* and *vmax* set the color scaling for the image by fixing the
  1180. values that map to the colormap color limits. If either *vmin*
  1181. or *vmax* is None, that limit is determined from the *arr*
  1182. min/max value.
  1183. cmap : str or `~matplotlib.colors.Colormap`, optional
  1184. A Colormap instance or registered colormap name. The colormap
  1185. maps scalar data to colors. It is ignored for RGB(A) data.
  1186. Defaults to :rc:`image.cmap` ('viridis').
  1187. format : str, optional
  1188. The file format, e.g. 'png', 'pdf', 'svg', ... . If not given, the
  1189. format is deduced form the filename extension in *fname*.
  1190. See `.Figure.savefig` for details.
  1191. origin : {'upper', 'lower'}, optional
  1192. Indicates whether the ``(0, 0)`` index of the array is in the upper
  1193. left or lower left corner of the axes. Defaults to :rc:`image.origin`
  1194. ('upper').
  1195. dpi : int
  1196. The DPI to store in the metadata of the file. This does not affect the
  1197. resolution of the output image.
  1198. """
  1199. from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas
  1200. from matplotlib.figure import Figure
  1201. if isinstance(fname, getattr(os, "PathLike", ())):
  1202. fname = os.fspath(fname)
  1203. if (format == 'png'
  1204. or (format is None
  1205. and isinstance(fname, str)
  1206. and fname.lower().endswith('.png'))):
  1207. image = AxesImage(None, cmap=cmap, origin=origin)
  1208. image.set_data(arr)
  1209. image.set_clim(vmin, vmax)
  1210. image.write_png(fname)
  1211. else:
  1212. fig = Figure(dpi=dpi, frameon=False)
  1213. FigureCanvas(fig)
  1214. fig.figimage(arr, cmap=cmap, vmin=vmin, vmax=vmax, origin=origin,
  1215. resize=True)
  1216. fig.savefig(fname, dpi=dpi, format=format, transparent=True)
  1217. def pil_to_array(pilImage):
  1218. """Load a `PIL image`_ and return it as a numpy array.
  1219. .. _PIL image: https://pillow.readthedocs.io/en/latest/reference/Image.html
  1220. Returns
  1221. -------
  1222. numpy.array
  1223. The array shape depends on the image type:
  1224. - (M, N) for grayscale images.
  1225. - (M, N, 3) for RGB images.
  1226. - (M, N, 4) for RGBA images.
  1227. """
  1228. if pilImage.mode in ['RGBA', 'RGBX', 'RGB', 'L']:
  1229. # return MxNx4 RGBA, MxNx3 RBA, or MxN luminance array
  1230. return np.asarray(pilImage)
  1231. elif pilImage.mode.startswith('I;16'):
  1232. # return MxN luminance array of uint16
  1233. raw = pilImage.tobytes('raw', pilImage.mode)
  1234. if pilImage.mode.endswith('B'):
  1235. x = np.fromstring(raw, '>u2')
  1236. else:
  1237. x = np.fromstring(raw, '<u2')
  1238. return x.reshape(pilImage.size[::-1]).astype('=u2')
  1239. else: # try to convert to an rgba image
  1240. try:
  1241. pilImage = pilImage.convert('RGBA')
  1242. except ValueError:
  1243. raise RuntimeError('Unknown image mode')
  1244. return np.asarray(pilImage) # return MxNx4 RGBA array
  1245. def thumbnail(infile, thumbfile, scale=0.1, interpolation='bilinear',
  1246. preview=False):
  1247. """
  1248. Make a thumbnail of image in *infile* with output filename *thumbfile*.
  1249. See :doc:`/gallery/misc/image_thumbnail_sgskip`.
  1250. Parameters
  1251. ----------
  1252. infile : str or file-like
  1253. The image file -- must be PNG, Pillow-readable if you have `Pillow
  1254. <http://python-pillow.org/>`_ installed.
  1255. thumbfile : str or file-like
  1256. The thumbnail filename.
  1257. scale : float, optional
  1258. The scale factor for the thumbnail.
  1259. interpolation : str, optional
  1260. The interpolation scheme used in the resampling. See the
  1261. *interpolation* parameter of `~.Axes.imshow` for possible values.
  1262. preview : bool, optional
  1263. If True, the default backend (presumably a user interface
  1264. backend) will be used which will cause a figure to be raised if
  1265. `~matplotlib.pyplot.show` is called. If it is False, the figure is
  1266. created using `FigureCanvasBase` and the drawing backend is selected
  1267. as `~matplotlib.figure.savefig` would normally do.
  1268. Returns
  1269. -------
  1270. figure : `~.figure.Figure`
  1271. The figure instance containing the thumbnail.
  1272. """
  1273. im = imread(infile)
  1274. rows, cols, depth = im.shape
  1275. # This doesn't really matter (it cancels in the end) but the API needs it.
  1276. dpi = 100
  1277. height = rows / dpi * scale
  1278. width = cols / dpi * scale
  1279. if preview:
  1280. # Let the UI backend do everything.
  1281. import matplotlib.pyplot as plt
  1282. fig = plt.figure(figsize=(width, height), dpi=dpi)
  1283. else:
  1284. from matplotlib.figure import Figure
  1285. fig = Figure(figsize=(width, height), dpi=dpi)
  1286. FigureCanvasBase(fig)
  1287. ax = fig.add_axes([0, 0, 1, 1], aspect='auto',
  1288. frameon=False, xticks=[], yticks=[])
  1289. ax.imshow(im, aspect='auto', resample=True, interpolation=interpolation)
  1290. fig.savefig(thumbfile, dpi=dpi)
  1291. return fig