check_frame.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """check_frame.py [--baseline base.png] shot.png [shot.png ...] - did the wallpaper reach the screen?
  2. check_frame.py --differ a.png b.png - do two frames differ (hotswap)?
  3. check_frame.py --similar a.png b.png [max] - are two frames of the same wallpaper alike (a hotswap must look like a fresh start)?
  4. check_frame.py --reference ref.png shot.png [shot.png ...] - does the shot look like the reference frame of that wallpaper (reference/<id>.png,
  5. make_reference_frames.sh), not upside down or mirrored, not another crop?
  6. check_frame.py --crop from,to [--baseline base.png] shot.png - only the part of the width between the two fractions (one
  7. monitor of a multi monitor screenshot)
  8. Without --baseline a screenshot only fails when it is pure black. With the baseline (the desktop's own screenshot taken
  9. before the engine started) it must also differ from it along the right edge and the top, where windows, panels and
  10. desktop icons rarely are, so a desktop that still shows its default background fails. Prints one "PASS|FAIL <file>: <why>"
  11. line per file, exit code 1 when any failed. With --reference the middle of the shot is compared cell by cell with the
  12. reference frame of the wallpaper: enough cells must match (a window or an animation may cover some), and when too few do
  13. and the flipped reference matches clearly better the shot is reported as upside down or mirrored.
  14. """
  15. import sys
  16. from PIL import Image, ImageChops, ImageOps, ImageStat
  17. def strips(image):
  18. w, h = image.size
  19. return [
  20. image.crop((w * 88 // 100, h * 15 // 100, w * 99 // 100, h * 80 // 100)),
  21. image.crop((w * 30 // 100, h * 2 // 100, w * 85 // 100, h * 10 // 100)),
  22. ]
  23. CROP = None
  24. def crop(image):
  25. if CROP is None:
  26. return image
  27. w, h = image.size
  28. return image.crop((int(w * CROP[0]), 0, int(w * CROP[1]), h))
  29. def check(path, baseline):
  30. image = crop(Image.open(path).convert("RGB"))
  31. parts = strips(image)
  32. stats = [ImageStat.Stat(part.convert("L")) for part in parts]
  33. mean = sum(stat.mean[0] for stat in stats) / len(stats)
  34. stddev = max(stat.stddev[0] for stat in stats)
  35. if mean < 1 and stddev < 1:
  36. return False, "black"
  37. if baseline is not None:
  38. base_parts = strips(crop(baseline).resize(image.size))
  39. diffs = [ImageStat.Stat(ImageChops.difference(a, b).convert("L")).mean[0] for a, b in zip(parts, base_parts)]
  40. diff = sum(diffs) / len(diffs)
  41. # a mostly black wallpaper has a small mean difference but still some lit pixels where a bare desktop has none
  42. histograms = [ImageChops.difference(a, b).convert("L").histogram() for a, b in zip(parts, base_parts)]
  43. lit = sum(sum(h[9:]) for h in histograms) / sum(sum(h) for h in histograms)
  44. if diff < 6 and lit < 0.003:
  45. return False, f"same as the desktop without a wallpaper (difference {diff:.1f})"
  46. return True, f"mean {mean:.0f}, difference from the baseline {diff:.0f}"
  47. return True, f"mean {mean:.0f}, stddev {stddev:.0f}"
  48. GRID = (32, 18)
  49. MIDDLE = (0.08, 0.08, 0.92, 0.86)
  50. CELL_LIMIT = 36
  51. MATCH_RATIO = 0.5
  52. def cells(image):
  53. w, h = image.size
  54. middle = image.crop((int(w * MIDDLE[0]), int(h * MIDDLE[1]), int(w * MIDDLE[2]), int(h * MIDDLE[3])))
  55. small = middle.resize(GRID, Image.BOX)
  56. return list(small.get_flattened_data() if hasattr(small, "get_flattened_data") else small.getdata())
  57. def match_ratio(a, b):
  58. close = sum(1 for p, q in zip(a, b) if sum(abs(x - y) for x, y in zip(p, q)) / 3 <= CELL_LIMIT)
  59. return close / len(a)
  60. def fill_crop(reference, size):
  61. """the scene fills the screen and crops whichever axis overflows, so the reference is cut to the shot's shape"""
  62. w, h = reference.size
  63. wanted = size[0] / size[1]
  64. if abs(w / h - wanted) < 0.02:
  65. return reference
  66. if w / h > wanted:
  67. width = round(h * wanted)
  68. return reference.crop(((w - width) // 2, 0, (w - width) // 2 + width, h))
  69. height = round(w / wanted)
  70. return reference.crop((0, (h - height) // 2, w, (h - height) // 2 + height))
  71. def check_reference(path, reference):
  72. image = crop(Image.open(path).convert("RGB"))
  73. reference = fill_crop(reference, image.size)
  74. shot = cells(image)
  75. straight = match_ratio(shot, cells(reference))
  76. for name, flipped in (("upside down", ImageOps.flip(reference)), ("mirrored", ImageOps.mirror(reference))):
  77. ratio = match_ratio(shot, cells(flipped))
  78. if ratio >= 0.6 and ratio >= straight + 0.15:
  79. return False, f"{name} ({ratio:.0%} of the cells match the flipped reference, {straight:.0%} the reference)"
  80. if straight < MATCH_RATIO:
  81. return False, f"does not look like the reference (only {straight:.0%} of the cells match)"
  82. return True, f"{straight:.0%} of the cells match the reference"
  83. def differ(a, b):
  84. """Two frames of the same desktop must differ clearly (a hotswap changed the picture)."""
  85. first, second = Image.open(a).convert("RGB"), Image.open(b).convert("RGB").resize(Image.open(a).size)
  86. parts = list(zip(strips(first), strips(second)))
  87. diff = sum(ImageStat.Stat(ImageChops.difference(x, y).convert("L")).mean[0] for x, y in parts) / len(parts)
  88. ok = diff >= 6
  89. print(f"{'PASS' if ok else 'FAIL'} {b}: {'differs from' if ok else 'same as'} {a} (difference {diff:.1f})")
  90. sys.exit(0 if ok else 1)
  91. def similar(a, b, limit):
  92. size = (96, 54)
  93. first, second = Image.open(a).convert("RGB").resize(size), Image.open(b).convert("RGB").resize(size)
  94. diff = ImageStat.Stat(ImageChops.difference(first, second).convert("L")).mean[0]
  95. ok = diff <= limit
  96. print(f"{'PASS' if ok else 'FAIL'} {b}: {'like' if ok else 'not like'} {a} (difference {diff:.1f}, limit {limit:g})")
  97. sys.exit(0 if ok else 1)
  98. def main():
  99. global CROP
  100. args = sys.argv[1:]
  101. if args[:1] == ["--similar"]:
  102. similar(args[1], args[2], float(args[3]) if len(args) > 3 else 10)
  103. if args[:1] == ["--crop"]:
  104. CROP = [float(x) for x in args[1].split(",")]
  105. args = args[2:]
  106. if args[:1] == ["--differ"]:
  107. differ(args[1], args[2])
  108. if args[:1] == ["--reference"]:
  109. reference = Image.open(args[1]).convert("RGB")
  110. failed = False
  111. for path in args[2:]:
  112. ok, why = check_reference(path, reference)
  113. failed |= not ok
  114. print(f"{'PASS' if ok else 'FAIL'} {path}: {why}")
  115. sys.exit(1 if failed else 0)
  116. baseline = None
  117. if args[:1] == ["--baseline"]:
  118. baseline = Image.open(args[1]).convert("RGB")
  119. args = args[2:]
  120. failed = False
  121. for path in args:
  122. ok, why = check(path, baseline)
  123. failed |= not ok
  124. print(f"{'PASS' if ok else 'FAIL'} {path}: {why}")
  125. sys.exit(1 if failed else 0)
  126. main()