imgA: merge ws/imgA-simple (tga, qoi, pnm, ico, hdr)
This commit is contained in:
commit
294b212801
23 files changed
+3293
No files matched your search
@@ -178,3 +178,43 @@ do
|
||||
Tiff.decode(Bytes.reader(enc16))
|
||||
end)
|
||||
end
|
||||
|
||||
-- ------------------------------------------------------------------------------------------------ imgA-simple: qoi / tga / pnm / hdr
|
||||
-- fixtures: tools/fixtures/qoi.py (tests/gen/qoi_bench.luau: run python3 -I tools/fixtures.py qoi first)
|
||||
do
|
||||
local Qoi = require("@formats/image/qoi")
|
||||
local Tga = require("@formats/image/tga")
|
||||
local Pnm = require("@formats/image/pnm")
|
||||
local Hdr = require("@formats/image/hdr")
|
||||
local Types = require("@formats/Types")
|
||||
local QB = require("@tests/gen/qoi_bench")
|
||||
local qd = buffer.fromstring(QB.data)
|
||||
local n = QB.width * QB.height * 4
|
||||
bench("qoi decode 1024x768", 5, n, function()
|
||||
Qoi.decode(Bytes.reader(qd))
|
||||
end)
|
||||
local img = Types.Image.new(QB.width, QB.height)
|
||||
img.pixels = buffer.fromstring(QB.pixels)
|
||||
bench("qoi encode 1024x768", 5, n, function()
|
||||
Qoi.encode(img)
|
||||
end)
|
||||
local tr = Tga.encode(img, { rle = true }) :: buffer
|
||||
bench("tga decode rle 1024x768", 3, n, function()
|
||||
Tga.decode(Bytes.reader(tr))
|
||||
end)
|
||||
bench("tga encode rle 1024x768", 3, n, function()
|
||||
Tga.encode(img, { rle = true })
|
||||
end)
|
||||
local pp = Pnm.encode(img, { format = "ppm" }) :: buffer
|
||||
bench("ppm decode 1024x768", 3, n, function()
|
||||
Pnm.decode(Bytes.reader(pp))
|
||||
end)
|
||||
local f = Hdr.decode(Bytes.reader(Hdr.encode(img) :: buffer), { native = true }) :: Types.Image
|
||||
local hb = Hdr.encode(f) :: buffer
|
||||
bench("hdr decode rle 1024x768 (rgbaf32)", 3, n, function()
|
||||
Hdr.decode(Bytes.reader(hb), { native = true })
|
||||
end)
|
||||
bench("hdr encode rle 1024x768", 3, n, function()
|
||||
Hdr.encode(f)
|
||||
end)
|
||||
end
|
||||
@@ -0,0 +1,93 @@
|
||||
# Radiance HDR fixtures (tools/fixtures.py): files ImageMagick writes (new-style RLE, from float PFM sources) and
|
||||
# hand-written ones (flat and old-style RLE scanlines, narrow images, the "#?RGBE" header, EXPOSURE lines, every
|
||||
# orientation); references = ImageMagick's float decodes for its files, and for the hand-written ones the RGBE values
|
||||
# decoded by the rgbe.c rule (m * 2^(e - 136)) here.
|
||||
# tests/gen/hdr.luau { { name, data, width, height, floats (rgbaf32 little-endian bytes), exposure? } }
|
||||
import math, os, random, shutil, struct, subprocess, tempfile
|
||||
|
||||
|
||||
def rgbe(r, g, b):
|
||||
v = max(r, g, b)
|
||||
if v < 1e-32:
|
||||
return (0, 0, 0, 0)
|
||||
m, e = math.frexp(v)
|
||||
s = m * 256 / v
|
||||
return (min(255, int(r * s)), min(255, int(g * s)), min(255, int(b * s)), e + 128)
|
||||
|
||||
|
||||
def flt(p):
|
||||
if p[3] == 0:
|
||||
return (0.0, 0.0, 0.0)
|
||||
f = math.ldexp(1.0, p[3] - 136)
|
||||
return (p[0] * f, p[1] * f, p[2] * f)
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
|
||||
work = tempfile.mkdtemp(prefix="formats-hdr-")
|
||||
try:
|
||||
_generate(ctx, magick, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, magick, work):
|
||||
rng = random.Random(4)
|
||||
cases = []
|
||||
|
||||
def im_case(name, w, h, fn):
|
||||
pfm = os.path.join(work, name + ".pfm")
|
||||
with open(pfm, "wb") as f:
|
||||
f.write(b"PF\n%d %d\n-1.0\n" % (w, h))
|
||||
for y in range(h - 1, -1, -1):
|
||||
for x in range(w):
|
||||
f.write(struct.pack("<fff", *fn(x, y)))
|
||||
out = os.path.join(work, name + ".hdr")
|
||||
subprocess.run([magick, pfm, out], check=True, capture_output=True)
|
||||
fl = subprocess.run([magick, out, "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-"], check=True, capture_output=True).stdout
|
||||
cases.append({"name": name, "data": open(out, "rb").read(), "width": w, "height": h, "floats": fl})
|
||||
|
||||
im_case("im-gradient", 64, 20, lambda x, y: (x / 16.0, y / 5.0, (x * y) % 7 * 0.3))
|
||||
im_case("im-noise", 33, 9, lambda x, y: (rng.random() * 100, rng.random(), rng.random() * 0.001))
|
||||
im_case("im-flat", 100, 3, lambda x, y: (0.5, 0.25, 2.0) if x < 60 else (0.0, 0.0, 0.0))
|
||||
|
||||
def hand(name, w, h, header, res, rows, mapping, exposure=None):
|
||||
"""rows: list of scanline byte strings; mapping(i, j) -> (x, y) of scanline i pixel j; pix: (i, j) -> RGBE"""
|
||||
data = header + b"\n\n" + res + b"\n" + b"".join(r for r, _ in rows)
|
||||
fl = [(0.0, 0.0, 0.0)] * (w * h)
|
||||
for i, (_, pixels) in enumerate(rows):
|
||||
for j, p in enumerate(pixels):
|
||||
x, y = mapping(i, j)
|
||||
fl[y * w + x] = flt(p)
|
||||
c = {"name": name, "data": data, "width": w, "height": h,
|
||||
"floats": b"".join(struct.pack("<ffff", *v, 1.0) for v in fl)}
|
||||
if exposure:
|
||||
c["exposure"] = exposure
|
||||
cases.append(c)
|
||||
|
||||
def flat_row(n, seed):
|
||||
px = [rgbe(rng.random() * 4, rng.random(), rng.random() * 0.1) for _ in range(n)]
|
||||
px = [p if p[:3] != (1, 1, 1) else (2, 1, 1, p[3]) for p in px]
|
||||
return b"".join(bytes(p) for p in px), px
|
||||
|
||||
def oldrle_row(n):
|
||||
p = rgbe(0.7, 0.2, 0.1)
|
||||
q = rgbe(3.0, 3.0, 3.0)
|
||||
# p, then a run of 3 more p, then q, then a run of 2 + (1 << 8)*0 ... keep it simple: q x (n - 5)
|
||||
pix = [p] * 4 + [q] * (n - 4)
|
||||
run = n - 5
|
||||
return bytes(p) + bytes((1, 1, 1, 3)) + bytes(q) + bytes((1, 1, 1, run)), pix
|
||||
|
||||
w, h = 5, 3
|
||||
rows = [flat_row(w, i) for i in range(h)]
|
||||
hand("flat-narrow", w, h, b"#?RGBE\nFORMAT=32-bit_rle_rgbe\nEXPOSURE=2.0\nEXPOSURE=1.5", b"-Y 3 +X 5", rows, lambda i, j: (j, i), exposure=3.0)
|
||||
rows = [oldrle_row(12) for _ in range(2)]
|
||||
hand("old-rle", 12, 2, b"#?RADIANCE\nFORMAT=32-bit_rle_rgbe\nSOFTWARE=hand", b"-Y 2 +X 12", rows, lambda i, j: (j, i))
|
||||
for res, mp in ((b"+Y 3 +X 5", lambda i, j: (j, 2 - i)), (b"-Y 3 -X 5", lambda i, j: (4 - j, i)),
|
||||
(b"+Y 3 -X 5", lambda i, j: (4 - j, 2 - i))):
|
||||
rows = [flat_row(5, i) for i in range(3)]
|
||||
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
|
||||
for res, mp in ((b"+X 5 -Y 3", lambda i, j: (i, j)), (b"-X 5 +Y 3", lambda i, j: (4 - i, 2 - j))):
|
||||
rows = [flat_row(3, i) for i in range(5)]
|
||||
hand("orient " + res.decode(), 5, 3, b"#?RADIANCE", res, rows, mp)
|
||||
ctx.emit("hdr", cases)
|
||||
@@ -0,0 +1,93 @@
|
||||
# ICO / CUR fixtures (tools/fixtures.py): icons written by ImageMagick (auto-resize sets with a 256 PNG entry) and
|
||||
# Pillow (PNG and BMP entries), and hand-built ones from Pillow's BMP writer (1 / 4 / 8 / 24 / 32-bit DIBs with AND
|
||||
# masks, a cursor with hotspots); references = Pillow's RGBA decode of every entry, in file order.
|
||||
# tests/gen/ico.luau { { name, data, entries = { { width, height, rgba (bytes) } } } }
|
||||
import struct
|
||||
|
||||
CODE = r'''
|
||||
import io, struct, subprocess, sys
|
||||
from PIL import Image, IcoImagePlugin
|
||||
magick = sys.argv[1]
|
||||
out = []
|
||||
def refs(data):
|
||||
if data[2] == 2: # IcoFile reads icons only: decode a cursor's entries as an icon's
|
||||
data = data[:2] + b"\x01" + data[3:]
|
||||
f = IcoImagePlugin.IcoFile(io.BytesIO(data))
|
||||
order = sorted(range(len(f.entry)), key=lambda i: f.entry[i].offset)
|
||||
res = []
|
||||
for i in order:
|
||||
im = f.frame(i).convert("RGBA")
|
||||
res.append((im.size[0], im.size[1], im.tobytes()))
|
||||
return res
|
||||
def emit(name, data):
|
||||
out.append((name, data, refs(data)))
|
||||
src = Image.new("RGBA", (64, 64))
|
||||
px = src.load()
|
||||
for y in range(64):
|
||||
for x in range(64):
|
||||
a = 255 if (x - 32) ** 2 + (y - 32) ** 2 < 900 else (0 if x < 8 else 128)
|
||||
px[x, y] = ((x * 4) % 256, (y * 4) % 256, ((x ^ y) * 8) % 256, a)
|
||||
png = io.BytesIO(); src.save(png, "PNG")
|
||||
r = subprocess.run([magick, "png:-", "-define", "icon:auto-resize=256,48,32,16", "ico:-"], input=png.getvalue(), capture_output=True, check=True)
|
||||
emit("im-autoresize", r.stdout)
|
||||
for fmt in ("png", "bmp"):
|
||||
b = io.BytesIO(); src.save(b, "ICO", sizes=[(16, 16), (32, 32), (64, 64)], bitmap_format=fmt); emit("pil-" + fmt, b.getvalue())
|
||||
# hand-built DIB entries from Pillow BMPs
|
||||
def dib(im, mask_fn):
|
||||
b = io.BytesIO(); im.save(b, "BMP"); d = b.getvalue()[14:]
|
||||
w, h = im.size
|
||||
hs = struct.unpack("<I", d[:4])[0]
|
||||
d = d[:8] + struct.pack("<i", h * 2) + d[12:]
|
||||
stride = ((w + 31) // 32) * 4
|
||||
mask = bytearray()
|
||||
for y in range(h - 1, -1, -1):
|
||||
row = bytearray(stride)
|
||||
for x in range(w):
|
||||
if mask_fn(x, y):
|
||||
row[x // 8] |= 0x80 >> (x % 8)
|
||||
mask += row
|
||||
return d + bytes(mask)
|
||||
def icon(entries, typ=1, hotspots=None):
|
||||
hdr = struct.pack("<HHH", 0, typ, len(entries))
|
||||
off = 6 + 16 * len(entries)
|
||||
dirs, blobs = b"", b""
|
||||
for i, (im, blob, bpp) in enumerate(entries):
|
||||
w, h = im.size
|
||||
f1, f2 = (1, bpp) if typ == 1 else hotspots[i]
|
||||
dirs += struct.pack("<BBBBHHII", w % 256, h % 256, 0, 0, f1, f2, len(blob), off)
|
||||
off += len(blob); blobs += blob
|
||||
return hdr + dirs + blobs
|
||||
base = src.resize((24, 20))
|
||||
m = lambda x, y: (x + y) % 7 == 0
|
||||
e1 = base.convert("1"); e4 = base.convert("RGB").quantize(16); e8 = base.convert("RGB").quantize(200); e24 = base.convert("RGB")
|
||||
emit("hand-dibs", icon([(e1, dib(e1, m), 1), (e4, dib(e4, m), 4), (e8, dib(e8, m), 8), (e24, dib(e24, m), 24)]))
|
||||
e32 = src.resize((30, 17))
|
||||
b = io.BytesIO(); e32.save(b, "BMP"); d32 = b.getvalue()[14:]
|
||||
# Pillow writes 32-bit BMPs as BGRA? if not, build one by hand
|
||||
w, h = e32.size
|
||||
bgra = b"".join(bytes((p[2], p[1], p[0], p[3])) for y in range(h - 1, -1, -1) for p in (e32.getpixel((x, y)) for x in range(w)))
|
||||
stride = ((w + 31) // 32) * 4
|
||||
d32 = struct.pack("<IiiHHIIiiII", 40, w, h * 2, 1, 32, 0, len(bgra), 0, 0, 0, 0) + bgra + bytes(stride * h)
|
||||
emit("hand-32", icon([(e32, d32, 32)]))
|
||||
emit("hand-cur", icon([(e24, dib(e24, m), 24), (e8, dib(e8, m), 8)], typ=2, hotspots=[(3, 4), (5, 6)]))
|
||||
for name, data, rs in out:
|
||||
sys.stdout.buffer.write(struct.pack("<HIH", len(name), len(data), len(rs)) + name.encode() + data)
|
||||
for w, h, px in rs:
|
||||
sys.stdout.buffer.write(struct.pack("<III", w, h, len(px)) + px)
|
||||
'''
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
|
||||
raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick)))
|
||||
cases, p = [], 0
|
||||
while p < len(raw):
|
||||
nl, dl, ne = struct.unpack("<HIH", raw[p:p + 8]); p += 8
|
||||
name = raw[p:p + nl].decode(); p += nl
|
||||
data = raw[p:p + dl]; p += dl
|
||||
ents = []
|
||||
for _ in range(ne):
|
||||
w, h, pl = struct.unpack("<III", raw[p:p + 12]); p += 12
|
||||
ents.append({"width": w, "height": h, "rgba": raw[p:p + pl]}); p += pl
|
||||
cases.append({"name": name, "data": data, "entries": ents})
|
||||
ctx.emit("ico", cases)
|
||||
@@ -0,0 +1,93 @@
|
||||
# Netpbm fixtures (tools/fixtures.py): files written by ImageMagick (P1-P7, ASCII / binary, 8 / 16-bit, PAM tuple
|
||||
# types, PFM both byte orders) and a few hand-written edge cases (comments, packed P1 digits, odd maxvals, PAM
|
||||
# GRAYSCALE_ALPHA / BLACKANDWHITE); references = ImageMagick's RGBA decodes (8-bit, and 16-bit for 16-bit files).
|
||||
# tests/gen/pnm.luau { { name, data, width, height, rgba8 (bytes), rgba16? (bytes, big-endian), tol, floats? } }
|
||||
import os, random, shutil, struct, subprocess, tempfile
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
|
||||
work = tempfile.mkdtemp(prefix="formats-pnm-")
|
||||
try:
|
||||
_generate(ctx, magick, work)
|
||||
finally:
|
||||
shutil.rmtree(work, ignore_errors=True)
|
||||
|
||||
|
||||
def _generate(ctx, magick, work):
|
||||
rng = random.Random(3)
|
||||
W = lambda n: os.path.join(work, n)
|
||||
|
||||
def run(*args, inp=None):
|
||||
r = subprocess.run([magick] + list(args), input=inp, capture_output=True)
|
||||
if r.returncode != 0:
|
||||
raise SystemExit("fixtures/pnm: magick %s failed: %s" % (" ".join(args), r.stderr.decode()))
|
||||
return r.stdout
|
||||
|
||||
# a 16-bit RGBA source with gradients, noise and transparency, written as a 16-bit PAM for ImageMagick
|
||||
w, h = 37, 23
|
||||
src = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
r = (x * 65535) // (w - 1)
|
||||
g = (y * 65535) // (h - 1)
|
||||
b = rng.randrange(65536)
|
||||
a = 65535 if (x + y) % 5 else (x * 3000) % 65536
|
||||
src += struct.pack(">HHHH", r, g, b, a)
|
||||
open(W("src.pam"), "wb").write(b"P7\nWIDTH %d\nHEIGHT %d\nDEPTH 4\nMAXVAL 65535\nTUPLTYPE RGB_ALPHA\nENDHDR\n" % (w, h) + bytes(src))
|
||||
|
||||
cases = []
|
||||
|
||||
def ref(path, wide, tol=0, floats=None, name=None):
|
||||
data = open(path, "rb").read()
|
||||
c = {"name": name or os.path.basename(path), "data": data, "tol": tol}
|
||||
info = run(path, "-format", "%w %h", "info:").decode().split()
|
||||
c["width"], c["height"] = int(info[0]), int(info[1])
|
||||
c["rgba8"] = run(path, "-depth", "8", "rgba:-")
|
||||
if wide:
|
||||
c["rgba16"] = run(path, "-depth", "16", "-endian", "MSB", "rgba:-")
|
||||
if floats is not None:
|
||||
c["floats"] = floats
|
||||
cases.append(c)
|
||||
|
||||
variants = [
|
||||
("p1.pbm", ["-colorspace", "gray", "-threshold", "50%", "-compress", "none"], "pbm:", False),
|
||||
("p4.pbm", ["-colorspace", "gray", "-threshold", "50%"], "pbm:", False),
|
||||
("p2.pgm", ["-colorspace", "gray", "-depth", "8", "-compress", "none"], "pgm:", False),
|
||||
("p5.pgm", ["-colorspace", "gray", "-depth", "8"], "pgm:", False),
|
||||
("p5-16.pgm", ["-colorspace", "gray", "-depth", "16"], "pgm:", True),
|
||||
("p2-16.pgm", ["-colorspace", "gray", "-depth", "16", "-compress", "none"], "pgm:", True),
|
||||
("p3.ppm", ["-alpha", "off", "-depth", "8", "-compress", "none"], "ppm:", False),
|
||||
("p6.ppm", ["-alpha", "off", "-depth", "8"], "ppm:", False),
|
||||
("p6-16.ppm", ["-alpha", "off", "-depth", "16"], "ppm:", True),
|
||||
("p3-16.ppm", ["-alpha", "off", "-depth", "16", "-compress", "none"], "ppm:", True),
|
||||
("rgba.pam", ["-depth", "8"], "pam:", False),
|
||||
("rgba16.pam", ["-depth", "16"], "pam:", True),
|
||||
("rgb.pam", ["-alpha", "off", "-depth", "8"], "pam:", False),
|
||||
("gray.pam", ["-alpha", "off", "-colorspace", "gray", "-depth", "8"], "pam:", False),
|
||||
("graya.pam", ["-colorspace", "gray", "-depth", "8"], "pam:", False),
|
||||
("graya16.pam", ["-colorspace", "gray", "-depth", "16"], "pam:", True),
|
||||
("bw.pam", ["-alpha", "off", "-colorspace", "gray", "-threshold", "50%", "-type", "bilevel"], "pam:", False),
|
||||
]
|
||||
for name, args, prefix, wide in variants:
|
||||
run(W("src.pam"), *args, prefix + W(name))
|
||||
ref(W(name), wide)
|
||||
for endian in ("LSB", "MSB"):
|
||||
for col in ("rgb", "gray"):
|
||||
name = "%s-%s.pfm" % (col, endian)
|
||||
extra = ["-colorspace", "gray"] if col == "gray" else []
|
||||
run(W("src.pam"), "-alpha", "off", *extra, "-endian", endian, "pfm:" + W(name))
|
||||
fl = run(W(name), "-depth", "32", "-define", "quantum:format=floating-point", "-endian", "LSB", "rgba:-")
|
||||
ref(W(name), False, tol=1, floats=fl)
|
||||
|
||||
# hand-written edge cases (references from ImageMagick too)
|
||||
def hand(name, data, wide=False, tol=0):
|
||||
open(W(name), "wb").write(data)
|
||||
ref(W(name), wide, tol=tol)
|
||||
hand("comments.ppm", b"P6\n# a comment\n3 # inline\n2\n#another\n255\n" + bytes(range(18)))
|
||||
hand("packed.pbm", b"P1\n5 3\n10101\n01010\n1 1 1 0 0\n")
|
||||
hand("maxval1000.pgm", b"P2\n4 2\n1000\n0 250 500 1000\n999 1 333 750\n", wide=True, tol=1)
|
||||
hand("maxval7.ppm", b"P3 2 2 7 0 1 2 3 4 5 6 7 7 7 0 0\n", tol=1)
|
||||
hand("p4-odd.pbm", b"P4\n11 3\n" + bytes([0b10101010, 0b11100000, 0b00001111, 0b00100000, 0b11111111, 0b11000000]))
|
||||
hand("graya-hand.pam", b"P7\nWIDTH 2\nHEIGHT 2\nDEPTH 2\nMAXVAL 255\nTUPLTYPE GRAYSCALE_ALPHA\nENDHDR\n" + bytes([0, 255, 100, 128, 200, 0, 255, 255]))
|
||||
ctx.emit("pnm", cases)
|
||||
@@ -0,0 +1,64 @@
|
||||
# QOI fixtures (tools/fixtures.py): Pillow's QOI writer and reader.
|
||||
# tests/gen/qoi.luau { { name, width, height, mode, pixels (source bytes, RGB or RGBA), data (Pillow's .qoi), crc
|
||||
# (CRC-32 of Pillow's RGBA decode) } }
|
||||
# tests/gen/qoi_bench.luau { width, height, pixels (RGBA), data }
|
||||
import struct
|
||||
|
||||
CODE = r'''
|
||||
import io, random, struct, sys, zlib
|
||||
from PIL import Image
|
||||
rng = random.Random(11)
|
||||
def make(w, h, mode, kind):
|
||||
n = len(mode)
|
||||
px = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
if kind == "noise":
|
||||
v = [rng.randrange(256) for _ in range(n)]
|
||||
elif kind == "grad":
|
||||
v = [(x * 3 + y) % 256, (y * 5) % 256, (x + y * 2) % 256, 255 - (x % 7) * 30][:n]
|
||||
elif kind == "flat":
|
||||
v = [10, 200, 30, 255][:n] if (x // 9 + y // 7) % 2 else [10, 200, 31, 128][:n]
|
||||
else: # small deltas around a walk, with an occasional jump
|
||||
base = (x * 2 + y) % 256
|
||||
v = [(base + rng.randrange(-2, 2)) % 256, (base + rng.randrange(-30, 30)) % 256, (base + rng.randrange(-9, 9)) % 256, 255 if rng.random() < 0.9 else rng.randrange(256)][:n]
|
||||
px += bytes(v)
|
||||
return bytes(px)
|
||||
out = []
|
||||
for (w, h, mode, kind) in ((1, 1, "RGB", "noise"), (1, 1, "RGBA", "noise"), (3, 2, "RGBA", "grad"), (64, 48, "RGB", "grad"),
|
||||
(64, 48, "RGBA", "grad"), (100, 37, "RGB", "noise"), (100, 37, "RGBA", "noise"),
|
||||
(200, 150, "RGBA", "flat"), (200, 150, "RGB", "flat"), (128, 99, "RGBA", "walk"), (128, 99, "RGB", "walk"),
|
||||
(500, 1, "RGBA", "flat"), (1, 300, "RGB", "walk")):
|
||||
px = make(w, h, mode, kind)
|
||||
im = Image.frombytes(mode, (w, h), px)
|
||||
b = io.BytesIO(); im.save(b, "QOI"); data = b.getvalue()
|
||||
back = Image.open(io.BytesIO(data)).convert("RGBA").tobytes()
|
||||
name = "%dx%d-%s-%s" % (w, h, mode, kind)
|
||||
sys.stdout.buffer.write(struct.pack("<HIIB", len(name), w, h, len(mode)) + name.encode() + struct.pack("<III", len(px), len(data), zlib.crc32(back)) + px + data)
|
||||
# bench: 1024 x 768 RGBA walk image
|
||||
w, h = 1024, 768
|
||||
px = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
base = (x // 4 + y // 3) % 256
|
||||
px += bytes(((base + (x * y) % 5) % 256, (base * 2) % 256, (255 - base + x % 3) % 256, 255))
|
||||
b = io.BytesIO(); Image.frombytes("RGBA", (w, h), bytes(px)).save(b, "QOI")
|
||||
sys.stdout.buffer.write(struct.pack("<HIIB", 0, w, h, 4) + struct.pack("<III", len(px), len(b.getvalue()), 0) + bytes(px) + b.getvalue())
|
||||
'''
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
raw = ctx.python(["pillow"], CODE)
|
||||
cases, p, bench = [], 0, None
|
||||
while p < len(raw):
|
||||
nl, w, h, ch = struct.unpack("<HIIB", raw[p:p + 11]); p += 11
|
||||
name = raw[p:p + nl].decode(); p += nl
|
||||
pl, dl, crc = struct.unpack("<III", raw[p:p + 12]); p += 12
|
||||
px, data = raw[p:p + pl], raw[p + pl:p + pl + dl]; p += pl + dl
|
||||
e = {"name": name, "width": w, "height": h, "channels": ch, "pixels": px, "data": data, "crc": crc}
|
||||
if nl == 0:
|
||||
bench = e
|
||||
else:
|
||||
cases.append(e)
|
||||
ctx.emit("qoi", cases)
|
||||
ctx.emit("qoi_bench", bench)
|
||||
@@ -0,0 +1,87 @@
|
||||
# TGA fixtures (tools/fixtures.py): files written by Pillow (RGB / RGBA / L / P / LA, raw and RLE, both origins) and
|
||||
# ImageMagick (raw / RLE, palette, grey), plus hand-written ones (15 / 16-bit pixels and colour maps, 8 / 16-bit
|
||||
# indexes with a first index, right-to-left, RLE packets crossing rows, an image ID, 16-bit grey + alpha);
|
||||
# references = Pillow's RGBA decodes, ImageMagick's for the files Pillow
|
||||
# refuses (right-to-left, 16-bit grey + alpha) and for 15 / 16-bit colour, where Pillow differs (5-bit scaling, alpha).
|
||||
# tests/gen/tga.luau { { name, data, width, height, rgba (bytes) } }
|
||||
import struct
|
||||
|
||||
CODE = r'''
|
||||
import io, os, random, struct, subprocess, sys
|
||||
from PIL import Image
|
||||
magick = sys.argv[1]
|
||||
rng = random.Random(9)
|
||||
out = []
|
||||
def emit(name, data, magick_ref=False):
|
||||
try:
|
||||
if magick_ref:
|
||||
raise ValueError("15 / 16-bit: Pillow scales 5-bit values by x * 255 // 31 and inverts the alpha bit")
|
||||
im = Image.open(io.BytesIO(data))
|
||||
rgba = im.convert("RGBA").tobytes()
|
||||
size = im.size
|
||||
except Exception:
|
||||
# files Pillow refuses (right-to-left, 16-bit grey + alpha): ImageMagick's decode
|
||||
info = subprocess.run([magick, "tga:-", "-format", "%w %h", "info:"], input=data, capture_output=True, check=True).stdout.split()
|
||||
size = (int(info[0]), int(info[1]))
|
||||
rgba = subprocess.run([magick, "tga:-", "-depth", "8", "rgba:-"], input=data, capture_output=True, check=True).stdout
|
||||
out.append((name, data, size, rgba))
|
||||
w, h = 29, 17
|
||||
px = bytearray()
|
||||
for y in range(h):
|
||||
for x in range(w):
|
||||
a = 255 if (x + y) % 4 else (x * 37) % 256
|
||||
px += bytes(((x * 9) % 256, (y * 15) % 256, rng.randrange(256) if x % 3 == 0 else 100, a))
|
||||
rgba = Image.frombytes("RGBA", (w, h), bytes(px))
|
||||
for mode in ("RGB", "RGBA", "L", "LA", "P"):
|
||||
im = rgba.convert(mode) if mode != "P" else rgba.convert("RGB").quantize(37)
|
||||
for comp in (None, "tga_rle"):
|
||||
for orient in (1, -1):
|
||||
b = io.BytesIO()
|
||||
kw = {"orientation": orient}
|
||||
if comp:
|
||||
kw["compression"] = comp
|
||||
im.save(b, "TGA", **kw)
|
||||
emit("pil-%s-%s-%s" % (mode, comp or "raw", "top" if orient == 1 else "bottom"), b.getvalue())
|
||||
# runs that cross rows (RLE)
|
||||
flat = Image.new("RGB", (13, 9), (10, 20, 30))
|
||||
for x in range(5):
|
||||
flat.putpixel((x, 4), (200, 0, 0))
|
||||
b = io.BytesIO(); flat.save(b, "TGA", compression="tga_rle"); emit("pil-runs", b.getvalue())
|
||||
# ImageMagick writers
|
||||
src = io.BytesIO(); rgba.save(src, "PNG")
|
||||
for name, args in (("im-rgba", []), ("im-rle", ["-compress", "RLE"]), ("im-gray", ["-colorspace", "gray"]), ("im-palette", ["-colors", "20", "-type", "Palette"]),
|
||||
("im-rgb", ["-alpha", "off"])):
|
||||
r = subprocess.run([magick, "png:-"] + args + ["tga:-"], input=src.getvalue(), capture_output=True, check=True)
|
||||
emit(name, r.stdout)
|
||||
# hand-written
|
||||
def hdr(idlen, cmt, it, cfirst, clen, cbits, w, h, depth, desc):
|
||||
return struct.pack("<BBBHHBHHHHBB", idlen, cmt, it, cfirst, clen, cbits, 0, 0, w, h, depth, desc)
|
||||
def p15(r, g, b, a=1):
|
||||
return struct.pack("<H", (a << 15) | ((r >> 3) << 10) | ((g >> 3) << 5) | (b >> 3))
|
||||
cols = [((i * 40) % 256, (i * 90) % 256, (255 - i * 20) % 256) for i in range(12)]
|
||||
w, h = 6, 4
|
||||
idx = [(x + y * 2) % 12 for y in range(h) for x in range(w)]
|
||||
emit("hand-16bit", hdr(0, 0, 2, 0, 0, 0, w, h, 16, 0) + b"".join(p15(*cols[i]) for i in idx), magick_ref=True)
|
||||
emit("hand-15bit-rtl", hdr(0, 0, 2, 0, 0, 0, w, h, 15, 0x10) + b"".join(p15(*cols[i], a=0) for i in idx), magick_ref=True)
|
||||
emit("hand-cmap16", hdr(0, 1, 1, 0, 12, 16, w, h, 8, 0x20) + b"".join(p15(*c) for c in cols) + bytes(idx), magick_ref=True)
|
||||
emit("hand-cmap32-first", hdr(0, 1, 1, 4, 12, 32, w, h, 8, 0x28) + b"".join(bytes((c[2], c[1], c[0], 77)) for c in cols) + bytes(i + 4 for i in idx))
|
||||
emit("hand-cmap24-rle", hdr(0, 1, 9, 0, 12, 24, w, h, 8, 0) + b"".join(bytes((c[2], c[1], c[0])) for c in cols) + bytes([0x80 + 9, 3, 0x05, 1, 2, 3, 4, 5, 6, 0x80 + 7, 11]))
|
||||
emit("hand-id-top", hdr(5, 0, 3, 0, 0, 0, w, h, 8, 0x20) + b"hello" + bytes((i * 21) % 256 for i in idx))
|
||||
emit("hand-graya16", hdr(0, 0, 3, 0, 0, 0, w, h, 16, 0x28) + b"".join(bytes(((i * 21) % 256, (i * 50) % 256)) for i in idx))
|
||||
emit("hand-rle32-cross", hdr(0, 0, 10, 0, 0, 0, 5, 3, 32, 0x28) + bytes([0x80 + 6, 1, 2, 3, 200, 0x08]) + bytes(range(9 * 4)))
|
||||
for name, data, size, rgba in out:
|
||||
sys.stdout.buffer.write(struct.pack("<HIIII", len(name), len(data), size[0], size[1], len(rgba)) + name.encode() + data + rgba)
|
||||
'''
|
||||
|
||||
|
||||
def generate(ctx):
|
||||
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
|
||||
raw = ctx.python(["pillow"], CODE.replace("sys.argv[1]", repr(magick)))
|
||||
cases, p = [], 0
|
||||
while p < len(raw):
|
||||
nl, dl, w, h, rl = struct.unpack("<HIIII", raw[p:p + 18]); p += 18
|
||||
name = raw[p:p + nl].decode(); p += nl
|
||||
data = raw[p:p + dl]; p += dl
|
||||
rgba = raw[p:p + rl]; p += rl
|
||||
cases.append({"name": name, "data": data, "width": w, "height": h, "rgba": rgba})
|
||||
ctx.emit("tga", cases)
|
||||
Reference in new issue
Block a user