check_frame.py 7.8 KB

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