test_image.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146
  1. from contextlib import ExitStack
  2. from copy import copy
  3. import io
  4. import os
  5. from pathlib import Path
  6. import platform
  7. import sys
  8. import urllib.request
  9. import numpy as np
  10. from numpy.testing import assert_array_equal
  11. from PIL import Image
  12. from matplotlib import (
  13. colors, image as mimage, patches, pyplot as plt, style, rcParams)
  14. from matplotlib.image import (AxesImage, BboxImage, FigureImage,
  15. NonUniformImage, PcolorImage)
  16. from matplotlib.testing.decorators import check_figures_equal, image_comparison
  17. from matplotlib.transforms import Bbox, Affine2D, TransformedBbox
  18. import pytest
  19. @image_comparison(['image_interps'], style='mpl20')
  20. def test_image_interps():
  21. """Make the basic nearest, bilinear and bicubic interps."""
  22. # Remove this line when this test image is regenerated.
  23. plt.rcParams['text.kerning_factor'] = 6
  24. X = np.arange(100)
  25. X = X.reshape(5, 20)
  26. fig = plt.figure()
  27. ax1 = fig.add_subplot(311)
  28. ax1.imshow(X, interpolation='nearest')
  29. ax1.set_title('three interpolations')
  30. ax1.set_ylabel('nearest')
  31. ax2 = fig.add_subplot(312)
  32. ax2.imshow(X, interpolation='bilinear')
  33. ax2.set_ylabel('bilinear')
  34. ax3 = fig.add_subplot(313)
  35. ax3.imshow(X, interpolation='bicubic')
  36. ax3.set_ylabel('bicubic')
  37. @image_comparison(['interp_alpha.png'], remove_text=True)
  38. def test_alpha_interp():
  39. """Test the interpolation of the alpha channel on RGBA images"""
  40. fig, (axl, axr) = plt.subplots(1, 2)
  41. # full green image
  42. img = np.zeros((5, 5, 4))
  43. img[..., 1] = np.ones((5, 5))
  44. # transparent under main diagonal
  45. img[..., 3] = np.tril(np.ones((5, 5), dtype=np.uint8))
  46. axl.imshow(img, interpolation="none")
  47. axr.imshow(img, interpolation="bilinear")
  48. @image_comparison(['interp_nearest_vs_none'],
  49. extensions=['pdf', 'svg'], remove_text=True)
  50. def test_interp_nearest_vs_none():
  51. """Test the effect of "nearest" and "none" interpolation"""
  52. # Setting dpi to something really small makes the difference very
  53. # visible. This works fine with pdf, since the dpi setting doesn't
  54. # affect anything but images, but the agg output becomes unusably
  55. # small.
  56. rcParams['savefig.dpi'] = 3
  57. X = np.array([[[218, 165, 32], [122, 103, 238]],
  58. [[127, 255, 0], [255, 99, 71]]], dtype=np.uint8)
  59. fig = plt.figure()
  60. ax1 = fig.add_subplot(121)
  61. ax1.imshow(X, interpolation='none')
  62. ax1.set_title('interpolation none')
  63. ax2 = fig.add_subplot(122)
  64. ax2.imshow(X, interpolation='nearest')
  65. ax2.set_title('interpolation nearest')
  66. @pytest.mark.parametrize('suppressComposite', [False, True])
  67. @image_comparison(['figimage'], extensions=['png', 'pdf'])
  68. def test_figimage(suppressComposite):
  69. fig = plt.figure(figsize=(2, 2), dpi=100)
  70. fig.suppressComposite = suppressComposite
  71. x, y = np.ix_(np.arange(100) / 100.0, np.arange(100) / 100)
  72. z = np.sin(x**2 + y**2 - x*y)
  73. c = np.sin(20*x**2 + 50*y**2)
  74. img = z + c/5
  75. fig.figimage(img, xo=0, yo=0, origin='lower')
  76. fig.figimage(img[::-1, :], xo=0, yo=100, origin='lower')
  77. fig.figimage(img[:, ::-1], xo=100, yo=0, origin='lower')
  78. fig.figimage(img[::-1, ::-1], xo=100, yo=100, origin='lower')
  79. def test_image_python_io():
  80. fig, ax = plt.subplots()
  81. ax.plot([1, 2, 3])
  82. buffer = io.BytesIO()
  83. fig.savefig(buffer)
  84. buffer.seek(0)
  85. plt.imread(buffer)
  86. @pytest.mark.parametrize(
  87. "img_size, fig_size, interpolation",
  88. [(5, 2, "hanning"), # data larger than figure.
  89. (5, 5, "nearest"), # exact resample.
  90. (5, 10, "nearest"), # double sample.
  91. (3, 2.9, "hanning"), # <3 upsample.
  92. (3, 9.1, "nearest"), # >3 upsample.
  93. ])
  94. @check_figures_equal(extensions=['png'])
  95. def test_imshow_antialiased(fig_test, fig_ref,
  96. img_size, fig_size, interpolation):
  97. np.random.seed(19680801)
  98. dpi = plt.rcParams["savefig.dpi"]
  99. A = np.random.rand(int(dpi * img_size), int(dpi * img_size))
  100. for fig in [fig_test, fig_ref]:
  101. fig.set_size_inches(fig_size, fig_size)
  102. axs = fig_test.subplots()
  103. axs.set_position([0, 0, 1, 1])
  104. axs.imshow(A, interpolation='antialiased')
  105. axs = fig_ref.subplots()
  106. axs.set_position([0, 0, 1, 1])
  107. axs.imshow(A, interpolation=interpolation)
  108. @check_figures_equal(extensions=['png'])
  109. def test_imshow_zoom(fig_test, fig_ref):
  110. # should be less than 3 upsample, so should be nearest...
  111. np.random.seed(19680801)
  112. dpi = plt.rcParams["savefig.dpi"]
  113. A = np.random.rand(int(dpi * 3), int(dpi * 3))
  114. for fig in [fig_test, fig_ref]:
  115. fig.set_size_inches(2.9, 2.9)
  116. axs = fig_test.subplots()
  117. axs.imshow(A, interpolation='antialiased')
  118. axs.set_xlim([10, 20])
  119. axs.set_ylim([10, 20])
  120. axs = fig_ref.subplots()
  121. axs.imshow(A, interpolation='nearest')
  122. axs.set_xlim([10, 20])
  123. axs.set_ylim([10, 20])
  124. @check_figures_equal()
  125. def test_imshow_pil(fig_test, fig_ref):
  126. style.use("default")
  127. png_path = Path(__file__).parent / "baseline_images/pngsuite/basn3p04.png"
  128. tiff_path = Path(__file__).parent / "baseline_images/test_image/uint16.tif"
  129. axs = fig_test.subplots(2)
  130. axs[0].imshow(Image.open(png_path))
  131. axs[1].imshow(Image.open(tiff_path))
  132. axs = fig_ref.subplots(2)
  133. axs[0].imshow(plt.imread(png_path))
  134. axs[1].imshow(plt.imread(tiff_path))
  135. def test_imread_pil_uint16():
  136. img = plt.imread(os.path.join(os.path.dirname(__file__),
  137. 'baseline_images', 'test_image', 'uint16.tif'))
  138. assert img.dtype == np.uint16
  139. assert np.sum(img) == 134184960
  140. def test_imread_fspath():
  141. img = plt.imread(
  142. Path(__file__).parent / 'baseline_images/test_image/uint16.tif')
  143. assert img.dtype == np.uint16
  144. assert np.sum(img) == 134184960
  145. @pytest.mark.parametrize("fmt", ["png", "jpg", "jpeg", "tiff"])
  146. def test_imsave(fmt):
  147. has_alpha = fmt not in ["jpg", "jpeg"]
  148. # The goal here is that the user can specify an output logical DPI
  149. # for the image, but this will not actually add any extra pixels
  150. # to the image, it will merely be used for metadata purposes.
  151. # So we do the traditional case (dpi == 1), and the new case (dpi
  152. # == 100) and read the resulting PNG files back in and make sure
  153. # the data is 100% identical.
  154. np.random.seed(1)
  155. # The height of 1856 pixels was selected because going through creating an
  156. # actual dpi=100 figure to save the image to a Pillow-provided format would
  157. # cause a rounding error resulting in a final image of shape 1855.
  158. data = np.random.rand(1856, 2)
  159. buff_dpi1 = io.BytesIO()
  160. plt.imsave(buff_dpi1, data, format=fmt, dpi=1)
  161. buff_dpi100 = io.BytesIO()
  162. plt.imsave(buff_dpi100, data, format=fmt, dpi=100)
  163. buff_dpi1.seek(0)
  164. arr_dpi1 = plt.imread(buff_dpi1, format=fmt)
  165. buff_dpi100.seek(0)
  166. arr_dpi100 = plt.imread(buff_dpi100, format=fmt)
  167. assert arr_dpi1.shape == (1856, 2, 3 + has_alpha)
  168. assert arr_dpi100.shape == (1856, 2, 3 + has_alpha)
  169. assert_array_equal(arr_dpi1, arr_dpi100)
  170. @pytest.mark.parametrize("fmt", ["png", "pdf", "ps", "eps", "svg"])
  171. def test_imsave_fspath(fmt):
  172. plt.imsave(Path(os.devnull), np.array([[0, 1]]), format=fmt)
  173. def test_imsave_color_alpha():
  174. # Test that imsave accept arrays with ndim=3 where the third dimension is
  175. # color and alpha without raising any exceptions, and that the data is
  176. # acceptably preserved through a save/read roundtrip.
  177. np.random.seed(1)
  178. for origin in ['lower', 'upper']:
  179. data = np.random.rand(16, 16, 4)
  180. buff = io.BytesIO()
  181. plt.imsave(buff, data, origin=origin, format="png")
  182. buff.seek(0)
  183. arr_buf = plt.imread(buff)
  184. # Recreate the float -> uint8 conversion of the data
  185. # We can only expect to be the same with 8 bits of precision,
  186. # since that's what the PNG file used.
  187. data = (255*data).astype('uint8')
  188. if origin == 'lower':
  189. data = data[::-1]
  190. arr_buf = (255*arr_buf).astype('uint8')
  191. assert_array_equal(data, arr_buf)
  192. def test_imsave_pil_kwargs_png():
  193. from PIL.PngImagePlugin import PngInfo
  194. buf = io.BytesIO()
  195. pnginfo = PngInfo()
  196. pnginfo.add_text("Software", "test")
  197. plt.imsave(buf, [[0, 1], [2, 3]],
  198. format="png", pil_kwargs={"pnginfo": pnginfo})
  199. im = Image.open(buf)
  200. assert im.info["Software"] == "test"
  201. def test_imsave_pil_kwargs_tiff():
  202. from PIL.TiffTags import TAGS_V2 as TAGS
  203. buf = io.BytesIO()
  204. pil_kwargs = {"description": "test image"}
  205. plt.imsave(buf, [[0, 1], [2, 3]], format="tiff", pil_kwargs=pil_kwargs)
  206. im = Image.open(buf)
  207. tags = {TAGS[k].name: v for k, v in im.tag_v2.items()}
  208. assert tags["ImageDescription"] == "test image"
  209. @image_comparison(['image_alpha'], remove_text=True)
  210. def test_image_alpha():
  211. plt.figure()
  212. np.random.seed(0)
  213. Z = np.random.rand(6, 6)
  214. plt.subplot(131)
  215. plt.imshow(Z, alpha=1.0, interpolation='none')
  216. plt.subplot(132)
  217. plt.imshow(Z, alpha=0.5, interpolation='none')
  218. plt.subplot(133)
  219. plt.imshow(Z, alpha=0.5, interpolation='nearest')
  220. def test_cursor_data():
  221. from matplotlib.backend_bases import MouseEvent
  222. fig, ax = plt.subplots()
  223. im = ax.imshow(np.arange(100).reshape(10, 10), origin='upper')
  224. x, y = 4, 4
  225. xdisp, ydisp = ax.transData.transform([x, y])
  226. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  227. assert im.get_cursor_data(event) == 44
  228. # Now try for a point outside the image
  229. # Tests issue #4957
  230. x, y = 10.1, 4
  231. xdisp, ydisp = ax.transData.transform([x, y])
  232. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  233. assert im.get_cursor_data(event) is None
  234. # Hmm, something is wrong here... I get 0, not None...
  235. # But, this works further down in the tests with extents flipped
  236. #x, y = 0.1, -0.1
  237. #xdisp, ydisp = ax.transData.transform([x, y])
  238. #event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  239. #z = im.get_cursor_data(event)
  240. #assert z is None, "Did not get None, got %d" % z
  241. ax.clear()
  242. # Now try with the extents flipped.
  243. im = ax.imshow(np.arange(100).reshape(10, 10), origin='lower')
  244. x, y = 4, 4
  245. xdisp, ydisp = ax.transData.transform([x, y])
  246. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  247. assert im.get_cursor_data(event) == 44
  248. fig, ax = plt.subplots()
  249. im = ax.imshow(np.arange(100).reshape(10, 10), extent=[0, 0.5, 0, 0.5])
  250. x, y = 0.25, 0.25
  251. xdisp, ydisp = ax.transData.transform([x, y])
  252. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  253. assert im.get_cursor_data(event) == 55
  254. # Now try for a point outside the image
  255. # Tests issue #4957
  256. x, y = 0.75, 0.25
  257. xdisp, ydisp = ax.transData.transform([x, y])
  258. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  259. assert im.get_cursor_data(event) is None
  260. x, y = 0.01, -0.01
  261. xdisp, ydisp = ax.transData.transform([x, y])
  262. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  263. assert im.get_cursor_data(event) is None
  264. @pytest.mark.parametrize(
  265. "data, text_without_colorbar, text_with_colorbar", [
  266. ([[10001, 10000]], "[1e+04]", "[10001]"),
  267. ([[.123, .987]], "[0.123]", "[0.123]"),
  268. ])
  269. def test_format_cursor_data(data, text_without_colorbar, text_with_colorbar):
  270. from matplotlib.backend_bases import MouseEvent
  271. fig, ax = plt.subplots()
  272. im = ax.imshow(data)
  273. xdisp, ydisp = ax.transData.transform([0, 0])
  274. event = MouseEvent('motion_notify_event', fig.canvas, xdisp, ydisp)
  275. assert im.get_cursor_data(event) == data[0][0]
  276. assert im.format_cursor_data(im.get_cursor_data(event)) \
  277. == text_without_colorbar
  278. fig.colorbar(im)
  279. fig.canvas.draw() # This is necessary to set up the colorbar formatter.
  280. assert im.get_cursor_data(event) == data[0][0]
  281. assert im.format_cursor_data(im.get_cursor_data(event)) \
  282. == text_with_colorbar
  283. @image_comparison(['image_clip'], style='mpl20')
  284. def test_image_clip():
  285. d = [[1, 2], [3, 4]]
  286. fig, ax = plt.subplots()
  287. im = ax.imshow(d)
  288. patch = patches.Circle((0, 0), radius=1, transform=ax.transData)
  289. im.set_clip_path(patch)
  290. @image_comparison(['image_cliprect'], style='mpl20')
  291. def test_image_cliprect():
  292. fig, ax = plt.subplots()
  293. d = [[1, 2], [3, 4]]
  294. im = ax.imshow(d, extent=(0, 5, 0, 5))
  295. rect = patches.Rectangle(
  296. xy=(1, 1), width=2, height=2, transform=im.axes.transData)
  297. im.set_clip_path(rect)
  298. @image_comparison(['imshow'], remove_text=True, style='mpl20')
  299. def test_imshow():
  300. fig, ax = plt.subplots()
  301. arr = np.arange(100).reshape((10, 10))
  302. ax.imshow(arr, interpolation="bilinear", extent=(1, 2, 1, 2))
  303. ax.set_xlim(0, 3)
  304. ax.set_ylim(0, 3)
  305. @check_figures_equal(extensions=['png'])
  306. def test_imshow_10_10_1(fig_test, fig_ref):
  307. # 10x10x1 should be the same as 10x10
  308. arr = np.arange(100).reshape((10, 10, 1))
  309. ax = fig_ref.subplots()
  310. ax.imshow(arr[:, :, 0], interpolation="bilinear", extent=(1, 2, 1, 2))
  311. ax.set_xlim(0, 3)
  312. ax.set_ylim(0, 3)
  313. ax = fig_test.subplots()
  314. ax.imshow(arr, interpolation="bilinear", extent=(1, 2, 1, 2))
  315. ax.set_xlim(0, 3)
  316. ax.set_ylim(0, 3)
  317. def test_imshow_10_10_2():
  318. fig, ax = plt.subplots()
  319. arr = np.arange(200).reshape((10, 10, 2))
  320. with pytest.raises(TypeError):
  321. ax.imshow(arr)
  322. def test_imshow_10_10_5():
  323. fig, ax = plt.subplots()
  324. arr = np.arange(500).reshape((10, 10, 5))
  325. with pytest.raises(TypeError):
  326. ax.imshow(arr)
  327. @image_comparison(['no_interpolation_origin'], remove_text=True)
  328. def test_no_interpolation_origin():
  329. fig, axs = plt.subplots(2)
  330. axs[0].imshow(np.arange(100).reshape((2, 50)), origin="lower",
  331. interpolation='none')
  332. axs[1].imshow(np.arange(100).reshape((2, 50)), interpolation='none')
  333. @image_comparison(['image_shift'], remove_text=True, extensions=['pdf', 'svg'])
  334. def test_image_shift():
  335. imgData = [[1 / x + 1 / y for x in range(1, 100)] for y in range(1, 100)]
  336. tMin = 734717.945208
  337. tMax = 734717.946366
  338. fig, ax = plt.subplots()
  339. ax.imshow(imgData, norm=colors.LogNorm(), interpolation='none',
  340. extent=(tMin, tMax, 1, 100))
  341. ax.set_aspect('auto')
  342. def test_image_edges():
  343. fig = plt.figure(figsize=[1, 1])
  344. ax = fig.add_axes([0, 0, 1, 1], frameon=False)
  345. data = np.tile(np.arange(12), 15).reshape(20, 9)
  346. im = ax.imshow(data, origin='upper', extent=[-10, 10, -10, 10],
  347. interpolation='none', cmap='gray')
  348. x = y = 2
  349. ax.set_xlim([-x, x])
  350. ax.set_ylim([-y, y])
  351. ax.set_xticks([])
  352. ax.set_yticks([])
  353. buf = io.BytesIO()
  354. fig.savefig(buf, facecolor=(0, 1, 0))
  355. buf.seek(0)
  356. im = plt.imread(buf)
  357. r, g, b, a = sum(im[:, 0])
  358. r, g, b, a = sum(im[:, -1])
  359. assert g != 100, 'Expected a non-green edge - but sadly, it was.'
  360. @image_comparison(['image_composite_background'],
  361. remove_text=True, style='mpl20')
  362. def test_image_composite_background():
  363. fig, ax = plt.subplots()
  364. arr = np.arange(12).reshape(4, 3)
  365. ax.imshow(arr, extent=[0, 2, 15, 0])
  366. ax.imshow(arr, extent=[4, 6, 15, 0])
  367. ax.set_facecolor((1, 0, 0, 0.5))
  368. ax.set_xlim([0, 12])
  369. @image_comparison(['image_composite_alpha'], remove_text=True)
  370. def test_image_composite_alpha():
  371. """
  372. Tests that the alpha value is recognized and correctly applied in the
  373. process of compositing images together.
  374. """
  375. fig, ax = plt.subplots()
  376. arr = np.zeros((11, 21, 4))
  377. arr[:, :, 0] = 1
  378. arr[:, :, 3] = np.concatenate(
  379. (np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))
  380. arr2 = np.zeros((21, 11, 4))
  381. arr2[:, :, 0] = 1
  382. arr2[:, :, 1] = 1
  383. arr2[:, :, 3] = np.concatenate(
  384. (np.arange(0, 1.1, 0.1), np.arange(0, 1, 0.1)[::-1]))[:, np.newaxis]
  385. ax.imshow(arr, extent=[1, 2, 5, 0], alpha=0.3)
  386. ax.imshow(arr, extent=[2, 3, 5, 0], alpha=0.6)
  387. ax.imshow(arr, extent=[3, 4, 5, 0])
  388. ax.imshow(arr2, extent=[0, 5, 1, 2])
  389. ax.imshow(arr2, extent=[0, 5, 2, 3], alpha=0.6)
  390. ax.imshow(arr2, extent=[0, 5, 3, 4], alpha=0.3)
  391. ax.set_facecolor((0, 0.5, 0, 1))
  392. ax.set_xlim([0, 5])
  393. ax.set_ylim([5, 0])
  394. @image_comparison(['rasterize_10dpi'],
  395. extensions=['pdf', 'svg'], remove_text=True, style='mpl20')
  396. def test_rasterize_dpi():
  397. # This test should check rasterized rendering with high output resolution.
  398. # It plots a rasterized line and a normal image with imshow. So it will
  399. # catch when images end up in the wrong place in case of non-standard dpi
  400. # setting. Instead of high-res rasterization I use low-res. Therefore
  401. # the fact that the resolution is non-standard is easily checked by
  402. # image_comparison.
  403. img = np.asarray([[1, 2], [3, 4]])
  404. fig, axs = plt.subplots(1, 3, figsize=(3, 1))
  405. axs[0].imshow(img)
  406. axs[1].plot([0, 1], [0, 1], linewidth=20., rasterized=True)
  407. axs[1].set(xlim=(0, 1), ylim=(-1, 2))
  408. axs[2].plot([0, 1], [0, 1], linewidth=20.)
  409. axs[2].set(xlim=(0, 1), ylim=(-1, 2))
  410. # Low-dpi PDF rasterization errors prevent proper image comparison tests.
  411. # Hide detailed structures like the axes spines.
  412. for ax in axs:
  413. ax.set_xticks([])
  414. ax.set_yticks([])
  415. for spine in ax.spines.values():
  416. spine.set_visible(False)
  417. rcParams['savefig.dpi'] = 10
  418. @image_comparison(['bbox_image_inverted'], remove_text=True, style='mpl20')
  419. def test_bbox_image_inverted():
  420. # This is just used to produce an image to feed to BboxImage
  421. image = np.arange(100).reshape((10, 10))
  422. fig, ax = plt.subplots()
  423. bbox_im = BboxImage(
  424. TransformedBbox(Bbox([[100, 100], [0, 0]]), ax.transData),
  425. interpolation='nearest')
  426. bbox_im.set_data(image)
  427. bbox_im.set_clip_on(False)
  428. ax.set_xlim(0, 100)
  429. ax.set_ylim(0, 100)
  430. ax.add_artist(bbox_im)
  431. image = np.identity(10)
  432. bbox_im = BboxImage(TransformedBbox(Bbox([[0.1, 0.2], [0.3, 0.25]]),
  433. ax.figure.transFigure),
  434. interpolation='nearest')
  435. bbox_im.set_data(image)
  436. bbox_im.set_clip_on(False)
  437. ax.add_artist(bbox_im)
  438. def test_get_window_extent_for_AxisImage():
  439. # Create a figure of known size (1000x1000 pixels), place an image
  440. # object at a given location and check that get_window_extent()
  441. # returns the correct bounding box values (in pixels).
  442. im = np.array([[0.25, 0.75, 1.0, 0.75], [0.1, 0.65, 0.5, 0.4],
  443. [0.6, 0.3, 0.0, 0.2], [0.7, 0.9, 0.4, 0.6]])
  444. fig, ax = plt.subplots(figsize=(10, 10), dpi=100)
  445. ax.set_position([0, 0, 1, 1])
  446. ax.set_xlim(0, 1)
  447. ax.set_ylim(0, 1)
  448. im_obj = ax.imshow(
  449. im, extent=[0.4, 0.7, 0.2, 0.9], interpolation='nearest')
  450. fig.canvas.draw()
  451. renderer = fig.canvas.renderer
  452. im_bbox = im_obj.get_window_extent(renderer)
  453. assert_array_equal(im_bbox.get_points(), [[400, 200], [700, 900]])
  454. @image_comparison(['zoom_and_clip_upper_origin.png'],
  455. remove_text=True, style='mpl20')
  456. def test_zoom_and_clip_upper_origin():
  457. image = np.arange(100)
  458. image = image.reshape((10, 10))
  459. fig, ax = plt.subplots()
  460. ax.imshow(image)
  461. ax.set_ylim(2.0, -0.5)
  462. ax.set_xlim(-0.5, 2.0)
  463. def test_nonuniformimage_setcmap():
  464. ax = plt.gca()
  465. im = NonUniformImage(ax)
  466. im.set_cmap('Blues')
  467. def test_nonuniformimage_setnorm():
  468. ax = plt.gca()
  469. im = NonUniformImage(ax)
  470. im.set_norm(plt.Normalize())
  471. def test_jpeg_2d():
  472. # smoke test that mode-L pillow images work.
  473. imd = np.ones((10, 10), dtype='uint8')
  474. for i in range(10):
  475. imd[i, :] = np.linspace(0.0, 1.0, 10) * 255
  476. im = Image.new('L', (10, 10))
  477. im.putdata(imd.flatten())
  478. fig, ax = plt.subplots()
  479. ax.imshow(im)
  480. def test_jpeg_alpha():
  481. plt.figure(figsize=(1, 1), dpi=300)
  482. # Create an image that is all black, with a gradient from 0-1 in
  483. # the alpha channel from left to right.
  484. im = np.zeros((300, 300, 4), dtype=float)
  485. im[..., 3] = np.linspace(0.0, 1.0, 300)
  486. plt.figimage(im)
  487. buff = io.BytesIO()
  488. plt.savefig(buff, facecolor="red", format='jpg', dpi=300)
  489. buff.seek(0)
  490. image = Image.open(buff)
  491. # If this fails, there will be only one color (all black). If this
  492. # is working, we should have all 256 shades of grey represented.
  493. num_colors = len(image.getcolors(256))
  494. assert 175 <= num_colors <= 185
  495. # The fully transparent part should be red.
  496. corner_pixel = image.getpixel((0, 0))
  497. assert corner_pixel == (254, 0, 0)
  498. def test_axesimage_setdata():
  499. ax = plt.gca()
  500. im = AxesImage(ax)
  501. z = np.arange(12, dtype=float).reshape((4, 3))
  502. im.set_data(z)
  503. z[0, 0] = 9.9
  504. assert im._A[0, 0] == 0, 'value changed'
  505. def test_figureimage_setdata():
  506. fig = plt.gcf()
  507. im = FigureImage(fig)
  508. z = np.arange(12, dtype=float).reshape((4, 3))
  509. im.set_data(z)
  510. z[0, 0] = 9.9
  511. assert im._A[0, 0] == 0, 'value changed'
  512. @pytest.mark.parametrize(
  513. "image_cls,x,y,a", [
  514. (NonUniformImage,
  515. np.arange(3.), np.arange(4.), np.arange(12.).reshape((4, 3))),
  516. (PcolorImage,
  517. np.arange(3.), np.arange(4.), np.arange(6.).reshape((3, 2))),
  518. ])
  519. def test_setdata_xya(image_cls, x, y, a):
  520. ax = plt.gca()
  521. im = image_cls(ax)
  522. im.set_data(x, y, a)
  523. x[0] = y[0] = a[0, 0] = 9.9
  524. assert im._A[0, 0] == im._Ax[0] == im._Ay[0] == 0, 'value changed'
  525. im.set_data(x, y, a.reshape((*a.shape, -1))) # Just a smoketest.
  526. def test_minimized_rasterized():
  527. # This ensures that the rasterized content in the colorbars is
  528. # only as thick as the colorbar, and doesn't extend to other parts
  529. # of the image. See #5814. While the original bug exists only
  530. # in Postscript, the best way to detect it is to generate SVG
  531. # and then parse the output to make sure the two colorbar images
  532. # are the same size.
  533. from xml.etree import ElementTree
  534. np.random.seed(0)
  535. data = np.random.rand(10, 10)
  536. fig, ax = plt.subplots(1, 2)
  537. p1 = ax[0].pcolormesh(data)
  538. p2 = ax[1].pcolormesh(data)
  539. plt.colorbar(p1, ax=ax[0])
  540. plt.colorbar(p2, ax=ax[1])
  541. buff = io.BytesIO()
  542. plt.savefig(buff, format='svg')
  543. buff = io.BytesIO(buff.getvalue())
  544. tree = ElementTree.parse(buff)
  545. width = None
  546. for image in tree.iter('image'):
  547. if width is None:
  548. width = image['width']
  549. else:
  550. if image['width'] != width:
  551. assert False
  552. def test_load_from_url():
  553. path = Path(__file__).parent / "baseline_images/test_image/imshow.png"
  554. url = ('file:'
  555. + ('///' if sys.platform == 'win32' else '')
  556. + path.resolve().as_posix())
  557. plt.imread(url)
  558. plt.imread(urllib.request.urlopen(url))
  559. @image_comparison(['log_scale_image'], remove_text=True)
  560. def test_log_scale_image():
  561. Z = np.zeros((10, 10))
  562. Z[::2] = 1
  563. fig, ax = plt.subplots()
  564. ax.imshow(Z, extent=[1, 100, 1, 100], cmap='viridis', vmax=1, vmin=-1,
  565. aspect='auto')
  566. ax.set(yscale='log')
  567. @image_comparison(['rotate_image'], remove_text=True)
  568. def test_rotate_image():
  569. delta = 0.25
  570. x = y = np.arange(-3.0, 3.0, delta)
  571. X, Y = np.meshgrid(x, y)
  572. Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)
  573. Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /
  574. (2 * np.pi * 0.5 * 1.5))
  575. Z = Z2 - Z1 # difference of Gaussians
  576. fig, ax1 = plt.subplots(1, 1)
  577. im1 = ax1.imshow(Z, interpolation='none', cmap='viridis',
  578. origin='lower',
  579. extent=[-2, 4, -3, 2], clip_on=True)
  580. trans_data2 = Affine2D().rotate_deg(30) + ax1.transData
  581. im1.set_transform(trans_data2)
  582. # display intended extent of the image
  583. x1, x2, y1, y2 = im1.get_extent()
  584. ax1.plot([x1, x2, x2, x1, x1], [y1, y1, y2, y2, y1], "r--", lw=3,
  585. transform=trans_data2)
  586. ax1.set_xlim(2, 5)
  587. ax1.set_ylim(0, 4)
  588. def test_image_preserve_size():
  589. buff = io.BytesIO()
  590. im = np.zeros((481, 321))
  591. plt.imsave(buff, im, format="png")
  592. buff.seek(0)
  593. img = plt.imread(buff)
  594. assert img.shape[:2] == im.shape
  595. def test_image_preserve_size2():
  596. n = 7
  597. data = np.identity(n, float)
  598. fig = plt.figure(figsize=(n, n), frameon=False)
  599. ax = plt.Axes(fig, [0.0, 0.0, 1.0, 1.0])
  600. ax.set_axis_off()
  601. fig.add_axes(ax)
  602. ax.imshow(data, interpolation='nearest', origin='lower', aspect='auto')
  603. buff = io.BytesIO()
  604. fig.savefig(buff, dpi=1)
  605. buff.seek(0)
  606. img = plt.imread(buff)
  607. assert img.shape == (7, 7, 4)
  608. assert_array_equal(np.asarray(img[:, :, 0], bool),
  609. np.identity(n, bool)[::-1])
  610. @image_comparison(['mask_image_over_under.png'], remove_text=True)
  611. def test_mask_image_over_under():
  612. delta = 0.025
  613. x = y = np.arange(-3.0, 3.0, delta)
  614. X, Y = np.meshgrid(x, y)
  615. Z1 = np.exp(-(X**2 + Y**2) / 2) / (2 * np.pi)
  616. Z2 = (np.exp(-(((X - 1) / 1.5)**2 + ((Y - 1) / 0.5)**2) / 2) /
  617. (2 * np.pi * 0.5 * 1.5))
  618. Z = 10*(Z2 - Z1) # difference of Gaussians
  619. palette = copy(plt.cm.gray)
  620. palette.set_over('r', 1.0)
  621. palette.set_under('g', 1.0)
  622. palette.set_bad('b', 1.0)
  623. Zm = np.ma.masked_where(Z > 1.2, Z)
  624. fig, (ax1, ax2) = plt.subplots(1, 2)
  625. im = ax1.imshow(Zm, interpolation='bilinear',
  626. cmap=palette,
  627. norm=colors.Normalize(vmin=-1.0, vmax=1.0, clip=False),
  628. origin='lower', extent=[-3, 3, -3, 3])
  629. ax1.set_title('Green=low, Red=high, Blue=bad')
  630. fig.colorbar(im, extend='both', orientation='horizontal',
  631. ax=ax1, aspect=10)
  632. im = ax2.imshow(Zm, interpolation='nearest',
  633. cmap=palette,
  634. norm=colors.BoundaryNorm([-1, -0.5, -0.2, 0, 0.2, 0.5, 1],
  635. ncolors=256, clip=False),
  636. origin='lower', extent=[-3, 3, -3, 3])
  637. ax2.set_title('With BoundaryNorm')
  638. fig.colorbar(im, extend='both', spacing='proportional',
  639. orientation='horizontal', ax=ax2, aspect=10)
  640. @image_comparison(['mask_image'], remove_text=True)
  641. def test_mask_image():
  642. # Test mask image two ways: Using nans and using a masked array.
  643. fig, (ax1, ax2) = plt.subplots(1, 2)
  644. A = np.ones((5, 5))
  645. A[1:2, 1:2] = np.nan
  646. ax1.imshow(A, interpolation='nearest')
  647. A = np.zeros((5, 5), dtype=bool)
  648. A[1:2, 1:2] = True
  649. A = np.ma.masked_array(np.ones((5, 5), dtype=np.uint16), A)
  650. ax2.imshow(A, interpolation='nearest')
  651. def test_mask_image_all():
  652. # Test behavior with an image that is entirely masked does not warn
  653. data = np.full((2, 2), np.nan)
  654. fig, ax = plt.subplots()
  655. ax.imshow(data)
  656. fig.canvas.draw_idle() # would emit a warning
  657. @image_comparison(['imshow_endianess.png'], remove_text=True)
  658. def test_imshow_endianess():
  659. x = np.arange(10)
  660. X, Y = np.meshgrid(x, x)
  661. Z = np.hypot(X - 5, Y - 5)
  662. fig, (ax1, ax2) = plt.subplots(1, 2)
  663. kwargs = dict(origin="lower", interpolation='nearest', cmap='viridis')
  664. ax1.imshow(Z.astype('<f8'), **kwargs)
  665. ax2.imshow(Z.astype('>f8'), **kwargs)
  666. @image_comparison(['imshow_masked_interpolation'],
  667. tol=0 if platform.machine() == 'x86_64' else 0.01,
  668. remove_text=True, style='mpl20')
  669. def test_imshow_masked_interpolation():
  670. cm = copy(plt.get_cmap('viridis'))
  671. cm.set_over('r')
  672. cm.set_under('b')
  673. cm.set_bad('k')
  674. N = 20
  675. n = colors.Normalize(vmin=0, vmax=N*N-1)
  676. data = np.arange(N*N, dtype=float).reshape(N, N)
  677. data[5, 5] = -1
  678. # This will cause crazy ringing for the higher-order
  679. # interpolations
  680. data[15, 5] = 1e5
  681. # data[3, 3] = np.nan
  682. data[15, 15] = np.inf
  683. mask = np.zeros_like(data).astype('bool')
  684. mask[5, 15] = True
  685. data = np.ma.masked_array(data, mask)
  686. fig, ax_grid = plt.subplots(3, 6)
  687. interps = sorted(mimage._interpd_)
  688. interps.remove('antialiased')
  689. for interp, ax in zip(interps, ax_grid.ravel()):
  690. ax.set_title(interp)
  691. ax.imshow(data, norm=n, cmap=cm, interpolation=interp)
  692. ax.axis('off')
  693. def test_imshow_no_warn_invalid():
  694. plt.imshow([[1, 2], [3, np.nan]]) # Check that no warning is emitted.
  695. @pytest.mark.parametrize(
  696. 'dtype', [np.dtype(s) for s in 'u2 u4 i2 i4 i8 f4 f8'.split()])
  697. def test_imshow_clips_rgb_to_valid_range(dtype):
  698. arr = np.arange(300, dtype=dtype).reshape((10, 10, 3))
  699. if dtype.kind != 'u':
  700. arr -= 10
  701. too_low = arr < 0
  702. too_high = arr > 255
  703. if dtype.kind == 'f':
  704. arr = arr / 255
  705. _, ax = plt.subplots()
  706. out = ax.imshow(arr).get_array()
  707. assert (out[too_low] == 0).all()
  708. if dtype.kind == 'f':
  709. assert (out[too_high] == 1).all()
  710. assert out.dtype.kind == 'f'
  711. else:
  712. assert (out[too_high] == 255).all()
  713. assert out.dtype == np.uint8
  714. @image_comparison(['imshow_flatfield.png'], remove_text=True, style='mpl20')
  715. def test_imshow_flatfield():
  716. fig, ax = plt.subplots()
  717. im = ax.imshow(np.ones((5, 5)), interpolation='nearest')
  718. im.set_clim(.5, 1.5)
  719. @image_comparison(['imshow_bignumbers.png'], remove_text=True, style='mpl20')
  720. def test_imshow_bignumbers():
  721. rcParams['image.interpolation'] = 'nearest'
  722. # putting a big number in an array of integers shouldn't
  723. # ruin the dynamic range of the resolved bits.
  724. fig, ax = plt.subplots()
  725. img = np.array([[1, 2, 1e12], [3, 1, 4]], dtype=np.uint64)
  726. pc = ax.imshow(img)
  727. pc.set_clim(0, 5)
  728. @image_comparison(['imshow_bignumbers_real.png'],
  729. remove_text=True, style='mpl20')
  730. def test_imshow_bignumbers_real():
  731. rcParams['image.interpolation'] = 'nearest'
  732. # putting a big number in an array of integers shouldn't
  733. # ruin the dynamic range of the resolved bits.
  734. fig, ax = plt.subplots()
  735. img = np.array([[2., 1., 1.e22], [4., 1., 3.]])
  736. pc = ax.imshow(img)
  737. pc.set_clim(0, 5)
  738. @pytest.mark.parametrize(
  739. "make_norm",
  740. [colors.Normalize,
  741. colors.LogNorm,
  742. lambda: colors.SymLogNorm(1),
  743. lambda: colors.PowerNorm(1)])
  744. def test_empty_imshow(make_norm):
  745. fig, ax = plt.subplots()
  746. with pytest.warns(UserWarning,
  747. match="Attempting to set identical left == right"):
  748. im = ax.imshow([[]], norm=make_norm())
  749. im.set_extent([-5, 5, -5, 5])
  750. fig.canvas.draw()
  751. with pytest.raises(RuntimeError):
  752. im.make_image(fig._cachedRenderer)
  753. def test_imshow_float128():
  754. fig, ax = plt.subplots()
  755. ax.imshow(np.zeros((3, 3), dtype=np.longdouble))
  756. with (ExitStack() if np.can_cast(np.longdouble, np.float64, "equiv")
  757. else pytest.warns(UserWarning)):
  758. # Ensure that drawing doesn't cause crash.
  759. fig.canvas.draw()
  760. def test_imshow_bool():
  761. fig, ax = plt.subplots()
  762. ax.imshow(np.array([[True, False], [False, True]], dtype=bool))
  763. def test_full_invalid():
  764. fig, ax = plt.subplots()
  765. ax.imshow(np.full((10, 10), np.nan))
  766. with pytest.warns(UserWarning):
  767. fig.canvas.draw()
  768. @pytest.mark.parametrize("fmt,counted",
  769. [("ps", b" colorimage"), ("svg", b"<image")])
  770. @pytest.mark.parametrize("composite_image,count", [(True, 1), (False, 2)])
  771. def test_composite(fmt, counted, composite_image, count):
  772. # Test that figures can be saved with and without combining multiple images
  773. # (on a single set of axes) into a single composite image.
  774. X, Y = np.meshgrid(np.arange(-5, 5, 1), np.arange(-5, 5, 1))
  775. Z = np.sin(Y ** 2)
  776. fig, ax = plt.subplots()
  777. ax.set_xlim(0, 3)
  778. ax.imshow(Z, extent=[0, 1, 0, 1])
  779. ax.imshow(Z[::-1], extent=[2, 3, 0, 1])
  780. plt.rcParams['image.composite_image'] = composite_image
  781. buf = io.BytesIO()
  782. fig.savefig(buf, format=fmt)
  783. assert buf.getvalue().count(counted) == count
  784. def test_relim():
  785. fig, ax = plt.subplots()
  786. ax.imshow([[0]], extent=(0, 1, 0, 1))
  787. ax.relim()
  788. ax.autoscale()
  789. assert ax.get_xlim() == ax.get_ylim() == (0, 1)
  790. def test_unclipped():
  791. fig, ax = plt.subplots()
  792. ax.set_axis_off()
  793. im = ax.imshow([[0, 0], [0, 0]], aspect="auto", extent=(-10, 10, -10, 10),
  794. cmap='gray', clip_on=False)
  795. ax.set(xlim=(0, 1), ylim=(0, 1))
  796. fig.canvas.draw()
  797. # The unclipped image should fill the *entire* figure and be black.
  798. # Ignore alpha for this comparison.
  799. assert (np.array(fig.canvas.buffer_rgba())[..., :3] == 0).all()
  800. def test_respects_bbox():
  801. fig, axs = plt.subplots(2)
  802. for ax in axs:
  803. ax.set_axis_off()
  804. im = axs[1].imshow([[0, 1], [2, 3]], aspect="auto", extent=(0, 1, 0, 1))
  805. im.set_clip_path(None)
  806. # Make the image invisible in axs[1], but visible in axs[0] if we pan
  807. # axs[1] up.
  808. im.set_clip_box(axs[0].bbox)
  809. buf_before = io.BytesIO()
  810. fig.savefig(buf_before, format="rgba")
  811. assert {*buf_before.getvalue()} == {0xff} # All white.
  812. axs[1].set(ylim=(-1, 0))
  813. buf_after = io.BytesIO()
  814. fig.savefig(buf_after, format="rgba")
  815. assert buf_before.getvalue() != buf_after.getvalue() # Not all white.
  816. def test_image_cursor_formatting():
  817. fig, ax = plt.subplots()
  818. # Create a dummy image to be able to call format_cursor_data
  819. im = ax.imshow(np.zeros((4, 4)))
  820. data = np.ma.masked_array([0], mask=[True])
  821. assert im.format_cursor_data(data) == '[]'
  822. data = np.ma.masked_array([0], mask=[False])
  823. assert im.format_cursor_data(data) == '[0]'
  824. data = np.nan
  825. assert im.format_cursor_data(data) == '[nan]'
  826. @check_figures_equal()
  827. def test_image_array_alpha(fig_test, fig_ref):
  828. """Per-pixel alpha channel test."""
  829. x = np.linspace(0, 1)
  830. xx, yy = np.meshgrid(x, x)
  831. zz = np.exp(- 3 * ((xx - 0.5) ** 2) + (yy - 0.7 ** 2))
  832. alpha = zz / zz.max()
  833. cmap = plt.get_cmap('viridis')
  834. ax = fig_test.add_subplot(111)
  835. ax.imshow(zz, alpha=alpha, cmap=cmap, interpolation='nearest')
  836. ax = fig_ref.add_subplot(111)
  837. rgba = cmap(colors.Normalize()(zz))
  838. rgba[..., -1] = alpha
  839. ax.imshow(rgba, interpolation='nearest')
  840. @pytest.mark.style('mpl20')
  841. def test_exact_vmin():
  842. cmap = copy(plt.cm.get_cmap("autumn_r"))
  843. cmap.set_under(color="lightgrey")
  844. # make the image exactly 190 pixels wide
  845. fig = plt.figure(figsize=(1.9, 0.1), dpi=100)
  846. ax = fig.add_axes([0, 0, 1, 1])
  847. data = np.array(
  848. [[-1, -1, -1, 0, 0, 0, 0, 43, 79, 95, 66, 1, -1, -1, -1, 0, 0, 0, 34]],
  849. dtype=float,
  850. )
  851. im = ax.imshow(data, aspect="auto", cmap=cmap, vmin=0, vmax=100)
  852. ax.axis("off")
  853. fig.canvas.draw()
  854. # get the RGBA slice from the image
  855. from_image = im.make_image(fig.canvas.renderer)[0][0]
  856. # expand the input to be 190 long and run through norm / cmap
  857. direct_computation = (
  858. im.cmap(im.norm((data * ([[1]] * 10)).T.ravel())) * 255
  859. ).astype(int)
  860. # check than the RBGA values are the same
  861. assert np.all(from_image == direct_computation)
  862. @pytest.mark.network
  863. @pytest.mark.flaky
  864. def test_https_imread_smoketest():
  865. v = mimage.imread('https://matplotlib.org/1.5.0/_static/logo2.png')
  866. @check_figures_equal(extensions=['png'])
  867. def test_huge_range_log(fig_test, fig_ref):
  868. data = np.full((5, 5), -1, dtype=np.float64)
  869. data[0:2, :] = 1E20
  870. ax = fig_test.subplots()
  871. im = ax.imshow(data, norm=colors.LogNorm(vmin=100, vmax=data.max()),
  872. interpolation='nearest', cmap='viridis')
  873. data = np.full((5, 5), -1, dtype=np.float64)
  874. data[0:2, :] = 1000
  875. cm = copy(plt.get_cmap('viridis'))
  876. cm.set_under('w')
  877. ax = fig_ref.subplots()
  878. im = ax.imshow(data, norm=colors.Normalize(vmin=100, vmax=data.max()),
  879. interpolation='nearest', cmap=cm)