test_png.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from io import BytesIO
  2. import glob
  3. import os
  4. from pathlib import Path
  5. import numpy as np
  6. import pytest
  7. from matplotlib.testing.decorators import image_comparison
  8. from matplotlib import pyplot as plt
  9. import matplotlib.cm as cm
  10. @image_comparison(['pngsuite.png'], tol=0.03)
  11. def test_pngsuite():
  12. dirname = os.path.join(
  13. os.path.dirname(__file__),
  14. 'baseline_images',
  15. 'pngsuite')
  16. files = sorted(glob.iglob(os.path.join(dirname, 'basn*.png')))
  17. plt.figure(figsize=(len(files), 2))
  18. for i, fname in enumerate(files):
  19. data = plt.imread(fname)
  20. cmap = None # use default colormap
  21. if data.ndim == 2:
  22. # keep grayscale images gray
  23. cmap = cm.gray
  24. plt.imshow(data, extent=[i, i + 1, 0, 1], cmap=cmap)
  25. plt.gca().patch.set_facecolor("#ddffff")
  26. plt.gca().set_xlim(0, len(files))
  27. def test_imread_png_uint16():
  28. from matplotlib import _png
  29. with (Path(__file__).parent
  30. / 'baseline_images/test_png/uint16.png').open('rb') as file:
  31. img = _png.read_png_int(file)
  32. assert (img.dtype == np.uint16)
  33. assert np.sum(img.flatten()) == 134184960
  34. def test_truncated_file(tmpdir):
  35. d = tmpdir.mkdir('test')
  36. fname = str(d.join('test.png'))
  37. fname_t = str(d.join('test_truncated.png'))
  38. plt.savefig(fname)
  39. with open(fname, 'rb') as fin:
  40. buf = fin.read()
  41. with open(fname_t, 'wb') as fout:
  42. fout.write(buf[:20])
  43. with pytest.raises(Exception):
  44. plt.imread(fname_t)
  45. def test_truncated_buffer():
  46. b = BytesIO()
  47. plt.savefig(b)
  48. b.seek(0)
  49. b2 = BytesIO(b.read(20))
  50. b2.seek(0)
  51. with pytest.raises(Exception):
  52. plt.imread(b2)