compare.py 19 KB

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