merge ws/imgA: jpeg gif tiff tga qoi pnm ico hdr, codecs Dct/Lzw/Quantize, ops/ImageOps, api image hooks

This commit is contained in:
4DBug committed 2026-10-31 09:00:39 -05:00
commit 2db77a7db8
55 files changed
+13401 -2

No files matched your search

+159
View File
@@ -230,5 +230,164 @@ do
end)
bench("yaml encode", 3, #YB.text, function()
Yaml.encode(v)
-- ------------------------------------------------------------------------------------------------ jpeg (ws-imgA)
do
local Jpeg = require("@formats/image/jpeg")
local Types = require("@formats/Types")
local JB = require("@tests/gen/jpeg_bench")
for _, c in JB.files do
local b = buffer.fromstring(c.data)
local img = Jpeg.decode(Bytes.reader(b))
assert(img and Crc32.of(img.pixels) == c.crc, "jpeg bench: " .. c.name .. " does not match djpeg")
bench("jpeg decode " .. c.name, 3, c.width * c.height * 4, function()
Jpeg.decode(Bytes.reader(b))
end)
end
local b0 = buffer.fromstring(JB.files[1].data)
bench("jpeg decode 1/8 (DC only)", 3, JB.width * JB.height * 4, function()
Jpeg.decode(Bytes.reader(b0), { scale = 8 })
end)
local src = Types.Image.new(JB.width, JB.height, "rgb8")
buffer.writestring(src.pixels, 0, JB.rgb)
for _, o in { { label = "baseline 4:2:0 q85", quality = 85 }, { label = "progressive 4:2:0 q85", quality = 85, progressive = true }, { label = "baseline 4:4:4 q85 optimized", quality = 85, subsampling = "444", optimize = true } } do
bench("jpeg encode " .. o.label, 2, JB.width * JB.height * 3, function()
Jpeg.encode(src, o :: any)
end)
end
end
-- ---------------------------------------------------------------------------------------- ws-imgA: gif + quantize
do
local Gif = require("@formats/image/gif")
local Quantize = require("@formats/codecs/Quantize")
local Types = require("@formats/Types")
local GB = require("@tests/gen/gif_bench")
local still = buffer.fromstring(GB.still)
local anim = buffer.fromstring(GB.anim)
local simg = assert(Gif.decode(Bytes.reader(still)))
local aimg = assert(Gif.decode(Bytes.reader(anim)))
local sw, sh = simg.width, simg.height
bench("gif decode 512x384", 5, sw * sh * 4, function()
Gif.decode(Bytes.reader(still))
end)
bench("gif decode 40 x 128x128 anim", 3, #(aimg.frames :: any) * 128 * 128 * 4, function()
Gif.decode(Bytes.reader(anim))
end)
bench("gif encode 512x384 (exact pal)", 3, sw * sh * 4, function()
Gif.encode(simg)
end)
local photo = Types.Image.new(sw, sh)
for i = 0, sw * sh - 1 do
local x, y = i % sw, i // sw
buffer.writeu32(photo.pixels, i * 4, (x % 256) + (y % 256) * 256 + ((x * y) % 256) * 65536 + 0xFF000000)
end
bench("quantize mediancut 256", 3, sw * sh * 4, function()
Quantize.palette(photo.pixels, sw, sh, 256)
end)
bench("quantize octree 256", 3, sw * sh * 4, function()
Quantize.palette(photo.pixels, sw, sh, 256, { method = "octree" })
end)
local pal = Quantize.palette(photo.pixels, sw, sh, 256)
bench("quantize map", 3, sw * sh * 4, function()
Quantize.map(photo.pixels, sw, sh, pal)
end)
bench("quantize map + dither", 3, sw * sh * 4, function()
Quantize.map(photo.pixels, sw, sh, pal, { dither = true })
end)
bench("gif encode 512x384 (quantize)", 2, sw * sh * 4, function()
Gif.encode(photo)
end)
end
-- ------------------------------------------------------------------------------------------------ ops/ImageOps
do
local Ops = require("@formats/ops/ImageOps")
local img = assert(Png.decode(Bytes.reader(buffer.fromstring(PB[1].data))))
local n = img.width * img.height * 4
bench("imageops resize 1/2 bilinear", 2, n, function()
Ops.resize(img, img.width // 2, img.height // 2, "bilinear")
end)
bench("imageops resize 1/2 lanczos", 2, n, function()
Ops.resize(img, img.width // 2, img.height // 2, "lanczos")
end)
bench("imageops resize x1.5 bilinear", 1, n, function()
Ops.resize(img, img.width * 3 // 2, img.height * 3 // 2, "bilinear")
end)
bench("imageops rotate 30 (expand)", 1, n, function()
Ops.rotate(img, 30)
end)
bench("imageops rotate90", 3, n, function()
Ops.rotate90(img, 1)
end)
bench("imageops convert rgba8 -> gray8", 3, n, function()
Ops.convert(img, "gray8")
end)
local other = assert(Ops.flip(img, "h"))
bench("imageops composite over", 3, n, function()
Ops.composite(img, other)
end)
end
-- ------------------------------------------------------------------------------------------------ image/tiff (ws-imgA)
do
local Tiff = require("@formats/image/tiff")
local Types = require("@formats/Types")
local src = Types.Image.new(1024, 768)
for i = 0, 1024 * 768 - 1 do
local x, y = i % 1024, i // 1024
buffer.writeu32(src.pixels, i * 4, 0xFF000000 + (x % 256) + ((y % 256) * 256) + (((x + y) // 4 % 256) * 65536))
end
for _, comp in { "none", "lzw", "deflate" } do
local enc = Tiff.encode(src, { compression = comp :: any }) :: buffer
bench("tiff decode rgba8 " .. comp, 3, 1024 * 768 * 4, function()
Tiff.decode(Bytes.reader(enc))
end)
bench("tiff encode rgba8 " .. comp, 2, 1024 * 768 * 4, function()
Tiff.encode(src, { compression = comp :: any })
end)
end
local enc16 = Tiff.encode(Types.Image.new(1024, 768, "rgba16"), { compression = "lzw" }) :: buffer
bench("tiff decode rgba16 lzw -> rgba8", 3, 1024 * 768 * 8, function()
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
+133
View File
@@ -0,0 +1,133 @@
# GIF fixtures (tools/fixtures.py): GIFs written by ImageMagick and Pillow (static, interlaced, 2..256 colours, grey,
# transparency, animations with every disposal method, sub-rectangle frames, local colour tables, loop counts,
# comments), each with ImageMagick's decode of every frame as the reference.
# tests/gen/gif.luau { { name, data, width, height, loops, frames = { { w, h, x, y, delay, dispose, crc } },
# first = crc of the first frame on a transparent canvas, comment? } }
# tests/gen/gif_bench.luau a 512 x 384 photo-like GIF (256 colours) and a 40-frame 128 x 128 animation
# CRCs are of rgba8 with transparent pixels (alpha 0) zeroed to 0, 0, 0, 0. delay in centiseconds.
import os, struct, tempfile, zlib
PILLOW = r'''
import io, sys, random
from PIL import Image, ImageDraw
out = sys.argv[1]
rng = random.Random(4)
def frame(w, h, seed, alpha=False):
im = Image.new("RGBA", (w, h), (0, 0, 0, 0) if alpha else (seed * 40 % 256, 90, 200, 255))
d = ImageDraw.Draw(im)
for i in range(5):
x, y = rng.randrange(w), rng.randrange(h)
d.ellipse([x - 6, y - 6, x + 6, y + 6], fill=(rng.randrange(256), rng.randrange(256), seed * 60 % 256, 255))
return im
# animation with per-frame disposal, durations, loop
fr = [frame(48, 32, i) for i in range(4)]
fr[0].save(out + "/pil_anim.gif", save_all=True, append_images=fr[1:], duration=[50, 120, 70, 200], loop=2, disposal=[0, 1, 2, 3], optimize=False)
# transparent animation (sub-rectangles from Pillow's optimizer)
fr = [frame(40, 40, i, alpha=True) for i in range(5)]
fr[0].save(out + "/pil_alpha.gif", save_all=True, append_images=fr[1:], duration=80, loop=0, disposal=2)
# a static interlaced palette image with a comment
im = frame(61, 37, 9).convert("P", palette=Image.Palette.ADAPTIVE, colors=32)
im.save(out + "/pil_interlaced.gif", interlace=True, comment=b"made by tools/fixtures/gif.py")
# 1-bit and a 3-colour image (minimum code size 2)
Image.frombytes("L", (17, 9), bytes((x * 255 // 16) if (x + y) % 3 else 0 for y in range(9) for x in range(17))).convert("1").save(out + "/pil_1bit.gif")
im = Image.new("P", (23, 19)); im.putpalette([255, 0, 0, 0, 255, 0, 0, 0, 255])
im.putdata([(x * y) % 3 for y in range(19) for x in range(23)]); im.save(out + "/pil_3col.gif")
'''
def run_im(ctx, args):
return ctx.nix("imagemagick", ["magick"] + args)
def reference(ctx, path):
info = run_im(ctx, ["identify", "-format", "%w %h %X %Y %T %D %W %H %[comment]|", path]).decode("latin-1")
raw = run_im(ctx, [path, "rgba:-"])
frames, pos = [], 0
comment = None
for line in info.split("|"):
if not line.strip():
continue
parts = line.split(" ", 8)
w, h, x, y, delay = int(parts[0]), int(parts[1]), int(parts[2]), int(parts[3]), int(parts[4])
dispose = parts[5]
cw, ch = int(parts[6]), int(parts[7])
if len(parts) > 8 and parts[8]:
comment = parts[8]
px = bytearray(raw[pos:pos + w * h * 4]); pos += w * h * 4
for i in range(0, len(px), 4):
if px[i + 3] == 0:
px[i:i + 4] = b"\0\0\0\0"
frames.append({"w": w, "h": h, "x": x, "y": y, "delay": delay, "dispose": dispose.lower(), "px": bytes(px), "crc": zlib.crc32(bytes(px))})
assert pos == len(raw), (path, pos, len(raw))
# the first frame on a transparent canvas
f = frames[0]
canvas = bytearray(cw * ch * 4)
for yy in range(f["h"]):
for xx in range(f["w"]):
X, Y = f["x"] + xx, f["y"] + yy
if 0 <= X < cw and 0 <= Y < ch:
p = f["px"][(yy * f["w"] + xx) * 4:(yy * f["w"] + xx) * 4 + 4]
if p[3]:
canvas[(Y * cw + X) * 4:(Y * cw + X) * 4 + 4] = p
for f in frames:
del f["px"]
return cw, ch, frames, zlib.crc32(bytes(canvas)), comment
def loops_of(data):
i = data.find(b"NETSCAPE2.0")
if i < 0:
return None
return data[i + 13] | (data[i + 14] << 8)
def generate(ctx):
work = tempfile.mkdtemp(prefix="gif-fx-")
files = []
def im(name, args):
p = os.path.join(work, name + ".gif")
run_im(ctx, args + [p])
files.append((name, p))
im("rose", ["rose:"])
im("rose_2col", ["rose:", "-colors", "2"])
im("rose_16col_interlaced", ["rose:", "-colors", "16", "-interlace", "GIF"])
im("rose_dither", ["rose:", "-resize", "200%", "-dither", "FloydSteinberg", "-colors", "64"])
im("logo", ["logo:", "-resize", "30%"])
im("gray", ["-size", "64x40", "gradient:", "-colorspace", "gray"])
im("transparent", ["-size", "40x30", "xc:none", "-fill", "red", "-draw", "circle 20,15 20,5"])
for disp in ("None", "Background", "Previous"):
im("anim_" + disp.lower(), ["-delay", "7", "-dispose", disp, "-size", "30x20", "xc:red",
"-size", "10x8", "-page", "+5+4", "xc:blue", "-page", "+12+9", "xc:lime",
"-page", "+0+0", "-size", "6x6", "xc:yellow", "-loop", "3"])
# local colour tables: frames with different 256-colour palettes
im("anim_local", ["-delay", "20", "rose:", "(", "rose:", "-negate", ")", "(", "logo:", "-resize", "70x46!", ")", "-loop", "0"])
# optimised transparency animation
im("anim_optimized", ["-delay", "5", "-size", "50x50", "xc:white", "-fill", "black",
"(", "+clone", "-draw", "circle 10,10 10,5", ")", "(", "+clone", "-draw", "circle 30,30 30,24", ")",
"(", "+clone", "-draw", "circle 40,12 40,6", ")", "-layers", "OptimizeTransparency", "-loop", "0"])
ctx.python(["pillow"], "import sys; sys.argv = ['', %r]\n" % work + PILLOW)
for n in ("pil_anim", "pil_alpha", "pil_interlaced", "pil_1bit", "pil_3col"):
files.append((n, os.path.join(work, n + ".gif")))
cases = []
for name, p in files:
data = open(p, "rb").read()
cw, ch, frames, first, comment = reference(ctx, p)
c = {"name": name, "data": data, "width": cw, "height": ch, "frames": frames, "first": first}
lp = loops_of(data)
if lp is not None:
c["loops"] = lp # the raw NETSCAPE2.0 repeat value
if comment:
c["comment"] = comment
cases.append(c)
ctx.emit("gif", cases)
bench = os.path.join(work, "bench.gif")
run_im(ctx, ["-size", "512x384", "-seed", "3", "plasma:fractal", "-colors", "256", bench])
anim = os.path.join(work, "bench_anim.gif")
args = ["-delay", "4"]
for i in range(40):
args += ["(", "-size", "128x128", "radial-gradient:", "-roll", "+%d+%d" % (i * 3, i * 2), ")"]
run_im(ctx, args + ["-colors", "128", "-loop", "0", anim])
ctx.emit("gif_bench", {"still": open(bench, "rb").read(), "anim": open(anim, "rb").read()})
+93
View File
@@ -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)
+93
View File
@@ -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)
+65
View File
@@ -0,0 +1,65 @@
# ImageOps fixtures (tools/fixtures.py): Pillow references for ops/ImageOps.
# tests/gen/imageops.luau { rgb = { w, h, px }, rgba = {...}, rgba2 = {...}, gray = L bytes of rgb,
# resize = { { filter, mode, w, h, px } }, rotate = { { angle, expand, w, h, px } },
# composite = bytes }
# rgb / rgba: smooth gradients + noise + shapes (Pillow drawing), deterministic.
import struct
CODE = r'''
import random, struct, sys
from PIL import Image, ImageDraw
rng = random.Random(11)
def src(w, h, mode):
im = Image.new("RGBA", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = ((x * 255) // (w - 1), (y * 255) // (h - 1), (x * y) % 256, 255 if mode == "RGB" else (x * 7 + y * 3) % 256)
d = ImageDraw.Draw(im)
for _ in range(5):
x0, y0 = rng.randrange(w), rng.randrange(h)
d.ellipse([x0, y0, x0 + rng.randrange(4, 20), y0 + rng.randrange(4, 20)], fill=(rng.randrange(256), rng.randrange(256), rng.randrange(256), 255 if mode == "RGB" else rng.randrange(256)))
return im.convert(mode)
out = []
def emit(tag, *parts):
data = b"".join(parts)
out.append(struct.pack("<16sI", tag.encode().ljust(16), len(data)) + data)
rgb = src(61, 47, "RGB"); rgba = src(61, 47, "RGBA"); rgba2 = src(61, 47, "RGBA")
hdr = lambda im: struct.pack("<II", *im.size)
emit("rgb", hdr(rgb), rgb.tobytes()); emit("rgba", hdr(rgba), rgba.tobytes()); emit("rgba2", hdr(rgba2), rgba2.tobytes())
emit("gray", rgb.convert("L").tobytes())
emit("graya", rgba.convert("L").tobytes())
F = {"nearest": Image.NEAREST, "bilinear": Image.BILINEAR, "lanczos": Image.LANCZOS}
for fname, f in F.items():
for (w, h) in ((30, 20), (100, 80), (61, 20), (13, 47), (7, 3), (200, 150)):
for mode in ("RGB", "L"):
r = rgb.convert(mode).resize((w, h), f)
emit("resize", struct.pack("<16s4sII", fname.encode().ljust(16), mode.encode().ljust(4), w, h), r.tobytes())
for angle, expand in ((30, True), (-45, True), (123.4, True), (17, False), (200, False)):
r = rgba.rotate(angle, Image.BILINEAR, expand=expand)
emit("rotate", struct.pack("<dBII", angle, 1 if expand else 0, *r.size), r.tobytes())
emit("composite", Image.alpha_composite(rgba, rgba2).tobytes())
sys.stdout.buffer.write(b"".join(out))
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
p = 0
fx = {"resize": [], "rotate": []}
while p < len(raw):
tag, n = struct.unpack("<16sI", raw[p:p + 20]); p += 20
tag = tag.decode().strip()
data = raw[p:p + n]; p += n
if tag in ("rgb", "rgba", "rgba2"):
w, h = struct.unpack("<II", data[:8])
fx[tag] = {"w": w, "h": h, "px": data[8:]}
elif tag in ("gray", "graya", "composite"):
fx[tag] = data
elif tag == "resize":
f, mode, w, h = struct.unpack("<16s4sII", data[:28])
fx["resize"].append({"filter": f.decode().strip(), "mode": mode.decode().strip(), "w": w, "h": h, "px": data[28:]})
elif tag == "rotate":
a, e, w, h = struct.unpack("<dBII", data[:17])
fx["rotate"].append({"angle": a, "expand": bool(e), "w": w, "h": h, "px": data[17:]})
ctx.emit("imageops", fx)
+293
View File
@@ -0,0 +1,293 @@
# JPEG fixtures (tools/fixtures.py), against libjpeg-turbo's cjpeg / djpeg / jpegtran (nix libjpeg_turbo) and Pillow.
# Ported from jpeg-luau tools/fixtures.py; the TMDB test photos are replaced by ImageMagick's built-in images.
# tests/gen/jpeg_dec.luau { { name, data, err?, refs = { { scale, width, height, crc } } | cmyk = rgb bytes } }:
# cjpeg encodes of synthetic and photo-like sources at every quality / sampling /
# progression / restart / colour setting, arithmetic-coded (sequential, progressive,
# restarts, grey, 12-bit), jpegtran transcodes, stripped DHT, odd sizes, 12-bit, CMYK /
# YCCK (Pillow); references = djpeg -dct int decodes at 1, 1/2, 1/4, 1/8 (CRC-32 of the
# RGBA8 pixels), files that must be refused (lossless).
# tests/gen/jpeg_enc.luau { { name, width, height, format, pixels, opts, want } }: raw sources and what cjpeg writes
# for the same settings (our encoder must produce the same bytes).
# tests/gen/jpeg_bench.luau 1024 x 768 baseline / progressive / arithmetic files for tools/bench.luau.
import os, shutil, subprocess, tempfile, zlib
SOURCES = r'''
import os, random, sys
from PIL import Image, ImageDraw
out = sys.argv[1]
def synth(w, h, seed):
rnd = random.Random(seed)
im = Image.new("RGB", (w, h))
px = im.load()
for y in range(h):
for x in range(w):
px[x, y] = ((x * 255) // max(1, w - 1), (y * 255) // max(1, h - 1), ((x + y) * 7) % 256)
d = ImageDraw.Draw(im)
for _ in range(6):
x0, y0 = rnd.randrange(w), rnd.randrange(h)
x1, y1 = x0 + rnd.randrange(1, w // 2 + 2), y0 + rnd.randrange(1, h // 2 + 2)
col = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
if rnd.random() < 0.5:
d.ellipse([x0, y0, x1, y1], fill=col)
else:
d.line([x0, y0, x1, y1], fill=col, width=rnd.randrange(1, 4))
for _ in range(w * h // 20):
x, y = rnd.randrange(w), rnd.randrange(h)
px[x, y] = (rnd.randrange(256), rnd.randrange(256), rnd.randrange(256))
return im
synth(97, 71, 1).save(os.path.join(out, "synth.ppm"))
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
synth(w, h, w * 100 + h).save(os.path.join(out, "s%dx%d.ppm" % (w, h)))
photo = Image.open(os.path.join(out, "photo.ppm")).convert("RGB")
photo.convert("L").save(os.path.join(out, "photo.pgm"))
with open(os.path.join(out, "photo16.ppm"), "wb") as f:
f.write(b"P6\n160 120\n65535\n")
f.write(bytes(b for v in photo.tobytes() for b in ((v * 257) >> 8, (v * 257) & 255)))
cmyk = photo.convert("CMYK")
for name, kw in (("cmyk", {}), ("cmyk_prog", {"progressive": True})):
p = os.path.join(out, "photo_" + name + ".jpg")
cmyk.save(p, "JPEG", quality=90, **kw)
data = bytearray(open(p, "rb").read())
i = data.find(b"Adobe")
assert i > 0
data[i + 11] = 2
open(os.path.join(out, "photo_" + name.replace("cmyk", "ycck") + ".jpg"), "wb").write(data)
for n in (name, name.replace("cmyk", "ycck")):
im = Image.open(os.path.join(out, "photo_" + n + ".jpg"))
raw = im.tobytes()
rgb = bytearray()
for k in range(0, len(raw), 4):
c, m, y, kk = raw[k:k + 4]
kk = 255 - kk
rgb += bytes((((255 - c) * kk + 127) // 255, ((255 - m) * kk + 127) // 255, ((255 - y) * kk + 127) // 255))
open(os.path.join(out, "photo_" + n + ".ref"), "wb").write(rgb)
'''
SCANS = {
"spectral": "0,1,2: 0-0, 0, 0;\n0: 1-5, 0, 0;\n0: 6-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
"deepsa": (
"0,1,2: 0-0, 0, 2;\n0: 1-5, 0, 3;\n1: 1-63, 0, 1;\n2: 1-63, 0, 1;\n0: 6-63, 0, 3;\n"
"0: 1-63, 3, 2;\n0: 1-63, 2, 1;\n0: 1-63, 1, 0;\n1: 1-63, 1, 0;\n2: 1-63, 1, 0;\n"
"0,1,2: 0-0, 2, 1;\n0,1,2: 0-0, 1, 0;\n"
),
"seqsplit": "0: 0-63, 0, 0;\n1: 0-63, 0, 0;\n2: 0-63, 0, 0;\n",
"dcsplit": "0: 0-0, 0, 0;\n1: 0-0, 0, 0;\n2: 0-0, 0, 0;\n0: 1-63, 0, 0;\n1: 1-63, 0, 0;\n2: 1-63, 0, 0;\n",
}
SAMPLINGS = {"444": "1x1", "422": "2x1", "420": "2x2", "411": "4x1", "440": "1x2"}
def parse_pnm(data):
"""P5 / P6 -> w, h, RGB8 bytes (16-bit samples scaled as djpeg's 12-bit output)"""
fields, pos = [], 0
while len(fields) < 4:
while data[pos:pos + 1].isspace():
pos += 1
if data[pos:pos + 1] == b"#":
while data[pos:pos + 1] != b"\n":
pos += 1
continue
s = pos
while not data[pos:pos + 1].isspace():
pos += 1
fields.append(data[s:pos])
pos += 1
magic, w, h, mx = fields[0], int(fields[1]), int(fields[2]), int(fields[3])
ch = 3 if magic == b"P6" else 1
n = w * h * ch
if mx < 256:
px = data[pos:pos + n]
else:
raw = data[pos:pos + 2 * n]
px = bytes(((raw[2 * i] << 8 | raw[2 * i + 1]) * 255 + mx // 2) // mx for i in range(n))
if ch == 1:
px = bytes(v for v in px for _ in range(3))
return w, h, px
def rgba_crc(rgb):
out = bytearray(len(rgb) // 3 * 4)
out[0::4], out[1::4], out[2::4] = rgb[0::3], rgb[1::3], rgb[2::3]
out[3::4] = b"\xff" * (len(rgb) // 3)
return zlib.crc32(bytes(out))
def generate(ctx):
bindir = os.path.dirname(ctx.nix("libjpeg_turbo", ["sh", "-c", "command -v cjpeg"]).decode().strip())
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-jpeg-")
try:
_generate(ctx, bindir, magick, work)
finally:
shutil.rmtree(work, ignore_errors=True)
def _generate(ctx, bindir, magick, work):
def run(tool, *args):
exe = tool if os.path.isabs(tool) else os.path.join(bindir, tool)
r = subprocess.run([exe] + list(args), capture_output=True)
if r.returncode != 0:
raise SystemExit("fixtures/jpeg: %s %s failed: %s" % (tool, " ".join(args), r.stderr.decode()))
return r.stdout
W = lambda n: os.path.join(work, n)
# photo-like sources: ImageMagick's built-in rose, and a plasma fractal
run(magick, "rose:", "-resize", "160x120!", W("photo.ppm"))
run(magick, "-size", "1024x768", "-seed", "7", "plasma:fractal", "-blur", "0x1", W("big.ppm"))
ctx.python(["pillow"], SOURCES.replace("sys.argv[1]", repr(work)))
for k, v in SCANS.items():
with open(W(k + ".scans"), "w") as f:
f.write(v)
SRC = {"synth": W("synth.ppm"), "photo": W("photo.ppm"), "gray": W("photo.pgm"), "photo16": W("photo16.ppm")}
for w, h in ((1, 1), (7, 5), (17, 9), (33, 1), (1, 33), (16, 16)):
SRC["%dx%d" % (w, h)] = W("s%dx%d.ppm" % (w, h))
cases = [] # (name, path, scales | "cmyk", err)
def cj(name, src, *args, scales=(1, 2, 4, 8), err=None):
out = W(name + ".jpg")
run("cjpeg", *args, "-outfile", out, SRC[src])
cases.append((name, out, scales, err))
for q in (30, 90):
for sn, s in SAMPLINGS.items():
cj("photo_q%d_%s" % (q, sn), "photo", "-quality", str(q), "-sample", s)
cj("photo_q%d_%s_prog" % (q, sn), "photo", "-quality", str(q), "-sample", s, "-progressive")
for sn, s in SAMPLINGS.items():
cj("synth_q75_%s" % sn, "synth", "-quality", "75", "-sample", s)
cj("synth_q75_%s_prog" % sn, "synth", "-quality", "75", "-sample", s, "-progressive")
cj("photo_q100_420", "photo", "-quality", "100", "-sample", "2x2")
cj("photo_q100_420_prog", "photo", "-quality", "100", "-sample", "2x2", "-progressive")
cj("photo_q5_420", "photo", "-quality", "5", "-sample", "2x2")
cj("photo_q5_444_prog", "photo", "-quality", "5", "-sample", "1x1", "-progressive")
cj("photo_optimize", "photo", "-quality", "80", "-optimize")
cj("photo_s31", "photo", "-sample", "3x1,1x1,1x1")
cj("photo_s4242", "photo", "-sample", "4x2,1x1,1x1")
cj("photo_s222111", "photo", "-sample", "2x2,2x1,1x1")
cj("photo_s111222", "photo", "-sample", "1x1,2x2,2x2")
cj("photo_s1422", "photo", "-sample", "1x4,1x2,1x2", "-progressive")
cj("synth_s2222", "synth", "-sample", "2x2,2x2,2x2", "-scans", W("seqsplit.scans"))
cj("photo_rst1", "photo", "-sample", "2x2", "-restart", "1")
cj("photo_rst3b", "photo", "-sample", "2x2", "-restart", "3B")
cj("photo_rst1b_prog", "photo", "-sample", "2x2", "-restart", "1B", "-progressive")
cj("photo_rst2_prog444", "photo", "-sample", "1x1", "-restart", "2", "-progressive")
cj("photo_gray", "photo", "-grayscale")
cj("photo_gray_prog", "photo", "-grayscale", "-progressive")
cj("photo_gray_rst", "photo", "-grayscale", "-restart", "5B")
cj("photo_rgb", "photo", "-rgb")
cj("photo_rgb_prog", "photo", "-rgb", "-progressive")
for k in SCANS:
cj("photo_scans_" + k, "photo", "-sample", "2x2", "-scans", W(k + ".scans"))
cj("synth_scans_" + k, "synth", "-sample", "1x1", "-scans", W(k + ".scans"))
cj("photo_12bit_420", "photo16", "-precision", "12", "-sample", "2x2")
cj("photo_12bit_444_prog", "photo16", "-precision", "12", "-sample", "1x1", "-progressive")
cj("photo_12bit_gray", "photo16", "-precision", "12", "-grayscale")
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
cj("tiny_%s_420" % k, k, "-sample", "2x2")
cj("tiny_%s_422_prog" % k, k, "-sample", "2x1", "-progressive")
cj("tiny_%s_444" % k, k, "-sample", "1x1", "-quality", "95")
cj("tiny_%s_arith" % k, k, "-sample", "2x2", "-arithmetic")
# arithmetic coding
for sn in ("444", "420", "422"):
cj("photo_arith_%s" % sn, "photo", "-arithmetic", "-sample", SAMPLINGS[sn])
cj("photo_arith_%s_prog" % sn, "photo", "-arithmetic", "-progressive", "-sample", SAMPLINGS[sn])
cj("photo_arith_q5", "photo", "-arithmetic", "-quality", "5")
cj("photo_arith_q100_prog", "photo", "-arithmetic", "-progressive", "-quality", "100")
cj("photo_arith_rst", "photo", "-arithmetic", "-restart", "1")
cj("photo_arith_rst_prog", "photo", "-arithmetic", "-progressive", "-restart", "3B")
cj("photo_arith_gray", "photo", "-arithmetic", "-grayscale")
cj("photo_arith_gray_prog", "photo", "-arithmetic", "-grayscale", "-progressive")
cj("photo_arith_rgb", "photo", "-arithmetic", "-rgb")
cj("photo_arith_12bit", "photo16", "-arithmetic", "-precision", "12", "-sample", "2x2")
cj("photo_arith_12bit_prog", "photo16", "-arithmetic", "-precision", "12", "-progressive")
cj("synth_arith_deepsa", "synth", "-arithmetic", "-sample", "1x1", "-scans", W("deepsa.scans"))
cj("synth_arith_spectral", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("spectral.scans"))
cj("synth_arith_seqsplit", "synth", "-arithmetic", "-sample", "2x2", "-scans", W("seqsplit.scans"))
# refused
cj("photo_lossless", "photo", "-lossless", "1", scales=(), err="lossless")
base = W("photo_q90_420.jpg")
for name, args in (("tran_prog", ["-progressive"]), ("tran_rst", ["-restart", "2B"]), ("tran_optimize", ["-optimize"]),
("tran_arith", ["-arithmetic"]), ("tran_arith_prog", ["-arithmetic", "-progressive"])):
out = W("photo_" + name + ".jpg")
run("jpegtran", *args, "-outfile", out, base)
cases.append(("photo_" + name, out, (1, 2, 4, 8), None))
# an arithmetic file back to Huffman
out = W("photo_tran_unarith.jpg")
run("jpegtran", "-outfile", out, W("photo_arith_420.jpg"))
cases.append(("photo_tran_unarith", out, (1, 2, 4, 8), None))
# stripped DHT: the standard tables
data = open(base, "rb").read()
out, pos = bytearray(data[:2]), 2
while pos < len(data):
m = data[pos + 1]
if m == 0xDA:
out += data[pos:]
break
ln = (data[pos + 2] << 8) | data[pos + 3]
if m != 0xC4:
out += data[pos:pos + 2 + ln]
pos += 2 + ln
open(W("photo_nodht.jpg"), "wb").write(bytes(out))
cases.append(("photo_nodht", W("photo_nodht.jpg"), (1, 2, 4, 8), None))
for n in ("cmyk", "cmyk_prog", "ycck", "ycck_prog"):
cases.append(("photo_" + n, W("photo_" + n + ".jpg"), "cmyk", None))
dec = []
for name, path, scales, err in cases:
e = {"name": name, "data": open(path, "rb").read()}
if err:
e["err"] = err
if scales == "cmyk":
e["cmyk"] = open(path[:-4] + ".ref", "rb").read()
else:
refs = []
for s in scales:
args = ["-dct", "int", "-pnm"] + (["-scale", "1/%d" % s] if s != 1 else []) + [path]
w, h, px = parse_pnm(run("djpeg", *args))
refs.append({"scale": s, "width": w, "height": h, "crc": rgba_crc(px)})
e["refs"] = refs
dec.append(e)
ctx.emit("jpeg_dec", dec)
# encoder: cjpeg's bytes for the same settings
enc = []
def ce(name, src, fmt, opts, *args):
out = W("enc_" + name + ".jpg")
run("cjpeg", "-baseline", *args, "-outfile", out, SRC[src])
w, h, px = parse_pnm(open(SRC[src], "rb").read())
if fmt == "gray8":
px = px[0::3]
enc.append({"name": name, "width": w, "height": h, "format": fmt, "pixels": px, "opts": opts,
"want": open(out, "rb").read()})
for q in (10, 50, 75, 90, 100):
ce("photo_q%d_420" % q, "photo", "rgb8", {"quality": q}, "-quality", str(q), "-sample", "2x2")
for sn in ("444", "422", "420"):
ce("photo_%s" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
ce("synth_%s" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn}, "-quality", "85", "-sample", SAMPLINGS[sn])
ce("photo_%s_prog" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
ce("synth_%s_prog" % sn, "synth", "rgb8", {"quality": 85, "subsampling": sn, "progressive": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-progressive")
ce("photo_%s_opt" % sn, "photo", "rgb8", {"quality": 85, "subsampling": sn, "optimize": True}, "-quality", "85", "-sample", SAMPLINGS[sn], "-optimize")
ce("photo_gray", "gray", "gray8", {"quality": 80}, "-quality", "80")
ce("photo_gray_prog", "gray", "gray8", {"quality": 80, "progressive": True}, "-quality", "80", "-progressive")
ce("photo_rgb_to_gray", "photo", "rgb8", {"quality": 80, "gray": True}, "-quality", "80", "-grayscale")
ce("photo_rst", "photo", "rgb8", {"quality": 75, "restart": 3}, "-quality", "75", "-sample", "2x2", "-restart", "3B")
ce("photo_rst_prog", "photo", "rgb8", {"quality": 75, "restart": 2, "progressive": True}, "-quality", "75", "-sample", "2x2", "-restart", "2B", "-progressive")
ce("photo_q100_prog444", "photo", "rgb8", {"quality": 100, "subsampling": "444", "progressive": True}, "-quality", "100", "-sample", "1x1", "-progressive")
for k in ("1x1", "7x5", "17x9", "33x1", "1x33", "16x16"):
ce("tiny_%s_420" % k, k, "rgb8", {"quality": 90}, "-quality", "90", "-sample", "2x2")
ce("tiny_%s_422_prog" % k, k, "rgb8", {"quality": 90, "subsampling": "422", "progressive": True}, "-quality", "90", "-sample", "2x1", "-progressive")
ctx.emit("jpeg_enc", enc)
SRC["big"] = W("big.ppm")
bench = []
for name, args in (("baseline 4:2:0", ["-sample", "2x2"]), ("progressive 4:2:0", ["-sample", "2x2", "-progressive"]),
("arithmetic 4:2:0", ["-sample", "2x2", "-arithmetic"]), ("baseline 4:4:4", ["-sample", "1x1"])):
out = W("bench.jpg")
run("cjpeg", "-quality", "85", *args, "-outfile", out, SRC["big"])
w, h, px = parse_pnm(run("djpeg", "-dct", "int", "-pnm", out))
bench.append({"name": name, "width": w, "height": h, "data": open(out, "rb").read(), "crc": rgba_crc(px)})
w, h, px = parse_pnm(open(SRC["big"], "rb").read())
ctx.emit("jpeg_bench", {"files": bench, "width": w, "height": h, "rgb": px})
+70
View File
@@ -0,0 +1,70 @@
# LZW fixtures (tools/fixtures.py): code streams written by reference encoders, with the data they encode.
# tests/gen/lzw.luau { gif = { { name, min, codes, data } }, tiff = { { name, codes, data } } }
# gif: Pillow's GIF writer (its own LZW), the image data sub-blocks joined; data = the palette indexes
# tiff: libtiff's LZW (Pillow compression="tiff_lzw"), one strip; data = the raw 8-bit samples
import struct
CODE = r'''
import io, random, struct, sys
from PIL import Image
rng = random.Random(7)
def img(w, h, kind, ncol):
px = bytearray()
for y in range(h):
for x in range(w):
if kind == "noise":
px.append(rng.randrange(ncol))
elif kind == "flat":
px.append(3 % ncol)
else:
px.append(((x // 3) ^ (y // 5)) % ncol if rng.random() < 0.97 else rng.randrange(ncol))
return bytes(px)
out = []
for (w, h, kind, ncol) in ((1, 1, "noise", 2), (16, 16, "noise", 2), (64, 48, "pattern", 4), (64, 48, "noise", 16),
(300, 200, "pattern", 256), (300, 200, "noise", 256), (256, 200, "flat", 256), (97, 3, "noise", 128)):
data = img(w, h, kind, ncol)
im = Image.frombytes("P", (w, h), data)
im.putpalette(bytes(range(256)) * 3)
b = io.BytesIO(); im.save(b, "GIF", optimize=False, interlace=False); g = b.getvalue()
# walk to the image descriptor
p = 13 + (3 << ((g[10] & 7) + 1) if g[10] & 0x80 else 0)
while g[p] != 0x2C:
p += 2
while g[p]: p += g[p] + 1
p += 1
flags = g[p + 9]; p += 10
if flags & 0x80: p += 3 << ((flags & 7) + 1)
mn = g[p]; p += 1; codes = bytearray()
while g[p]: codes += g[p + 1:p + 1 + g[p]]; p += g[p] + 1
# Pillow may reduce the palette: decode its own image back for the indexes
back = Image.open(io.BytesIO(g)); back.load()
out.append(("gif", "%dx%d-%s-%d" % (w, h, kind, ncol), mn, bytes(codes), back.tobytes()))
t = io.BytesIO()
Image.frombytes("L", (w, h), data).save(t, "TIFF", compression="tiff_lzw", rowsperstrip=h)
tb = t.getvalue()
le = tb[:2] == b"II"; E = "<" if le else ">"
ifd = struct.unpack(E + "I", tb[4:8])[0]; n = struct.unpack(E + "H", tb[ifd:ifd + 2])[0]
tags = {}
for i in range(n):
tag, typ, cnt, val = struct.unpack(E + "HHII", tb[ifd + 2 + i * 12: ifd + 14 + i * 12])
if typ == 3 and cnt == 1:
val = struct.unpack(E + "H", tb[ifd + 10 + i * 12: ifd + 12 + i * 12])[0]
tags[tag] = (val, cnt)
assert tags[259][0] == 5 and tags[273][1] == 1, "one LZW strip"
off, cnt = tags[273][0], tags[279][0]
out.append(("tiff", "%dx%d-%s-%d" % (w, h, kind, ncol), 8, tb[off:off + cnt], data))
for kind, name, mn, codes, data in out:
sys.stdout.buffer.write(struct.pack("<4sB", kind.ljust(4).encode(), len(name)) + name.encode() + struct.pack("<BII", mn, len(codes), len(data)) + codes + data)
'''
def generate(ctx):
raw = ctx.python(["pillow"], CODE)
gif, tiff, p = [], [], 0
while p < len(raw):
kind, nl = struct.unpack("<4sB", raw[p:p + 5]); p += 5
name = raw[p:p + nl].decode(); p += nl
mn, cl, dl = struct.unpack("<BII", raw[p:p + 9]); p += 9
codes, data = raw[p:p + cl], raw[p + cl:p + cl + dl]; p += cl + dl
(gif if kind.strip() == b"gif" else tiff).append({"name": name, "min": mn, "codes": codes, "data": data})
ctx.emit("lzw", {"gif": gif, "tiff": tiff})
+93
View File
@@ -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)
+64
View File
@@ -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)
+87
View File
@@ -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)
+226
View File
@@ -0,0 +1,226 @@
# TIFF fixtures (tools/fixtures.py): files written by tifffile (+ imagecodecs) and ImageMagick, with references from
# tifffile's decode (the native sample arrays) turned into what image/tiff must produce.
# tests/gen/tiff.luau { cases = { { name, data, width, height, pages = { { crc, native, ncrc } } } },
# jpeg = data (a JPEG-compressed TIFF for the decodeImage hook test),
# jpegRef = { width, height, rgb } (tifffile + imagecodecs' libjpeg-turbo decode of it) }
# crc CRC-32 of the default rgba8 decode
# native / ncrc: the opts.native pixel format and the CRC-32 of its little-endian bytes
# Every case is decoded by tifffile; the expected pixels follow image/tiff's rules: unsigned samples v / (2^bits - 1),
# floats as stored, min-is-white inverted, palette = ColorMap / 65535, CMYK r = (1 - c)(1 - k), associated alpha
# divided out, then 8-bit = floor(clamp(u) * 255 + 0.5) (16-bit: * 65535).
import os, shutil, struct, subprocess, tempfile
CODE = r'''
import os, struct, sys, zlib
import numpy as np, tifffile
work = WORK
magick = MAGICK
rng = np.random.default_rng(5)
H, W = 37, 53
yy, xx = np.mgrid[0:H, 0:W]
def ramp(maxv, ch):
base = [(xx * 7 + yy * 3) % 256, (xx * 255 // (W - 1)), (yy * 255 // (H - 1)), 255 - ((xx ^ yy) & 63)]
a = np.stack([b for b in base[:ch]], -1).astype(np.float64) / 255.0
noise = rng.random(a.shape) < 0.2
a = np.where(noise, rng.random(a.shape), a)
return np.squeeze(np.round(a * maxv))
cases = []
def add(name, path):
cases.append((name, path))
def tw(name, data, **kw):
p = os.path.join(work, name + ".tif")
tifffile.imwrite(p, data, **kw)
add(name, p)
rgb8 = ramp(255, 3).astype(np.uint8)
rgba8 = ramp(255, 4).astype(np.uint8)
gray8 = ramp(255, 1).astype(np.uint8)
gray16 = ramp(65535, 1).astype(np.uint16)
rgb16 = ramp(65535, 3).astype(np.uint16)
rgba16 = ramp(65535, 4).astype(np.uint16)
f32 = (ramp(1000, 3) / 1000.0 * 1.2 - 0.1).astype(np.float32)
for comp in (None, "lzw", "zlib", "adobe_deflate", "packbits"):
cn = comp or "none"
tw("rgb8_" + cn, rgb8, photometric="rgb", compression=comp)
tw("gray16_" + cn, gray16, photometric="minisblack", compression=comp)
for comp in ("lzw", "zlib"):
tw("rgb8_pred_" + comp, rgb8, photometric="rgb", compression=comp, predictor=True)
tw("rgba16_pred_be_" + comp, rgba16, photometric="rgb", compression=comp, predictor=True, byteorder=">", extrasamples=["unassalpha"])
tw("gray16_pred_" + comp, gray16, photometric="minisblack", compression=comp, predictor=True)
tw("f32_fpred_" + comp, f32, photometric="rgb", compression=comp, predictor=3)
tw("f32_fpred_be_" + comp, f32, photometric="rgb", compression=comp, predictor=3, byteorder=">")
tw("rgba8_assoc", rgba8, photometric="rgb", extrasamples=["assocalpha"])
tw("rgba8_unassoc_tiles", rgba8, photometric="rgb", extrasamples=["unassalpha"], tile=(16, 16), compression="zlib")
tw("rgb8_planar", np.ascontiguousarray(np.moveaxis(rgb8, -1, 0)), photometric="rgb", planarconfig="separate", compression="lzw")
tw("rgb16_planar_tiles_be", np.ascontiguousarray(np.moveaxis(rgb16, -1, 0)), photometric="rgb", planarconfig="separate", tile=(32, 16), byteorder=">", compression="zlib", predictor=True)
tw("rgb8_strips5", rgb8, photometric="rgb", rowsperstrip=5, compression="packbits")
tw("rgb8_bigtiff", rgb8, photometric="rgb", bigtiff=True, compression="zlib")
tw("rgb8_bigtiff_be_tiles", rgb8, photometric="rgb", bigtiff=True, byteorder=">", tile=(16, 32))
tw("gray8_miniswhite", gray8, photometric="miniswhite")
tw("gray8_be", gray8, photometric="minisblack", byteorder=">")
tw("f16_gray", (gray16 / 65535.0).astype(np.float16), photometric="minisblack")
tw("f64_rgb", (f32.astype(np.float64)), photometric="rgb")
tw("f32_gray_tiles", f32[:, :, 0].copy(), photometric="minisblack", tile=(16, 16), compression="zlib")
tw("int16_gray", (gray16.astype(np.int32) - 32768).astype(np.int16), photometric="minisblack")
tw("int8_gray", (gray8.astype(np.int16) - 128).astype(np.int8), photometric="minisblack")
tw("u32_gray", (gray16.astype(np.uint32) * 65537), photometric="minisblack", compression="zlib")
cm = (rng.integers(0, 65536, (3, 256))).astype(np.uint16)
tw("palette8", gray8, photometric="palette", colormap=cm, compression="lzw")
tw("gray4", (gray8 >> 4).astype(np.uint8), photometric="minisblack", bitspersample=4)
tw("gray2_lzw", (gray8 >> 6).astype(np.uint8), photometric="minisblack", bitspersample=2, compression=None)
tw("bilevel", gray8 > 127, photometric="minisblack")
tw("bilevel_white_packbits", gray8 > 100, photometric="miniswhite", compression="packbits")
tw("gray12", (gray16 >> 4).astype(np.uint16), photometric="minisblack", bitspersample=12)
tw("cmyk8", ramp(255, 4).astype(np.uint8), photometric="separated", compression="lzw")
tw("graya8", np.stack([gray8, rgba8[:, :, 3]], -1), photometric="minisblack", extrasamples=["unassalpha"])
with tifffile.TiffWriter(os.path.join(work, "pages3.tif")) as t:
t.write(rgb8, photometric="rgb", compression="zlib")
t.write(gray16, photometric="minisblack", compression="lzw")
t.write(rgba8, photometric="rgb", extrasamples=["unassalpha"])
add("pages3", os.path.join(work, "pages3.tif"))
# ImageMagick
import subprocess
src = os.path.join(work, "src.png")
from PIL import Image
Image.fromarray(rgba8, "RGBA").save(src)
srgb = os.path.join(work, "srgb.png")
Image.fromarray(rgb8, "RGB").save(srgb)
def im(name, *args, s=srgb):
p = os.path.join(work, name + ".tif")
subprocess.run([magick, s] + list(args) + [p], check=True, capture_output=True)
add(name, p)
im("im_lzw", "-compress", "LZW")
im("im_zip_pred", "-compress", "Zip", "-define", "tiff:predictor=2")
im("im_rle", "-compress", "RLE")
im("im_none_msb", "-compress", "None", "-endian", "MSB")
im("im_tiles", "-compress", "LZW", "-define", "tiff:tile-geometry=32x32")
im("im_plane", "-compress", "Zip", "-interlace", "plane")
im("im_16", "-depth", "16", "-compress", "LZW")
im("im_float", "-depth", "32", "-define", "quantum:format=floating-point", "-compress", "Zip")
im("im_alpha", "-compress", "LZW", s=src)
im("im_alpha_assoc", "-define", "tiff:alpha=associated", s=src)
im("im_gray4", "-colorspace", "gray", "-depth", "4")
im("im_bilevel", "-monochrome")
im("im_palette", "-type", "palette", "-compress", "LZW")
im("im_palette4", "-colors", "12", "-type", "palette", "-depth", "4")
im("im_cmyk", "-colorspace", "CMYK", "-compress", "LZW")
p = os.path.join(work, "im_multi.tif")
subprocess.run([magick, srgb, src, srgb, "-compress", "Zip", p], check=True, capture_output=True)
add("im_multi", p)
jp = os.path.join(work, "im_jpeg.tif")
subprocess.run([magick, srgb, "-compress", "JPEG", jp], check=True, capture_output=True)
def expect(page):
a = page.asarray()
spp = page.samplesperpixel
if spp > 1 and page.planarconfig == 2:
a = np.moveaxis(a, 0, -1)
if a.ndim == 2:
a = a[:, :, None]
a = a.reshape(page.imagelength, page.imagewidth, spp)
photo = int(page.photometric)
bps = page.bitspersample
fmt = int(page.sampleformat)
cc = 3 if photo in (2, 6) else (4 if photo == 5 else 1)
alpha = cc if spp > cc else -1
ex = page.extrasamples
assoc = alpha >= 0 and len(ex) > 0 and int(ex[0]) == 1
maxv = float(2 ** min(bps, 32) - 1)
if fmt == 3:
u = a.astype(np.float64)
elif fmt == 2:
u = (a.astype(np.float64) + 2 ** (bps - 1)) / maxv
else:
u = a.astype(np.float64) / maxv
if photo == 3:
cmap = page.colormap.astype(np.float64) / 65535.0
idx = a[:, :, 0].astype(np.int64)
rgb = np.stack([cmap[0][idx], cmap[1][idx], cmap[2][idx]], -1)
elif photo == 2:
rgb = u[:, :, 0:3]
elif photo == 5:
c, m, y, k = u[:, :, 0], u[:, :, 1], u[:, :, 2], u[:, :, 3]
rgb = np.stack([(1 - c) * (1 - k), (1 - m) * (1 - k), (1 - y) * (1 - k)], -1)
else:
v = u[:, :, 0]
if photo == 0:
v = 1 - v
rgb = np.stack([v, v, v], -1)
if alpha >= 0:
al = u[:, :, alpha]
if assoc:
safe = np.where(al > 0, al, 1)
rgb = np.where((al > 0)[:, :, None], np.minimum(rgb / safe[:, :, None], 1), 0)
else:
al = np.ones(rgb.shape[:2])
def q(x, m):
return np.floor(np.clip(np.nan_to_num(x), 0, 1) * m + 0.5)
rgba = np.concatenate([rgb, al[:, :, None]], -1)
out8 = q(rgba, 255).astype(np.uint8)
crc = zlib.crc32(out8.tobytes())
# native
if photo in (3, 5):
kind, nat = "rgba8", out8
elif fmt == 3:
kind, nat = "rgbaf32", rgba.astype("<f4")
elif cc == 1:
if alpha >= 0:
if bps <= 8:
kind, nat = "graya8", q(np.stack([rgb[:, :, 0], al], -1), 255).astype(np.uint8)
else:
kind, nat = "rgba16", q(rgba, 65535).astype("<u2")
else:
if bps <= 8:
kind, nat = "gray8", q(rgb[:, :, 0], 255).astype(np.uint8)
else:
kind, nat = "gray16", q(rgb[:, :, 0], 65535).astype("<u2")
else:
if bps <= 8:
kind, nat = ("rgba8", out8) if alpha >= 0 else ("rgb8", out8[:, :, 0:3].copy())
else:
kind, nat = "rgba16", q(rgba, 65535).astype("<u2")
return crc, kind, zlib.crc32(np.ascontiguousarray(nat).tobytes())
def emit(b):
sys.stdout.buffer.write(struct.pack("<I", len(b)) + b)
emit(str(len(cases)).encode())
for name, path in cases:
with tifffile.TiffFile(path) as t:
pages = [p for p in t.pages if not (int(p.subfiletype) & 1)]
info = []
for pg in pages:
info.append("%d:%s:%d" % expect(pg))
w, h = pages[0].imagewidth, pages[0].imagelength
emit(name.encode()); emit(open(path, "rb").read()); emit(("%d %d " % (w, h) + " ".join(info)).encode())
emit(open(jp, "rb").read())
with tifffile.TiffFile(jp) as t:
a = t.pages[0].asarray()
emit(("%d %d" % (a.shape[1], a.shape[0])).encode())
emit(np.ascontiguousarray(a[:, :, 0:3]).astype(np.uint8).tobytes())
'''
def generate(ctx):
magick = ctx.nix("imagemagick", ["sh", "-c", "command -v magick"]).decode().strip()
work = tempfile.mkdtemp(prefix="formats-tiff-")
try:
raw = ctx.python(["pillow", "tifffile", "numpy", "imagecodecs"], CODE.replace("WORK", repr(work)).replace("MAGICK", repr(magick)))
finally:
shutil.rmtree(work, ignore_errors=True)
p = 0
items = []
while p < len(raw):
n = struct.unpack("<I", raw[p:p + 4])[0]
items.append(raw[p + 4:p + 4 + n])
p += 4 + n
count = int(items[0])
cases = []
for i in range(count):
name, data, info = items[1 + i * 3], items[2 + i * 3], items[3 + i * 3].decode().split()
pages = []
for s in info[2:]:
crc, kind, ncrc = s.split(":")
pages.append({"crc": int(crc), "native": kind, "ncrc": int(ncrc)})
cases.append({"name": name.decode(), "data": data, "width": int(info[0]), "height": int(info[1]), "pages": pages})
jw, jh = map(int, items[2 + count * 3].decode().split())
ctx.emit("tiff", {"cases": cases, "jpeg": items[1 + count * 3],
"jpegRef": {"width": jw, "height": jh, "rgb": items[3 + count * 3]}})