compare.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515
  1. """
  2. Utilities for comparing image results.
  3. """
  4. import atexit
  5. import functools
  6. import hashlib
  7. import logging
  8. import os
  9. from pathlib import Path
  10. import shutil
  11. import subprocess
  12. import sys
  13. from tempfile import TemporaryDirectory, TemporaryFile
  14. import weakref
  15. import numpy as np
  16. from PIL import Image
  17. import matplotlib as mpl
  18. from matplotlib import cbook
  19. from matplotlib.testing.exceptions import ImageComparisonFailure
  20. _log = logging.getLogger(__name__)
  21. __all__ = ['calculate_rms', 'comparable_formats', 'compare_images']
  22. def make_test_filename(fname, purpose):
  23. """
  24. Make a new filename by inserting *purpose* before the file's extension.
  25. """
  26. base, ext = os.path.splitext(fname)
  27. return f'{base}-{purpose}{ext}'
  28. def _get_cache_path():
  29. cache_dir = Path(mpl.get_cachedir(), 'test_cache')
  30. cache_dir.mkdir(parents=True, exist_ok=True)
  31. return cache_dir
  32. def get_cache_dir():
  33. return str(_get_cache_path())
  34. def get_file_hash(path, block_size=2 ** 20):
  35. md5 = hashlib.md5()
  36. with open(path, 'rb') as fd:
  37. while True:
  38. data = fd.read(block_size)
  39. if not data:
  40. break
  41. md5.update(data)
  42. if Path(path).suffix == '.pdf':
  43. md5.update(str(mpl._get_executable_info("gs").version)
  44. .encode('utf-8'))
  45. elif Path(path).suffix == '.svg':
  46. md5.update(str(mpl._get_executable_info("inkscape").version)
  47. .encode('utf-8'))
  48. return md5.hexdigest()
  49. class _ConverterError(Exception):
  50. pass
  51. class _Converter:
  52. def __init__(self):
  53. self._proc = None
  54. # Explicitly register deletion from an atexit handler because if we
  55. # wait until the object is GC'd (which occurs later), then some module
  56. # globals (e.g. signal.SIGKILL) has already been set to None, and
  57. # kill() doesn't work anymore...
  58. atexit.register(self.__del__)
  59. def __del__(self):
  60. if self._proc:
  61. self._proc.kill()
  62. self._proc.wait()
  63. for stream in filter(None, [self._proc.stdin,
  64. self._proc.stdout,
  65. self._proc.stderr]):
  66. stream.close()
  67. self._proc = None
  68. def _read_until(self, terminator):
  69. """Read until the prompt is reached."""
  70. buf = bytearray()
  71. while True:
  72. c = self._proc.stdout.read(1)
  73. if not c:
  74. raise _ConverterError(os.fsdecode(bytes(buf)))
  75. buf.extend(c)
  76. if buf.endswith(terminator):
  77. return bytes(buf)
  78. class _GSConverter(_Converter):
  79. def __call__(self, orig, dest):
  80. if not self._proc:
  81. self._proc = subprocess.Popen(
  82. [mpl._get_executable_info("gs").executable,
  83. "-dNOSAFER", "-dNOPAUSE", "-dEPSCrop", "-sDEVICE=png16m"],
  84. # As far as I can see, ghostscript never outputs to stderr.
  85. stdin=subprocess.PIPE, stdout=subprocess.PIPE)
  86. try:
  87. self._read_until(b"\nGS")
  88. except _ConverterError as e:
  89. raise OSError(f"Failed to start Ghostscript:\n\n{e.args[0]}") from None
  90. def encode_and_escape(name):
  91. return (os.fsencode(name)
  92. .replace(b"\\", b"\\\\")
  93. .replace(b"(", br"\(")
  94. .replace(b")", br"\)"))
  95. self._proc.stdin.write(
  96. b"<< /OutputFile ("
  97. + encode_and_escape(dest)
  98. + b") >> setpagedevice ("
  99. + encode_and_escape(orig)
  100. + b") run flush\n")
  101. self._proc.stdin.flush()
  102. # GS> if nothing left on the stack; GS<n> if n items left on the stack.
  103. err = self._read_until((b"GS<", b"GS>"))
  104. stack = self._read_until(b">") if err.endswith(b"GS<") else b""
  105. if stack or not os.path.exists(dest):
  106. stack_size = int(stack[:-1]) if stack else 0
  107. self._proc.stdin.write(b"pop\n" * stack_size)
  108. # Using the systemencoding should at least get the filenames right.
  109. raise ImageComparisonFailure(
  110. (err + stack).decode(sys.getfilesystemencoding(), "replace"))
  111. class _SVGConverter(_Converter):
  112. def __call__(self, orig, dest):
  113. old_inkscape = mpl._get_executable_info("inkscape").version.major < 1
  114. terminator = b"\n>" if old_inkscape else b"> "
  115. if not hasattr(self, "_tmpdir"):
  116. self._tmpdir = TemporaryDirectory()
  117. # On Windows, we must make sure that self._proc has terminated
  118. # (which __del__ does) before clearing _tmpdir.
  119. weakref.finalize(self._tmpdir, self.__del__)
  120. if (not self._proc # First run.
  121. or self._proc.poll() is not None): # Inkscape terminated.
  122. if self._proc is not None and self._proc.poll() is not None:
  123. for stream in filter(None, [self._proc.stdin,
  124. self._proc.stdout,
  125. self._proc.stderr]):
  126. stream.close()
  127. env = {
  128. **os.environ,
  129. # If one passes e.g. a png file to Inkscape, it will try to
  130. # query the user for conversion options via a GUI (even with
  131. # `--without-gui`). Unsetting `DISPLAY` prevents this (and
  132. # causes GTK to crash and Inkscape to terminate, but that'll
  133. # just be reported as a regular exception below).
  134. "DISPLAY": "",
  135. # Do not load any user options.
  136. "INKSCAPE_PROFILE_DIR": self._tmpdir.name,
  137. }
  138. # Old versions of Inkscape (e.g. 0.48.3.1) seem to sometimes
  139. # deadlock when stderr is redirected to a pipe, so we redirect it
  140. # to a temporary file instead. This is not necessary anymore as of
  141. # Inkscape 0.92.1.
  142. stderr = TemporaryFile()
  143. self._proc = subprocess.Popen(
  144. ["inkscape", "--without-gui", "--shell"] if old_inkscape else
  145. ["inkscape", "--shell"],
  146. stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=stderr,
  147. env=env, cwd=self._tmpdir.name)
  148. # Slight abuse, but makes shutdown handling easier.
  149. self._proc.stderr = stderr
  150. try:
  151. self._read_until(terminator)
  152. except _ConverterError as err:
  153. raise OSError(
  154. "Failed to start Inkscape in interactive mode:\n\n"
  155. + err.args[0]) from err
  156. # Inkscape's shell mode does not support escaping metacharacters in the
  157. # filename ("\n", and ":;" for inkscape>=1). Avoid any problems by
  158. # running from a temporary directory and using fixed filenames.
  159. inkscape_orig = Path(self._tmpdir.name, os.fsdecode(b"f.svg"))
  160. inkscape_dest = Path(self._tmpdir.name, os.fsdecode(b"f.png"))
  161. try:
  162. inkscape_orig.symlink_to(Path(orig).resolve())
  163. except OSError:
  164. shutil.copyfile(orig, inkscape_orig)
  165. self._proc.stdin.write(
  166. b"f.svg --export-png=f.png\n" if old_inkscape else
  167. b"file-open:f.svg;export-filename:f.png;export-do;file-close\n")
  168. self._proc.stdin.flush()
  169. try:
  170. self._read_until(terminator)
  171. except _ConverterError as err:
  172. # Inkscape's output is not localized but gtk's is, so the output
  173. # stream probably has a mixed encoding. Using the filesystem
  174. # encoding should at least get the filenames right...
  175. self._proc.stderr.seek(0)
  176. raise ImageComparisonFailure(
  177. self._proc.stderr.read().decode(
  178. sys.getfilesystemencoding(), "replace")) from err
  179. os.remove(inkscape_orig)
  180. shutil.move(inkscape_dest, dest)
  181. def __del__(self):
  182. super().__del__()
  183. if hasattr(self, "_tmpdir"):
  184. self._tmpdir.cleanup()
  185. class _SVGWithMatplotlibFontsConverter(_SVGConverter):
  186. """
  187. A SVG converter which explicitly adds the fonts shipped by Matplotlib to
  188. Inkspace's font search path, to better support `svg.fonttype = "none"`
  189. (which is in particular used by certain mathtext tests).
  190. """
  191. def __call__(self, orig, dest):
  192. if not hasattr(self, "_tmpdir"):
  193. self._tmpdir = TemporaryDirectory()
  194. shutil.copytree(cbook._get_data_path("fonts/ttf"),
  195. Path(self._tmpdir.name, "fonts"))
  196. return super().__call__(orig, dest)
  197. def _update_converter():
  198. try:
  199. mpl._get_executable_info("gs")
  200. except mpl.ExecutableNotFoundError:
  201. pass
  202. else:
  203. converter['pdf'] = converter['eps'] = _GSConverter()
  204. try:
  205. mpl._get_executable_info("inkscape")
  206. except mpl.ExecutableNotFoundError:
  207. pass
  208. else:
  209. converter['svg'] = _SVGConverter()
  210. #: A dictionary that maps filename extensions to functions which themselves
  211. #: convert between arguments `old` and `new` (filenames).
  212. converter = {}
  213. _update_converter()
  214. _svg_with_matplotlib_fonts_converter = _SVGWithMatplotlibFontsConverter()
  215. def comparable_formats():
  216. """
  217. Return the list of file formats that `.compare_images` can compare
  218. on this system.
  219. Returns
  220. -------
  221. list of str
  222. E.g. ``['png', 'pdf', 'svg', 'eps']``.
  223. """
  224. return ['png', *converter]
  225. def convert(filename, cache):
  226. """
  227. Convert the named file to png; return the name of the created file.
  228. If *cache* is True, the result of the conversion is cached in
  229. `matplotlib.get_cachedir() + '/test_cache/'`. The caching is based on a
  230. hash of the exact contents of the input file. Old cache entries are
  231. automatically deleted as needed to keep the size of the cache capped to
  232. twice the size of all baseline images.
  233. """
  234. path = Path(filename)
  235. if not path.exists():
  236. raise OSError(f"{path} does not exist")
  237. if path.suffix[1:] not in converter:
  238. import pytest
  239. pytest.skip(f"Don't know how to convert {path.suffix} files to png")
  240. newpath = path.parent / f"{path.stem}_{path.suffix[1:]}.png"
  241. # Only convert the file if the destination doesn't already exist or
  242. # is out of date.
  243. if not newpath.exists() or newpath.stat().st_mtime < path.stat().st_mtime:
  244. cache_dir = _get_cache_path() if cache else None
  245. if cache_dir is not None:
  246. _register_conversion_cache_cleaner_once()
  247. hash_value = get_file_hash(path)
  248. cached_path = cache_dir / (hash_value + newpath.suffix)
  249. if cached_path.exists():
  250. _log.debug("For %s: reusing cached conversion.", filename)
  251. shutil.copyfile(cached_path, newpath)
  252. return str(newpath)
  253. _log.debug("For %s: converting to png.", filename)
  254. convert = converter[path.suffix[1:]]
  255. if path.suffix == ".svg":
  256. contents = path.read_text()
  257. if 'style="font:' in contents:
  258. # for svg.fonttype = none, we explicitly patch the font search
  259. # path so that fonts shipped by Matplotlib are found.
  260. convert = _svg_with_matplotlib_fonts_converter
  261. convert(path, newpath)
  262. if cache_dir is not None:
  263. _log.debug("For %s: caching conversion result.", filename)
  264. shutil.copyfile(newpath, cached_path)
  265. return str(newpath)
  266. def _clean_conversion_cache():
  267. # This will actually ignore mpl_toolkits baseline images, but they're
  268. # relatively small.
  269. baseline_images_size = sum(
  270. path.stat().st_size
  271. for path in Path(mpl.__file__).parent.glob("**/baseline_images/**/*"))
  272. # 2x: one full copy of baselines, and one full copy of test results
  273. # (actually an overestimate: we don't convert png baselines and results).
  274. max_cache_size = 2 * baseline_images_size
  275. # Reduce cache until it fits.
  276. with cbook._lock_path(_get_cache_path()):
  277. cache_stat = {
  278. path: path.stat() for path in _get_cache_path().glob("*")}
  279. cache_size = sum(stat.st_size for stat in cache_stat.values())
  280. paths_by_atime = sorted( # Oldest at the end.
  281. cache_stat, key=lambda path: cache_stat[path].st_atime,
  282. reverse=True)
  283. while cache_size > max_cache_size:
  284. path = paths_by_atime.pop()
  285. cache_size -= cache_stat[path].st_size
  286. path.unlink()
  287. @functools.cache # Ensure this is only registered once.
  288. def _register_conversion_cache_cleaner_once():
  289. atexit.register(_clean_conversion_cache)
  290. def crop_to_same(actual_path, actual_image, expected_path, expected_image):
  291. # clip the images to the same size -- this is useful only when
  292. # comparing eps to pdf
  293. if actual_path[-7:-4] == 'eps' and expected_path[-7:-4] == 'pdf':
  294. aw, ah, ad = actual_image.shape
  295. ew, eh, ed = expected_image.shape
  296. actual_image = actual_image[int(aw / 2 - ew / 2):int(
  297. aw / 2 + ew / 2), int(ah / 2 - eh / 2):int(ah / 2 + eh / 2)]
  298. return actual_image, expected_image
  299. def calculate_rms(expected_image, actual_image):
  300. """
  301. Calculate the per-pixel errors, then compute the root mean square error.
  302. """
  303. if expected_image.shape != actual_image.shape:
  304. raise ImageComparisonFailure(
  305. f"Image sizes do not match expected size: {expected_image.shape} "
  306. f"actual size {actual_image.shape}")
  307. # Convert to float to avoid overflowing finite integer types.
  308. return np.sqrt(((expected_image - actual_image).astype(float) ** 2).mean())
  309. # NOTE: compare_image and save_diff_image assume that the image does not have
  310. # 16-bit depth, as Pillow converts these to RGB incorrectly.
  311. def _load_image(path):
  312. img = Image.open(path)
  313. # In an RGBA image, if the smallest value in the alpha channel is 255, all
  314. # values in it must be 255, meaning that the image is opaque. If so,
  315. # discard the alpha channel so that it may compare equal to an RGB image.
  316. if img.mode != "RGBA" or img.getextrema()[3][0] == 255:
  317. img = img.convert("RGB")
  318. return np.asarray(img)
  319. def compare_images(expected, actual, tol, in_decorator=False):
  320. """
  321. Compare two "image" files checking differences within a tolerance.
  322. The two given filenames may point to files which are convertible to
  323. PNG via the `.converter` dictionary. The underlying RMS is calculated
  324. with the `.calculate_rms` function.
  325. Parameters
  326. ----------
  327. expected : str
  328. The filename of the expected image.
  329. actual : str
  330. The filename of the actual image.
  331. tol : float
  332. The tolerance (a color value difference, where 255 is the
  333. maximal difference). The test fails if the average pixel
  334. difference is greater than this value.
  335. in_decorator : bool
  336. Determines the output format. If called from image_comparison
  337. decorator, this should be True. (default=False)
  338. Returns
  339. -------
  340. None or dict or str
  341. Return *None* if the images are equal within the given tolerance.
  342. If the images differ, the return value depends on *in_decorator*.
  343. If *in_decorator* is true, a dict with the following entries is
  344. returned:
  345. - *rms*: The RMS of the image difference.
  346. - *expected*: The filename of the expected image.
  347. - *actual*: The filename of the actual image.
  348. - *diff_image*: The filename of the difference image.
  349. - *tol*: The comparison tolerance.
  350. Otherwise, a human-readable multi-line string representation of this
  351. information is returned.
  352. Examples
  353. --------
  354. ::
  355. img1 = "./baseline/plot.png"
  356. img2 = "./output/plot.png"
  357. compare_images(img1, img2, 0.001)
  358. """
  359. actual = os.fspath(actual)
  360. if not os.path.exists(actual):
  361. raise Exception(f"Output image {actual} does not exist.")
  362. if os.stat(actual).st_size == 0:
  363. raise Exception(f"Output image file {actual} is empty.")
  364. # Convert the image to png
  365. expected = os.fspath(expected)
  366. if not os.path.exists(expected):
  367. raise OSError(f'Baseline image {expected!r} does not exist.')
  368. extension = expected.split('.')[-1]
  369. if extension != 'png':
  370. actual = convert(actual, cache=True)
  371. expected = convert(expected, cache=True)
  372. # open the image files
  373. expected_image = _load_image(expected)
  374. actual_image = _load_image(actual)
  375. actual_image, expected_image = crop_to_same(
  376. actual, actual_image, expected, expected_image)
  377. diff_image = make_test_filename(actual, 'failed-diff')
  378. if tol <= 0:
  379. if np.array_equal(expected_image, actual_image):
  380. return None
  381. # convert to signed integers, so that the images can be subtracted without
  382. # overflow
  383. expected_image = expected_image.astype(np.int16)
  384. actual_image = actual_image.astype(np.int16)
  385. rms = calculate_rms(expected_image, actual_image)
  386. if rms <= tol:
  387. return None
  388. save_diff_image(expected, actual, diff_image)
  389. results = dict(rms=rms, expected=str(expected),
  390. actual=str(actual), diff=str(diff_image), tol=tol)
  391. if not in_decorator:
  392. # Then the results should be a string suitable for stdout.
  393. template = ['Error: Image files did not match.',
  394. 'RMS Value: {rms}',
  395. 'Expected: \n {expected}',
  396. 'Actual: \n {actual}',
  397. 'Difference:\n {diff}',
  398. 'Tolerance: \n {tol}', ]
  399. results = '\n '.join([line.format(**results) for line in template])
  400. return results
  401. def save_diff_image(expected, actual, output):
  402. """
  403. Parameters
  404. ----------
  405. expected : str
  406. File path of expected image.
  407. actual : str
  408. File path of actual image.
  409. output : str
  410. File path to save difference image to.
  411. """
  412. expected_image = _load_image(expected)
  413. actual_image = _load_image(actual)
  414. actual_image, expected_image = crop_to_same(
  415. actual, actual_image, expected, expected_image)
  416. expected_image = np.array(expected_image, float)
  417. actual_image = np.array(actual_image, float)
  418. if expected_image.shape != actual_image.shape:
  419. raise ImageComparisonFailure(
  420. f"Image sizes do not match expected size: {expected_image.shape} "
  421. f"actual size {actual_image.shape}")
  422. abs_diff = np.abs(expected_image - actual_image)
  423. # expand differences in luminance domain
  424. abs_diff *= 10
  425. abs_diff = np.clip(abs_diff, 0, 255).astype(np.uint8)
  426. if abs_diff.shape[2] == 4: # Hard-code the alpha channel to fully solid
  427. abs_diff[:, :, 3] = 255
  428. Image.fromarray(abs_diff).save(output, format="png")