Files

56 lines
2.3 KiB
Python

# Reference decodes of the PngSuite (run once, the output is committed; from png-luau tools/png_reference.py):
# nix shell --impure --expr 'with import <nixpkgs> {}; python3.withPackages (p: [p.pypng p.pillow])' \
# -c python3 -I tools/fixtures/_png_reference.py
# Writes tests/fixtures/pngsuite_ref.txt: "<file> <width> <height> <crc32 of RGBA8 pixels>" per image, or
# "<file> corrupt" for the suite's deliberately broken x* files. Pixels come from pypng (pure Python, exact at every bit depth) as RGBA,
# scaled to 8 bits the way png-luau does: 16-bit samples keep the high byte, 1/2/4-bit samples are scaled by
# 255 / (2^depth - 1). Pillow cross-checks every image without 16-bit samples.
import os, sys, zlib
import png
from PIL import Image
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SUITE = os.path.join(ROOT, "tests", "fixtures", "pngsuite")
def rgba8(path):
r = png.Reader(filename=path)
w, h, rows, info = r.asRGBA()
bd = info["bitdepth"]
out = bytearray()
for row in rows:
if bd == 16:
out += bytes(v >> 8 for v in row)
elif bd == 8:
out += bytes(row)
else:
m = (1 << bd) - 1
out += bytes(v * 255 // m for v in row)
return w, h, bytes(out), bd
lines, agree, checked = [], 0, 0
for name in sorted(os.listdir(SUITE)):
if not name.endswith(".png"):
continue
path = os.path.join(SUITE, name)
if name.startswith("x"):
lines.append("%s corrupt" % name) # the suite's deliberately corrupt files (x*: bad signature, CRC, ...)
continue
try:
w, h, px, bd = rgba8(path)
except Exception as e:
lines.append("%s error" % name)
continue
lines.append("%s %d %d %08x" % (name, w, h, zlib.crc32(px)))
with open(path, "rb") as f:
raw = f.read()
if bd != 16 and b"sBIT" not in raw:
checked += 1
im = Image.open(path).convert("RGBA")
if im.tobytes() == px:
agree += 1
else:
print("pillow disagrees:", name, file=sys.stderr)
with open(os.path.join(ROOT, "tests", "fixtures", "pngsuite_ref.txt"), "w") as f:
f.write("\n".join(lines) + "\n")
print("%d images, %d rejected; pillow agrees on %d of %d checked" % (len(lines), sum(l.endswith(" error") for l in lines), agree, checked))