test_agg.py 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246
  1. import io
  2. import numpy as np
  3. from numpy.testing import assert_array_almost_equal
  4. from PIL import Image, TiffTags
  5. import pytest
  6. from matplotlib import (
  7. collections, path, pyplot as plt, transforms as mtransforms, rcParams)
  8. from matplotlib.image import imread
  9. from matplotlib.figure import Figure
  10. from matplotlib.testing.decorators import image_comparison
  11. def test_repeated_save_with_alpha():
  12. # We want an image which has a background color of bluish green, with an
  13. # alpha of 0.25.
  14. fig = Figure([1, 0.4])
  15. fig.set_facecolor((0, 1, 0.4))
  16. fig.patch.set_alpha(0.25)
  17. # The target color is fig.patch.get_facecolor()
  18. buf = io.BytesIO()
  19. fig.savefig(buf,
  20. facecolor=fig.get_facecolor(),
  21. edgecolor='none')
  22. # Save the figure again to check that the
  23. # colors don't bleed from the previous renderer.
  24. buf.seek(0)
  25. fig.savefig(buf,
  26. facecolor=fig.get_facecolor(),
  27. edgecolor='none')
  28. # Check the first pixel has the desired color & alpha
  29. # (approx: 0, 1.0, 0.4, 0.25)
  30. buf.seek(0)
  31. assert_array_almost_equal(tuple(imread(buf)[0, 0]),
  32. (0.0, 1.0, 0.4, 0.250),
  33. decimal=3)
  34. def test_large_single_path_collection():
  35. buff = io.BytesIO()
  36. # Generates a too-large single path in a path collection that
  37. # would cause a segfault if the draw_markers optimization is
  38. # applied.
  39. f, ax = plt.subplots()
  40. collection = collections.PathCollection(
  41. [path.Path([[-10, 5], [10, 5], [10, -5], [-10, -5], [-10, 5]])])
  42. ax.add_artist(collection)
  43. ax.set_xlim(10**-3, 1)
  44. plt.savefig(buff)
  45. def test_marker_with_nan():
  46. # This creates a marker with nans in it, which was segfaulting the
  47. # Agg backend (see #3722)
  48. fig, ax = plt.subplots(1)
  49. steps = 1000
  50. data = np.arange(steps)
  51. ax.semilogx(data)
  52. ax.fill_between(data, data*0.8, data*1.2)
  53. buf = io.BytesIO()
  54. fig.savefig(buf, format='png')
  55. def test_long_path():
  56. buff = io.BytesIO()
  57. fig, ax = plt.subplots()
  58. np.random.seed(0)
  59. points = np.random.rand(70000)
  60. ax.plot(points)
  61. fig.savefig(buff, format='png')
  62. @image_comparison(['agg_filter.png'], remove_text=True)
  63. def test_agg_filter():
  64. def smooth1d(x, window_len):
  65. # copied from http://www.scipy.org/Cookbook/SignalSmooth
  66. s = np.r_[
  67. 2*x[0] - x[window_len:1:-1], x, 2*x[-1] - x[-1:-window_len:-1]]
  68. w = np.hanning(window_len)
  69. y = np.convolve(w/w.sum(), s, mode='same')
  70. return y[window_len-1:-window_len+1]
  71. def smooth2d(A, sigma=3):
  72. window_len = max(int(sigma), 3) * 2 + 1
  73. A = np.apply_along_axis(smooth1d, 0, A, window_len)
  74. A = np.apply_along_axis(smooth1d, 1, A, window_len)
  75. return A
  76. class BaseFilter:
  77. def get_pad(self, dpi):
  78. return 0
  79. def process_image(self, padded_src, dpi):
  80. raise NotImplementedError("Should be overridden by subclasses")
  81. def __call__(self, im, dpi):
  82. pad = self.get_pad(dpi)
  83. padded_src = np.pad(im, [(pad, pad), (pad, pad), (0, 0)],
  84. "constant")
  85. tgt_image = self.process_image(padded_src, dpi)
  86. return tgt_image, -pad, -pad
  87. class OffsetFilter(BaseFilter):
  88. def __init__(self, offsets=(0, 0)):
  89. self.offsets = offsets
  90. def get_pad(self, dpi):
  91. return int(max(self.offsets) / 72 * dpi)
  92. def process_image(self, padded_src, dpi):
  93. ox, oy = self.offsets
  94. a1 = np.roll(padded_src, int(ox / 72 * dpi), axis=1)
  95. a2 = np.roll(a1, -int(oy / 72 * dpi), axis=0)
  96. return a2
  97. class GaussianFilter(BaseFilter):
  98. """Simple Gaussian filter."""
  99. def __init__(self, sigma, alpha=0.5, color=(0, 0, 0)):
  100. self.sigma = sigma
  101. self.alpha = alpha
  102. self.color = color
  103. def get_pad(self, dpi):
  104. return int(self.sigma*3 / 72 * dpi)
  105. def process_image(self, padded_src, dpi):
  106. tgt_image = np.empty_like(padded_src)
  107. tgt_image[:, :, :3] = self.color
  108. tgt_image[:, :, 3] = smooth2d(padded_src[:, :, 3] * self.alpha,
  109. self.sigma / 72 * dpi)
  110. return tgt_image
  111. class DropShadowFilter(BaseFilter):
  112. def __init__(self, sigma, alpha=0.3, color=(0, 0, 0), offsets=(0, 0)):
  113. self.gauss_filter = GaussianFilter(sigma, alpha, color)
  114. self.offset_filter = OffsetFilter(offsets)
  115. def get_pad(self, dpi):
  116. return max(self.gauss_filter.get_pad(dpi),
  117. self.offset_filter.get_pad(dpi))
  118. def process_image(self, padded_src, dpi):
  119. t1 = self.gauss_filter.process_image(padded_src, dpi)
  120. t2 = self.offset_filter.process_image(t1, dpi)
  121. return t2
  122. fig, ax = plt.subplots()
  123. # draw lines
  124. l1, = ax.plot([0.1, 0.5, 0.9], [0.1, 0.9, 0.5], "bo-",
  125. mec="b", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
  126. l2, = ax.plot([0.1, 0.5, 0.9], [0.5, 0.2, 0.7], "ro-",
  127. mec="r", mfc="w", lw=5, mew=3, ms=10, label="Line 1")
  128. gauss = DropShadowFilter(4)
  129. for l in [l1, l2]:
  130. # draw shadows with same lines with slight offset.
  131. xx = l.get_xdata()
  132. yy = l.get_ydata()
  133. shadow, = ax.plot(xx, yy)
  134. shadow.update_from(l)
  135. # offset transform
  136. ot = mtransforms.offset_copy(l.get_transform(), ax.figure,
  137. x=4.0, y=-6.0, units='points')
  138. shadow.set_transform(ot)
  139. # adjust zorder of the shadow lines so that it is drawn below the
  140. # original lines
  141. shadow.set_zorder(l.get_zorder() - 0.5)
  142. shadow.set_agg_filter(gauss)
  143. shadow.set_rasterized(True) # to support mixed-mode renderers
  144. ax.set_xlim(0., 1.)
  145. ax.set_ylim(0., 1.)
  146. ax.xaxis.set_visible(False)
  147. ax.yaxis.set_visible(False)
  148. def test_too_large_image():
  149. fig = plt.figure(figsize=(300, 1000))
  150. buff = io.BytesIO()
  151. with pytest.raises(ValueError):
  152. fig.savefig(buff)
  153. def test_chunksize():
  154. x = range(200)
  155. # Test without chunksize
  156. fig, ax = plt.subplots()
  157. ax.plot(x, np.sin(x))
  158. fig.canvas.draw()
  159. # Test with chunksize
  160. fig, ax = plt.subplots()
  161. rcParams['agg.path.chunksize'] = 105
  162. ax.plot(x, np.sin(x))
  163. fig.canvas.draw()
  164. @pytest.mark.backend('Agg')
  165. def test_jpeg_dpi():
  166. # Check that dpi is set correctly in jpg files.
  167. plt.plot([0, 1, 2], [0, 1, 0])
  168. buf = io.BytesIO()
  169. plt.savefig(buf, format="jpg", dpi=200)
  170. im = Image.open(buf)
  171. assert im.info['dpi'] == (200, 200)
  172. def test_pil_kwargs_png():
  173. from PIL.PngImagePlugin import PngInfo
  174. buf = io.BytesIO()
  175. pnginfo = PngInfo()
  176. pnginfo.add_text("Software", "test")
  177. plt.figure().savefig(buf, format="png", pil_kwargs={"pnginfo": pnginfo})
  178. im = Image.open(buf)
  179. assert im.info["Software"] == "test"
  180. def test_pil_kwargs_tiff():
  181. buf = io.BytesIO()
  182. pil_kwargs = {"description": "test image"}
  183. plt.figure().savefig(buf, format="tiff", pil_kwargs=pil_kwargs)
  184. im = Image.open(buf)
  185. tags = {TiffTags.TAGS_V2[k].name: v for k, v in im.tag_v2.items()}
  186. assert tags["ImageDescription"] == "test image"