227 lines
11 KiB
Python
227 lines
11 KiB
Python
# 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]}})
|