imgA: merge ws/imgA-ops (ops/ImageOps)

This commit is contained in:
4DBug committed 2026-10-31 08:48:25 -05:00
commit 25cf9fa396
5 files changed
+1624

No files matched your search

+520
View File
@@ -0,0 +1,520 @@
--!strict
--!native
--!optimize 2
-- ops/ImageOps/Kernels: the hot loops behind ops/ImageOps (native; never throws). Every function trusts its caller
-- (ops/ImageOps validates sizes, formats and buffer lengths first), so all buffer indexes are in range by
-- construction. Samples are addressed by kind: 1 = u8, 2 = u16, 4 = f32 (little endian, as Types.Image buffers).
-- The resampling follows Pillow's Resample.c (separable convolution, horizontal pass first, filter support scaled by
-- the downscale ratio, 22-bit fixed-point coefficients for 8-bit samples) and Geometry.c (affine transforms through
-- pixel centres, bilinear with clamped neighbours); the alpha compositing is Pillow's AlphaComposite.c.
local readu8, writeu8, readu16, writeu16, readf32, writef32 = buffer.readu8, buffer.writeu8, buffer.readu16, buffer.writeu16, buffer.readf32, buffer.writef32
local floor, clamp = math.floor, math.clamp
local K = {}
-- format ids: rgba8 1, rgba16 2, rgbaf32 3, rgb8 4, gray8 5, gray16 6, graya8 7, alpha8 8
K.ID = { rgba8 = 1, rgba16 = 2, rgbaf32 = 3, rgb8 = 4, gray8 = 5, gray16 = 6, graya8 = 7, alpha8 = 8 }
K.KIND = { rgba8 = 1, rgba16 = 2, rgbaf32 = 4, rgb8 = 1, gray8 = 1, gray16 = 2, graya8 = 1, alpha8 = 1 }
K.CHANNELS = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, rgb8 = 3, gray8 = 1, gray16 = 1, graya8 = 2, alpha8 = 1 }
local function rd(b: buffer, o: number, kind: number): number
if kind == 1 then
return readu8(b, o)
elseif kind == 2 then
return readu16(b, o)
end
return readf32(b, o)
end
local function wr(b: buffer, o: number, kind: number, v: number)
if kind == 1 then
writeu8(b, o, clamp(floor(v + 0.5), 0, 255))
elseif kind == 2 then
writeu16(b, o, clamp(floor(v + 0.5), 0, 65535))
else
writef32(b, o, v)
end
end
-- ------------------------------------------------------------------------------------------------ convert
-- depth: 8 -> 0..255, 16 -> 0..65535, 0 -> float 0..1
local DEPTH = { 8, 16, 0, 8, 8, 16, 8, 8 }
local function depthConv(v: number, from: number, to: number): number
if from == to then
return v
end
if from == 8 then
if to == 16 then
return v * 257
end
return v / 255
elseif from == 16 then
if to == 8 then
return (v * 255 + 32767) // 65535
end
return v / 65535
end
-- float
if v ~= v then
v = 0
end
if to == 8 then
return clamp(floor(v * 255 + 0.5), 0, 255)
end
return clamp(floor(v * 65535 + 0.5), 0, 65535)
end
-- Pillow's L24 luma (19595 R + 38470 G + 7471 B + 0x8000) >> 16, in the source depth
local function luma(r: number, g: number, b: number, depth: number): number
if depth == 0 then
return (r * 19595 + g * 38470 + b * 7471) / 65536
end
return (r * 19595 + g * 38470 + b * 7471 + 32768) // 65536
end
function K.convert(src: buffer, sf: number, dst: buffer, df: number, n: number)
local sd, dd = DEPTH[sf], DEPTH[df]
local smax = if sd == 8 then 255 elseif sd == 16 then 65535 else 1
local toGray = df == 5 or df == 6 or df == 7
for i = 0, n - 1 do
local r, g, b, a
if sf == 1 then
local o = i * 4
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), readu8(src, o + 3)
elseif sf == 2 then
local o = i * 8
r, g, b, a = readu16(src, o), readu16(src, o + 2), readu16(src, o + 4), readu16(src, o + 6)
elseif sf == 3 then
local o = i * 16
r, g, b, a = readf32(src, o), readf32(src, o + 4), readf32(src, o + 8), readf32(src, o + 12)
elseif sf == 4 then
local o = i * 3
r, g, b, a = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2), 255
elseif sf == 5 then
local v = readu8(src, i)
r, g, b, a = v, v, v, 255
elseif sf == 6 then
local v = readu16(src, i * 2)
r, g, b, a = v, v, v, 65535
elseif sf == 7 then
local v = readu8(src, i * 2)
r, g, b, a = v, v, v, readu8(src, i * 2 + 1)
else
r, g, b, a = 255, 255, 255, readu8(src, i)
end
if toGray then
local isGray = sf == 5 or sf == 6 or sf == 7
local l = if isGray then r else luma(r, g, b, sd)
l = depthConv(l, sd, dd)
if df == 5 then
writeu8(dst, i, l)
elseif df == 6 then
writeu16(dst, i * 2, l)
else
writeu8(dst, i * 2, l)
writeu8(dst, i * 2 + 1, depthConv(a, sd, dd))
end
elseif df == 8 then
writeu8(dst, i, depthConv(a, sd, 8))
else
r, g, b = depthConv(r, sd, dd), depthConv(g, sd, dd), depthConv(b, sd, dd)
if df == 1 then
local o = i * 4
writeu8(dst, o, r)
writeu8(dst, o + 1, g)
writeu8(dst, o + 2, b)
writeu8(dst, o + 3, depthConv(a, sd, dd))
elseif df == 2 then
local o = i * 8
writeu16(dst, o, r)
writeu16(dst, o + 2, g)
writeu16(dst, o + 4, b)
writeu16(dst, o + 6, depthConv(a, sd, dd))
elseif df == 3 then
local o = i * 16
writef32(dst, o, r)
writef32(dst, o + 4, g)
writef32(dst, o + 8, b)
writef32(dst, o + 12, if a == smax and sd ~= 0 then 1 else depthConv(a, sd, dd))
else -- rgb8
local o = i * 3
writeu8(dst, o, r)
writeu8(dst, o + 1, g)
writeu8(dst, o + 2, b)
end
end
end
end
-- JPEG-style BT.601 full range
function K.rgbaToYuv(src: buffer, w: number, h: number, dst: buffer)
local cw, ch = (w + 1) // 2, (h + 1) // 2
local uo, vo = w * h, w * h + cw * ch
for i = 0, w * h - 1 do
local o = i * 4
local r, g, b = readu8(src, o), readu8(src, o + 1), readu8(src, o + 2)
writeu8(dst, i, clamp(floor(0.299 * r + 0.587 * g + 0.114 * b + 0.5), 0, 255))
end
for cy = 0, ch - 1 do
for cx = 0, cw - 1 do
local sr, sg, sb, n = 0, 0, 0, 0
for dy = 0, 1 do
local y = cy * 2 + dy
if y < h then
for dx = 0, 1 do
local x = cx * 2 + dx
if x < w then
local o = (y * w + x) * 4
sr += readu8(src, o)
sg += readu8(src, o + 1)
sb += readu8(src, o + 2)
n += 1
end
end
end
end
sr, sg, sb = sr / n, sg / n, sb / n
local i = cy * cw + cx
writeu8(dst, uo + i, clamp(floor(128 - 0.168736 * sr - 0.331264 * sg + 0.5 * sb + 0.5), 0, 255))
writeu8(dst, vo + i, clamp(floor(128 + 0.5 * sr - 0.418688 * sg - 0.081312 * sb + 0.5), 0, 255))
end
end
end
function K.yuvToRgba(src: buffer, w: number, h: number, dst: buffer)
local cw, ch = (w + 1) // 2, (h + 1) // 2
local uo, vo = w * h, w * h + cw * ch
for y = 0, h - 1 do
local crow = (y // 2) * cw
for x = 0, w - 1 do
local yy = readu8(src, y * w + x)
local ci = crow + x // 2
local u, v = readu8(src, uo + ci) - 128, readu8(src, vo + ci) - 128
local o = (y * w + x) * 4
writeu8(dst, o, clamp(floor(yy + 1.402 * v + 0.5), 0, 255))
writeu8(dst, o + 1, clamp(floor(yy - 0.344136 * u - 0.714136 * v + 0.5), 0, 255))
writeu8(dst, o + 2, clamp(floor(yy + 1.772 * u + 0.5), 0, 255))
writeu8(dst, o + 3, 255)
end
end
local _ = ch
end
-- ------------------------------------------------------------------------------------------------ geometry
-- flip(src, dst, w, h, bpp, horizontal)
function K.flip(src: buffer, dst: buffer, w: number, h: number, bpp: number, horizontal: boolean)
local stride = w * bpp
if not horizontal then
for y = 0, h - 1 do
buffer.copy(dst, (h - 1 - y) * stride, src, y * stride, stride)
end
return
end
for y = 0, h - 1 do
local row = y * stride
for x = 0, w - 1 do
buffer.copy(dst, row + (w - 1 - x) * bpp, src, row + x * bpp, bpp)
end
end
end
-- rotate90(src, dst, w, h, bpp, turns): counter-clockwise quarter turns 1..3
function K.rotate90(src: buffer, dst: buffer, w: number, h: number, bpp: number, turns: number)
for y = 0, h - 1 do
for x = 0, w - 1 do
local ox, oy, ow
if turns == 1 then
ox, oy, ow = y, w - 1 - x, h
elseif turns == 2 then
ox, oy, ow = w - 1 - x, h - 1 - y, w
else
ox, oy, ow = h - 1 - y, x, h
end
local so, d = (y * w + x) * bpp, (oy * ow + ox) * bpp
if bpp == 4 then
buffer.writeu32(dst, d, buffer.readu32(src, so))
else
buffer.copy(dst, d, src, so, bpp)
end
end
end
end
-- ------------------------------------------------------------------------------------------------ resample
local function bilinearF(x: number): number
if x < 0 then
x = -x
end
if x < 1 then
return 1 - x
end
return 0
end
local function sinc(x: number): number
if x == 0 then
return 1
end
x *= math.pi
return math.sin(x) / x
end
local function lanczosF(x: number): number
if x > -3 and x < 3 then
return sinc(x) * sinc(x / 3)
end
return 0
end
local function trunc(x: number): number
return if x < 0 then math.ceil(x) else floor(x)
end
-- Pillow precompute_coeffs: per output index its first input index, tap count and weights (normalised)
export type Coeffs = { start: { number }, count: { number }, weights: { { number } } }
function K.coeffs(inSize: number, outSize: number, filter: string): Coeffs
local support0 = if filter == "lanczos" then 3 else 1
local f = if filter == "lanczos" then lanczosF else bilinearF
local scale = inSize / outSize
local filterscale = math.max(scale, 1)
local support = support0 * filterscale
local ss = 1 / filterscale
local start, count, weights = table.create(outSize, 0), table.create(outSize, 0), table.create(outSize)
for xx = 0, outSize - 1 do
local center = (xx + 0.5) * scale
local xmin = math.max(0, trunc(center - support + 0.5))
local xmax = math.min(inSize, trunc(center + support + 0.5)) - xmin
local w = table.create(math.max(xmax, 0), 0)
local ww = 0
for x = 0, xmax - 1 do
local v = f((x + xmin - center + 0.5) * ss)
w[x + 1] = v
ww += v
end
if ww ~= 0 then
for x = 1, xmax do
w[x] /= ww
end
end
start[xx + 1], count[xx + 1], weights[xx + 1] = xmin, math.max(xmax, 0), w
end
return { start = start, count = count, weights = weights }
end
-- one separable pass. horizontal: src w x h -> dst outN x h; vertical: src w x h -> dst w x outN. ch channels of kind.
function K.resamplePass(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, outN: number, c: Coeffs, horizontal: boolean)
local start, count, weights = c.start, c.count, c.weights
local size = kind
local fixed = kind == 1
-- 8-bit: Pillow's 22-bit fixed-point coefficients
local iw: { { number } } = weights
if fixed then
iw = table.create(outN)
for i = 1, outN do
local src0 = weights[i]
local t = table.create(#src0, 0)
for k = 1, #src0 do
local v = src0[k] * 4194304
t[k] = if v < 0 then math.ceil(v - 0.5) else floor(v + 0.5)
end
iw[i] = t
end
end
if horizontal then
for y = 0, h - 1 do
local row = y * w
for xx = 0, outN - 1 do
local s0, n, wt = start[xx + 1], count[xx + 1], iw[xx + 1]
local o = ((y * outN) + xx) * ch * size
for cc = 0, ch - 1 do
if fixed then
local acc = 2097152
for k = 0, n - 1 do
acc += readu8(src, (row + s0 + k) * ch + cc) * wt[k + 1]
end
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
else
local acc = 0
for k = 0, n - 1 do
acc += rd(src, ((row + s0 + k) * ch + cc) * size, kind) * wt[k + 1]
end
wr(dst, o + cc * size, kind, acc)
end
end
end
end
else
for yy = 0, outN - 1 do
local s0, n, wt = start[yy + 1], count[yy + 1], iw[yy + 1]
for x = 0, w - 1 do
local o = (yy * w + x) * ch * size
for cc = 0, ch - 1 do
if fixed then
local acc = 2097152
for k = 0, n - 1 do
acc += readu8(src, ((s0 + k) * w + x) * ch + cc) * wt[k + 1]
end
writeu8(dst, o + cc, clamp(acc // 4194304, 0, 255))
else
local acc = 0
for k = 0, n - 1 do
acc += rd(src, (((s0 + k) * w + x) * ch + cc) * size, kind) * wt[k + 1]
end
wr(dst, o + cc * size, kind, acc)
end
end
end
end
end
local _ = h
end
-- nearest: dst pixel (x, y) = src pixel (floor((x + 0.5) * w / ow), ...)
function K.nearest(src: buffer, w: number, h: number, bpp: number, dst: buffer, ow: number, oh: number)
local sx, sy = w / ow, h / oh
for y = 0, oh - 1 do
local iy = math.min(floor((y + 0.5) * sy), h - 1)
for x = 0, ow - 1 do
local ix = math.min(floor((x + 0.5) * sx), w - 1)
buffer.copy(dst, (y * ow + x) * bpp, src, (iy * w + ix) * bpp, bpp)
end
end
end
-- affine(src, w, h, ch, kind, dst, ow, oh, m): dst pixel centres mapped through m = { a, b, c, d, e, f } to src
-- coordinates (xin = a x + b y + c), bilinear with clamped neighbours; centres outside the source -> zeros (Pillow)
function K.affine(src: buffer, w: number, h: number, ch: number, kind: number, dst: buffer, ow: number, oh: number, m: { number })
local a, b, c, d, e, f = m[1], m[2], m[3], m[4], m[5], m[6]
local size = kind
for y = 0, oh - 1 do
local py = y + 0.5
for x = 0, ow - 1 do
local px = x + 0.5
local xin = a * px + b * py + c - 0.5
local yin = d * px + e * py + f - 0.5
local o = (y * ow + x) * ch * size
local x0 = floor(xin)
local y0 = floor(yin)
if xin < -0.5 or xin >= w - 0.5 or yin < -0.5 or yin >= h - 0.5 then
continue -- dst starts zeroed
end
local dx, dy = xin - x0, yin - y0
local xa, xb = clamp(x0, 0, w - 1), clamp(x0 + 1, 0, w - 1)
local ya, yb = clamp(y0, 0, h - 1), clamp(y0 + 1, 0, h - 1)
for cc = 0, ch - 1 do
local p00 = rd(src, ((ya * w + xa) * ch + cc) * size, kind)
local p01 = rd(src, ((ya * w + xb) * ch + cc) * size, kind)
local p10 = rd(src, ((yb * w + xa) * ch + cc) * size, kind)
local p11 = rd(src, ((yb * w + xb) * ch + cc) * size, kind)
local top = p00 + (p01 - p00) * dx
local bot = p10 + (p11 - p10) * dx
local v = top + (bot - top) * dy
if kind == 1 then
writeu8(dst, o + cc, clamp(floor(v), 0, 255)) -- Pillow truncates
else
wr(dst, o + cc * size, kind, v)
end
end
end
end
end
-- ------------------------------------------------------------------------------------------------ compositing
-- overRgba8(dst, dw, src, sw, sx, sy, dx, dy, w, h, opacity255): Pillow's alpha_composite of src onto dst, in place
function K.overRgba8(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number)
for y = 0, h - 1 do
for x = 0, w - 1 do
local so = ((sy + y) * sw + sx + x) * 4
local doff = ((dy + y) * dw + dx + x) * 4
local sa = readu8(src, so + 3)
if opacity < 255 then
sa = (sa * opacity + 127) // 255
end
if sa == 0 then
continue
end
local da = readu8(dst, doff + 3)
local blend = da * (255 - sa)
local outa255 = sa * 255 + blend
local coef1 = (sa * 255 * 255 * 128) // outa255
local coef2 = 255 * 128 - coef1
for cc = 0, 2 do
local t = readu8(src, so + cc) * coef1 + readu8(dst, doff + cc) * coef2 + 0x80 * 128
t = ((t // 256) + t) // 256
writeu8(dst, doff + cc, t // 128)
end
local t = outa255 + 0x80
writeu8(dst, doff + 3, ((t // 256) + t) // 256)
end
end
end
-- overFloat: straight-alpha "over" for rgba16 (kind 2) / rgbaf32 (kind 4); max = 65535 or 1
function K.overFloat(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, opacity: number, kind: number)
local max = if kind == 2 then 65535 else 1
local px = 4 * kind
for y = 0, h - 1 do
for x = 0, w - 1 do
local so = ((sy + y) * sw + sx + x) * px
local doff = ((dy + y) * dw + dx + x) * px
local sa = rd(src, so + 3 * kind, kind) / max * opacity
if sa <= 0 then
continue
end
local da = rd(dst, doff + 3 * kind, kind) / max
local oa = sa + da * (1 - sa)
for cc = 0, 2 do
local s = rd(src, so + cc * kind, kind)
local d = rd(dst, doff + cc * kind, kind)
wr(dst, doff + cc * kind, kind, if oa > 0 then (s * sa + d * da * (1 - sa)) / oa else 0)
end
wr(dst, doff + 3 * kind, kind, oa * max)
end
end
end
-- copyRect: rows of a rectangle (bpp bytes per pixel)
function K.copyRect(dst: buffer, dw: number, src: buffer, sw: number, sx: number, sy: number, dx: number, dy: number, w: number, h: number, bpp: number)
for y = 0, h - 1 do
buffer.copy(dst, ((dy + y) * dw + dx) * bpp, src, ((sy + y) * sw + sx) * bpp, w * bpp)
end
end
-- premultiply / unpremultiply in place: ch channels, alpha last, kind
function K.premultiply(b: buffer, n: number, ch: number, kind: number, un: boolean)
local max = if kind == 1 then 255 elseif kind == 2 then 65535 else 1
local px = ch * kind
for i = 0, n - 1 do
local o = i * px
local a = rd(b, o + (ch - 1) * kind, kind)
for cc = 0, ch - 2 do
local v = rd(b, o + cc * kind, kind)
local r
if un then
if a <= 0 then
r = 0
elseif kind == 4 then
r = v / a
elseif kind == 1 then
r = math.min(255, (v * 255) // a) -- Pillow's rgbA2rgba
else
r = math.min(max, (v * max + a // 2) // a)
end
else
if kind == 4 then
r = v * a
elseif kind == 1 then
local t = v * a + 128 -- Pillow's MULDIV255
r = ((t // 256) + t) // 256
else
r = (v * a + max // 2) // max
end
end
wr(b, o + cc * kind, kind, r)
end
end
end
return K
+689
View File
@@ -0,0 +1,689 @@
--!strict
-- ops/ImageOps: editing on the standard Image (layer 5.5: core, Types and codecs only). Pixel format conversion,
-- crop, resize (nearest / bilinear / Lanczos-3, as Pillow), flips, quarter turns and arbitrary rotation (bilinear, as
-- Pillow's rotate), alpha compositing (Pillow's alpha_composite for rgba8), premultiplication, pixel access, and
-- helpers for animations (Image.frames). New code; the resampling and compositing follow Pillow's C sources.
--
-- local Ops = require("@formats/ops/ImageOps")
-- local small = Ops.resize(img, 320, 240, "lanczos") -- every call returns a new Image | nil, Err (never throws)
-- local grey = Ops.convert(img, "gray8")
-- Ops.blit(canvas, sprite, 10, 20) -- in place on canvas, straight-alpha "over"
-- for i, frame in Ops.coalesce(gif) do ... end -- full-canvas frames of an animation
--
-- Conventions: angles are degrees counter-clockwise and rotate90 turns are counter-clockwise quarter turns (as
-- Pillow). Resizing and rotating filter premultiplied alpha (as Pillow does for RGBA / LA). Grey is Pillow's
-- L = (19595 R + 38470 G + 7471 B + 32768) >> 16. 8 <-> 16 bit is * 257 and
-- (v * 255 + 32767) // 65535; float <-> integer clamps to 0..1 and rounds (no gamma). alpha8 converts to white with
-- that alpha. yuv420p is JPEG-style BT.601 full range (2x2 box chroma); geometric ops on yuv420p go through rgba8.
local Err = require("@formats/core/Err")
local Types = require("@formats/Types")
local K = require("@formats/ops/ImageOps/Kernels")
local ImageOps = {}
local MAX_PIXELS = 2 ^ 26
type Image = Types.Image
-- ------------------------------------------------------------------------------------------------ validation
local function arg(msg: string): (nil, Err.Err)
return nil, Err.new(Err.ARG, msg)
end
local function isInt(v: any): boolean
return type(v) == "number" and v == v and v % 1 == 0 and v > -2 ^ 31 and v < 2 ^ 31
end
local function bytesOf(fmt: string, w: number, h: number): number?
if fmt == "yuv420p" then
return w * h + 2 * ((w + 1) // 2) * ((h + 1) // 2)
end
local bpp = Types.BPP[fmt]
return if bpp then w * h * bpp else nil
end
-- check(img) -> true | nil, Err: a well-formed Image (known format, sizes, buffer long enough)
local function check(img: any): (boolean?, Err.Err?)
if type(img) ~= "table" or type(img.pixels) ~= "buffer" then
return arg("expected an Image")
end
if not isInt(img.width) or not isInt(img.height) or img.width < 1 or img.height < 1 then
return arg("bad image size")
end
local need = bytesOf(img.format, img.width, img.height)
if not need then
return arg("unknown pixel format " .. tostring(img.format))
end
if buffer.len(img.pixels) < need then
return arg("pixel buffer too small for " .. img.width .. " x " .. img.height .. " " .. img.format)
end
return true
end
ImageOps.check = check
local function limit(w: number, h: number, opts: any): (boolean?, Err.Err?)
local max = (type(opts) == "table" and opts.maxPixels) or MAX_PIXELS
if w * h > max then
return nil, Err.new(Err.LIMIT, string.format("%d x %d is over the %d pixel limit", w, h, max))
end
return true
end
-- a new Image of the same kind with a copy of meta's plain fields (source, palette...) but no frames
local function like(img: Image, w: number, h: number, fmt: string?): Image
local out = Types.Image.new(w, h, (fmt or img.format) :: any)
for k, v in img.meta do
out.meta[k] = v
end
out.loops = img.loops
return out
end
-- ------------------------------------------------------------------------------------------------ basics
-- new(w, h, format?) -> a zero-filled Image | nil, Err
function ImageOps.new(w: number, h: number, format: string?): (Image?, Err.Err?)
local fmt = format or "rgba8"
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
return arg("bad image size")
end
if not bytesOf(fmt, 1, 1) then
return arg("unknown pixel format " .. tostring(fmt))
end
local ok, e = limit(w, h, nil)
if not ok then
return nil, e
end
return Types.Image.new(w, h, fmt :: any)
end
-- copy(img) -> a deep copy of the pixels (frames are shared)
function ImageOps.copy(img: Image): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
local out = like(img, img.width, img.height)
buffer.copy(out.pixels, 0, img.pixels, 0, buffer.len(out.pixels))
out.frames = img.frames
return out
end
-- ------------------------------------------------------------------------------------------------ convert
-- convert(img, format) -> a new Image in format (a copy when it is already)
function ImageOps.convert(img: Image, format: string): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not bytesOf(format, 1, 1) then
return arg("unknown pixel format " .. tostring(format))
end
local w, h = img.width, img.height
if img.format == format then
return ImageOps.copy(img)
end
local src = img
if img.format == "yuv420p" then
local rgba = like(img, w, h, "rgba8")
K.yuvToRgba(img.pixels, w, h, rgba.pixels)
if format == "rgba8" then
return rgba
end
src = rgba
end
local out = like(img, w, h, format)
if format == "yuv420p" then
local rgba = src
if src.format ~= "rgba8" then
rgba = like(img, w, h, "rgba8")
K.convert(src.pixels, K.ID[src.format], rgba.pixels, K.ID.rgba8, w * h)
end
K.rgbaToYuv(rgba.pixels, w, h, out.pixels)
return out
end
K.convert(src.pixels, K.ID[src.format], out.pixels, K.ID[format], w * h)
return out
end
-- ops on yuv420p run on rgba8 and convert back
local function viaRgba(img: Image, f: (Image) -> (Image?, Err.Err?)): (Image?, Err.Err?)
if img.format ~= "yuv420p" then
return f(img)
end
local rgba = ImageOps.convert(img, "rgba8") :: Image
local res, e = f(rgba)
if not res then
return nil, e
end
return ImageOps.convert(res, "yuv420p")
end
-- ------------------------------------------------------------------------------------------------ geometry
local ALPHA_CH = { rgba8 = 4, rgba16 = 4, rgbaf32 = 4, graya8 = 2 }
-- crop(img, x, y, w, h) -> the rectangle clipped to the image | nil, Err (empty)
function ImageOps.crop(img: Image, x: number, y: number, w: number, h: number): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not (isInt(x) and isInt(y) and isInt(w) and isInt(h)) then
return arg("crop: integer x, y, w, h")
end
local x0, y0 = math.max(0, x), math.max(0, y)
local x1, y1 = math.min(img.width, x + w), math.min(img.height, y + h)
if x1 <= x0 or y1 <= y0 then
return arg("crop: the rectangle is outside the image or empty")
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local bpp = Types.BPP[im.format] :: number
local out = like(im, x1 - x0, y1 - y0)
K.copyRect(out.pixels, out.width, im.pixels, im.width, x0, y0, 0, 0, out.width, out.height, bpp)
return out
end)
end
-- flip(img, "h" | "v") -> mirrored horizontally (left-right) or vertically (top-bottom)
function ImageOps.flip(img: Image, axis: string): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if axis ~= "h" and axis ~= "v" then
return arg("flip: axis must be \"h\" or \"v\"")
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local out = like(im, im.width, im.height)
K.flip(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, axis == "h")
return out
end)
end
-- rotate90(img, turns) -> turned by turns counter-clockwise quarter turns (any integer; negative = clockwise)
function ImageOps.rotate90(img: Image, turns: number): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(turns) then
return arg("rotate90: integer turns")
end
local t = turns % 4
if t == 0 then
return ImageOps.copy(img)
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local swap = t ~= 2
local out = like(im, if swap then im.height else im.width, if swap then im.width else im.height)
K.rotate90(im.pixels, out.pixels, im.width, im.height, Types.BPP[im.format] :: number, t)
return out
end)
end
export type ResizeFilter = "nearest" | "bilinear" | "lanczos"
-- resize(img, w, h, filter?, opts?) -> w x h (filter default "bilinear"; opts.maxPixels)
function ImageOps.resize(img: Image, w: number, h: number, filter: string?, opts: any?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(w) or not isInt(h) or w < 1 or h < 1 then
return arg("resize: bad target size")
end
local f = filter or "bilinear"
if f ~= "nearest" and f ~= "bilinear" and f ~= "lanczos" then
return arg("resize: filter must be nearest, bilinear or lanczos")
end
local lok, le = limit(w, h, opts)
if not lok then
return nil, le
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local fmt = im.format
local bpp = Types.BPP[fmt] :: number
local out = like(im, w, h)
if f == "nearest" then
K.nearest(im.pixels, im.width, im.height, bpp, out.pixels, w, h)
return out
end
local kind, ch = K.KIND[fmt], K.CHANNELS[fmt]
local src, sw, sh = im.pixels, im.width, im.height
local alpha = ALPHA_CH[fmt]
if alpha then
src = buffer.create(buffer.len(im.pixels))
buffer.copy(src, 0, im.pixels)
K.premultiply(src, sw * sh, alpha, kind, false)
end
if w ~= sw then
local tmp = buffer.create(w * sh * bpp)
K.resamplePass(src, sw, sh, ch, kind, tmp, w, K.coeffs(sw, w, f), true)
src, sw = tmp, w
end
if h ~= sh then
K.resamplePass(src, sw, sh, ch, kind, out.pixels, h, K.coeffs(sh, h, f), false)
elseif src == im.pixels or (w == im.width and alpha) then
buffer.copy(out.pixels, 0, im.pixels, 0, w * h * bpp)
return out
else
out.pixels = src
end
if alpha then
K.premultiply(out.pixels, w * h, alpha, kind, true)
end
return out
end)
end
-- rotate(img, degrees, opts?) -> rotated counter-clockwise about the centre with bilinear sampling (as Pillow's
-- rotate(angle, BILINEAR, expand)): opts.expand (default true) grows the canvas to hold the whole image; uncovered
-- pixels are zero (transparent). opts.maxPixels.
function ImageOps.rotate(img: Image, degrees: number, opts: { expand: boolean?, maxPixels: number? }?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if type(degrees) ~= "number" or degrees ~= degrees or degrees == math.huge or degrees == -math.huge then
return arg("rotate: degrees must be a finite number")
end
local expand = not (opts and opts.expand == false)
if degrees % 90 == 0 and (expand or degrees % 180 == 0 or img.width == img.height) then
return ImageOps.rotate90(img, (degrees // 90) % 4)
end
local w, h = img.width, img.height
local ang = -math.rad(degrees)
local function r15(v: number): number
return math.floor(v * 1e15 + 0.5) / 1e15
end
local m = { r15(math.cos(ang)), r15(math.sin(ang)), 0, r15(-math.sin(ang)), r15(math.cos(ang)), 0 }
local function tr(x: number, y: number): (number, number)
return m[1] * x + m[2] * y + m[3], m[4] * x + m[5] * y + m[6]
end
local cx, cy = w / 2, h / 2
m[3], m[6] = tr(-cx, -cy)
m[3] += cx
m[6] += cy
local nw, nh = w, h
if expand then
local xs, ys = {}, {}
for _, p in { { 0, 0 }, { w, 0 }, { w, h }, { 0, h } } do
local x, y = tr(p[1], p[2])
table.insert(xs, x)
table.insert(ys, y)
end
nw = math.ceil(math.max(xs[1], xs[2], xs[3], xs[4])) - math.floor(math.min(xs[1], xs[2], xs[3], xs[4]))
nh = math.ceil(math.max(ys[1], ys[2], ys[3], ys[4])) - math.floor(math.min(ys[1], ys[2], ys[3], ys[4]))
m[3], m[6] = tr(-(nw - w) / 2, -(nh - h) / 2)
end
local lok, le = limit(nw, nh, opts)
if not lok then
return nil, le
end
return viaRgba(img, function(im: Image): (Image?, Err.Err?)
local out = like(im, nw, nh)
local kind = K.KIND[im.format]
local alpha = ALPHA_CH[im.format]
local src = im.pixels
if alpha then
src = buffer.create(buffer.len(im.pixels))
buffer.copy(src, 0, im.pixels)
K.premultiply(src, w * h, alpha, kind, false)
end
K.affine(src, w, h, K.CHANNELS[im.format], kind, out.pixels, nw, nh, m)
if alpha then
K.premultiply(out.pixels, nw * nh, alpha, kind, true)
end
return out
end)
end
-- ------------------------------------------------------------------------------------------------ compositing
local RGBA = { rgba8 = true, rgba16 = true, rgbaf32 = true }
export type BlitOptions = { blend: ("over" | "source")?, opacity: number? }
-- blit(dst, src, x, y, opts?) -> dst (modified in place) | nil, Err. src is clipped to dst; it is converted to dst's
-- format first when they differ. blend "over" (default: Porter-Duff over, straight alpha; Pillow's alpha_composite
-- for rgba8) or "source" (copy); opts.opacity 0..1 scales src alpha ("over" only).
function ImageOps.blit(dst: Image, src: Image, x: number, y: number, opts: BlitOptions?): (Image?, Err.Err?)
local ok, e = check(dst)
if not ok then
return nil, e
end
local ok2, e2 = check(src)
if not ok2 then
return nil, e2
end
if not isInt(x) or not isInt(y) then
return arg("blit: integer x, y")
end
local blend = (opts and opts.blend) or "over"
if blend ~= "over" and blend ~= "source" then
return arg("blit: blend must be \"over\" or \"source\"")
end
local opacity = (opts and opts.opacity) or 1
if type(opacity) ~= "number" or not (opacity >= 0 and opacity <= 1) then
return arg("blit: opacity must be 0..1")
end
-- clip
local sx, sy = math.max(0, -x), math.max(0, -y)
local dx, dy = math.max(0, x), math.max(0, y)
local w = math.min(src.width - sx, dst.width - dx)
local h = math.min(src.height - sy, dst.height - dy)
if w <= 0 or h <= 0 then
return dst
end
if dst.format == "yuv420p" or (blend == "over" and not RGBA[dst.format]) then
-- work on an rgba copy of the region, then write it back in dst's format
local region = ImageOps.crop(dst, dx, dy, w, h) :: Image
local work = if region.format == "rgba8" then region else ImageOps.convert(region, "rgba8") :: Image
ImageOps.blit(work, src, x - dx, y - dy, opts)
if dst.format == "yuv420p" then
local full = ImageOps.convert(dst, "rgba8") :: Image
ImageOps.blit(full, work, dx, dy, { blend = "source" })
local back = ImageOps.convert(full, "yuv420p") :: Image
buffer.copy(dst.pixels, 0, back.pixels, 0, buffer.len(back.pixels))
else
local back = ImageOps.convert(work, dst.format) :: Image
K.copyRect(dst.pixels, dst.width, back.pixels, back.width, 0, 0, dx, dy, w, h, Types.BPP[dst.format] :: number)
end
return dst
end
local s = src
if src.format ~= dst.format then
s = ImageOps.convert(src, dst.format) :: Image
end
if blend == "source" then
K.copyRect(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, Types.BPP[dst.format] :: number)
elseif dst.format == "rgba8" then
K.overRgba8(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, math.floor(opacity * 255 + 0.5))
else
K.overFloat(dst.pixels, dst.width, s.pixels, s.width, sx, sy, dx, dy, w, h, opacity, K.KIND[dst.format])
end
return dst
end
-- composite(dst, src, x?, y?, opts?) -> a new Image: a copy of dst with src blitted onto it
function ImageOps.composite(dst: Image, src: Image, x: number?, y: number?, opts: BlitOptions?): (Image?, Err.Err?)
local out, e = ImageOps.copy(dst)
if not out then
return nil, e
end
out.frames = nil
return ImageOps.blit(out, src, x or 0, y or 0, opts)
end
local function premul(img: Image, un: boolean): (Image?, Err.Err?)
local out, e = ImageOps.copy(img)
if not out then
return nil, e
end
out.frames = nil
local ch = ALPHA_CH[img.format]
if ch then
K.premultiply(out.pixels, img.width * img.height, ch, K.KIND[img.format], un)
end
return out
end
-- premultiply(img) / unpremultiply(img) -> a new Image (formats without alpha are copied unchanged)
function ImageOps.premultiply(img: Image): (Image?, Err.Err?)
return premul(img, false)
end
function ImageOps.unpremultiply(img: Image): (Image?, Err.Err?)
return premul(img, true)
end
-- ------------------------------------------------------------------------------------------------ pixels
local MAXV = { rgba8 = 255, rgba16 = 65535, rgbaf32 = 1, rgb8 = 255, gray8 = 255, gray16 = 65535, graya8 = 255, alpha8 = 255, yuv420p = 255 }
-- getPixel(img, x, y) -> r, g, b, a in the format's scale (0..255, 0..65535 or float); grey gives r = g = b;
-- alpha8 gives white; yuv420p converts to RGB. nil, Err out of range.
function ImageOps.getPixel(img: Image, x: number, y: number): (any, any, number?, number?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
return arg("getPixel: coordinates out of range")
end
local b, f, i = img.pixels, img.format, y * img.width + x
local ru8, ru16, rf = buffer.readu8, buffer.readu16, buffer.readf32
if f == "rgba8" then
return ru8(b, i * 4), ru8(b, i * 4 + 1), ru8(b, i * 4 + 2), ru8(b, i * 4 + 3)
elseif f == "rgba16" then
return ru16(b, i * 8), ru16(b, i * 8 + 2), ru16(b, i * 8 + 4), ru16(b, i * 8 + 6)
elseif f == "rgbaf32" then
return rf(b, i * 16), rf(b, i * 16 + 4), rf(b, i * 16 + 8), rf(b, i * 16 + 12)
elseif f == "rgb8" then
return ru8(b, i * 3), ru8(b, i * 3 + 1), ru8(b, i * 3 + 2), 255
elseif f == "gray8" then
local v = ru8(b, i)
return v, v, v, 255
elseif f == "gray16" then
local v = ru16(b, i * 2)
return v, v, v, 65535
elseif f == "graya8" then
local v = ru8(b, i * 2)
return v, v, v, ru8(b, i * 2 + 1)
elseif f == "alpha8" then
return 255, 255, 255, ru8(b, i)
end
local one = ImageOps.crop(img, x - x % 2, y - y % 2, 2, 2) :: Image
local rgba = ImageOps.convert(one, "rgba8") :: Image
local j = ((y % 2) * rgba.width + (x % 2)) * 4
if j + 4 > buffer.len(rgba.pixels) then
j = 0
end
return ru8(rgba.pixels, j), ru8(rgba.pixels, j + 1), ru8(rgba.pixels, j + 2), 255
end
-- setPixel(img, x, y, r, g, b, a?) -> true (in place) | nil, Err. Values in the format's scale (clamped and
-- rounded for integer formats); grey formats take Pillow's luma of r, g, b; a defaults to opaque. Not for yuv420p.
function ImageOps.setPixel(img: Image, x: number, y: number, r: number, g: number, b: number, a: number?): (boolean?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if not isInt(x) or not isInt(y) or x < 0 or y < 0 or x >= img.width or y >= img.height then
return arg("setPixel: coordinates out of range")
end
if type(r) ~= "number" or type(g) ~= "number" or type(b) ~= "number" or (a ~= nil and type(a) ~= "number") then
return arg("setPixel: numeric channels")
end
local f = img.format
if f == "yuv420p" then
return arg("setPixel: not supported on yuv420p (convert to rgba8 first)")
end
local max = MAXV[f]
local al = if a == nil then max else a
local function q(v: number): number
if max == 1 then
return v
end
if v ~= v then
return 0
end
return math.clamp(math.floor(v + 0.5), 0, max)
end
local px, i = img.pixels, y * img.width + x
local wu8, wu16, wf = buffer.writeu8, buffer.writeu16, buffer.writef32
local function grey(): number
if max == 1 then
return (r * 19595 + g * 38470 + b * 7471) / 65536
end
return (q(r) * 19595 + q(g) * 38470 + q(b) * 7471 + 32768) // 65536
end
if f == "rgba8" then
wu8(px, i * 4, q(r))
wu8(px, i * 4 + 1, q(g))
wu8(px, i * 4 + 2, q(b))
wu8(px, i * 4 + 3, q(al))
elseif f == "rgba16" then
wu16(px, i * 8, q(r))
wu16(px, i * 8 + 2, q(g))
wu16(px, i * 8 + 4, q(b))
wu16(px, i * 8 + 6, q(al))
elseif f == "rgbaf32" then
wf(px, i * 16, r)
wf(px, i * 16 + 4, g)
wf(px, i * 16 + 8, b)
wf(px, i * 16 + 12, al)
elseif f == "rgb8" then
wu8(px, i * 3, q(r))
wu8(px, i * 3 + 1, q(g))
wu8(px, i * 3 + 2, q(b))
elseif f == "gray8" then
wu8(px, i, grey())
elseif f == "gray16" then
wu16(px, i * 2, grey())
elseif f == "graya8" then
wu8(px, i * 2, grey())
wu8(px, i * 2 + 1, q(al))
else
wu8(px, i, q(al))
end
return true
end
-- fill(img, r, g, b, a?) -> img (in place) with every pixel set (values as setPixel)
function ImageOps.fill(img: Image, r: number, g: number, b: number, a: number?): (Image?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
if img.format == "yuv420p" then
return arg("fill: not supported on yuv420p")
end
local sok, se = ImageOps.setPixel(img, 0, 0, r, g, b, a)
if not sok then
return nil, se
end
local bpp = Types.BPP[img.format] :: number
local n = img.width * img.height * bpp
local filled = bpp
while filled < n do
local c = math.min(filled, n - filled)
buffer.copy(img.pixels, filled, img.pixels, 0, c)
filled += c
end
return img
end
-- ------------------------------------------------------------------------------------------------ animation
-- frameCount(img) -> the number of frames (1 for a still image)
function ImageOps.frameCount(img: Image): number
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
return #img.frames
end
return 1
end
-- durations(img) -> { seconds } per frame ({ 0 } for a still image)
function ImageOps.durations(img: Image): { number }
local out = {}
if type(img) == "table" and type(img.frames) == "table" and #img.frames > 0 then
for i, f in img.frames do
out[i] = if type(f.delay) == "number" then f.delay else 0
end
return out
end
return { 0 }
end
-- coalesce(img) -> { Image } | nil, Err: every frame composited onto a width x height canvas (rgba8, or rgba16 /
-- rgbaf32 when the image is), honouring each frame's x, y, blend ("over" / "source") and the previous frame's
-- dispose ("none" keeps the canvas, "background" clears the frame's rectangle to transparent, "previous" restores
-- the canvas from before the frame). A still image gives { img }.
function ImageOps.coalesce(img: Image): ({ Image }?, Err.Err?)
local ok, e = check(img)
if not ok then
return nil, e
end
local frames = img.frames
if type(frames) ~= "table" or #frames == 0 then
return { img }
end
local fmt = if RGBA[img.format] then img.format else "rgba8"
local canvas = Types.Image.new(img.width, img.height, fmt :: any)
local bpp = Types.BPP[fmt] :: number
local out = {}
for i, f in frames do
if type(f) ~= "table" then
return arg("coalesce: frame " .. i .. " is not a Frame")
end
local fi = f.image
local fok, fe = check(fi)
if not fok then
return nil, Err.new(Err.ARG, "coalesce: frame " .. i .. ": " .. (fe :: Err.Err).message)
end
local fx, fy = if isInt(f.x) then f.x else 0, if isInt(f.y) then f.y else 0
local saved: buffer? = nil
if f.dispose == "previous" then
local sb = buffer.create(buffer.len(canvas.pixels))
buffer.copy(sb, 0, canvas.pixels)
saved = sb
end
local bok, be = ImageOps.blit(canvas, fi, fx, fy, { blend = if f.blend == "source" then "source" else "over" })
if not bok then
return nil, be
end
local snap = Types.Image.new(img.width, img.height, fmt :: any)
buffer.copy(snap.pixels, 0, canvas.pixels)
for k, v in img.meta do
snap.meta[k] = v
end
snap.meta.delay = f.delay
out[i] = snap
if f.dispose == "background" then
local x0, y0 = math.max(0, fx), math.max(0, fy)
local x1, y1 = math.min(img.width, fx + fi.width), math.min(img.height, fy + fi.height)
for y = y0, y1 - 1 do
if x1 > x0 then
buffer.fill(canvas.pixels, (y * img.width + x0) * bpp, 0, (x1 - x0) * bpp)
end
end
elseif saved then
canvas.pixels = saved
end
end
return out
end
-- fromFrames(images, delays?) -> an animated Image: img.frames = the images as full-canvas frames (x = y = 0,
-- dispose "none", blend "source"), img.pixels = a copy of frame 1. delays: a number (every frame) or { seconds }
-- (default 0.1). All images need the same size and format.
function ImageOps.fromFrames(images: { Image }, delays: (number | { number })?): (Image?, Err.Err?)
if type(images) ~= "table" or #images == 0 then
return arg("fromFrames: a non-empty list of Images")
end
local first = images[1]
local ok, e = check(first)
if not ok then
return nil, e
end
local frames = {}
for i, im in images do
local iok, ie = check(im)
if not iok then
return nil, ie
end
if im.width ~= first.width or im.height ~= first.height or im.format ~= first.format then
return arg("fromFrames: frame " .. i .. " differs in size or format from frame 1")
end
local d = 0.1
if type(delays) == "number" then
d = delays
elseif type(delays) == "table" and type(delays[i]) == "number" then
d = delays[i]
end
frames[i] = { image = im, delay = d, x = 0, y = 0, dispose = "none", blend = "source" }
end
local out = like(first, first.width, first.height)
buffer.copy(out.pixels, 0, first.pixels, 0, buffer.len(out.pixels))
out.frames = frames :: any
out.loops = 0
return out
end
return ImageOps
+321
View File
@@ -0,0 +1,321 @@
-- ops/ImageOps tests: against Pillow (tools/fixtures/imageops.py): grey conversion (exact), resize nearest / bilinear /
-- Lanczos up and down (max error), rotate with bilinear + expand (PSNR), alpha_composite (exact); property tests for
-- every pixel format (conversion round trips, flips, quarter turns, crop, premultiply, pixel access, fill), blit
-- clipping and blend modes, animation helpers (coalesce with each disposal, fromFrames, durations), and a pass of bad
-- arguments that must return nil, Err without throwing.
local T = require("@tests/T")
local Ops = require("@formats/ops/ImageOps")
local Types = require("@formats/Types")
local Err = require("@formats/core/Err")
local Fx = require("@tests/gen/imageops")
local t = T.suite("imageops")
local function image(w: number, h: number, fmt: string, px: string): any
local img = Types.Image.new(w, h, fmt :: any)
buffer.writestring(img.pixels, 0, px)
return img
end
-- max abs difference and PSNR of two byte strings / buffers
local function diff(a: buffer, b: string): (number, number)
local n = #b
local mx, se = 0, 0
for i = 0, n - 1 do
local d = math.abs(buffer.readu8(a, i) - string.byte(b, i + 1))
if d > mx then
mx = d
end
se += d * d
end
local mse = se / n
return mx, if mse == 0 then 99 else 10 * math.log10(255 * 255 / mse)
end
local rgb = image(Fx.rgb.w, Fx.rgb.h, "rgb8", Fx.rgb.px)
local rgba = image(Fx.rgba.w, Fx.rgba.h, "rgba8", Fx.rgba.px)
local rgba2 = image(Fx.rgba2.w, Fx.rgba2.h, "rgba8", Fx.rgba2.px)
-- Pillow references
do
local g = Ops.convert(rgb, "gray8") :: any
t:check(buffer.tostring(g.pixels) == Fx.gray, "rgb8 -> gray8 matches Pillow convert('L')")
local ga = Ops.convert(rgba, "gray8") :: any
t:check(buffer.tostring(ga.pixels) == Fx.graya, "rgba8 -> gray8 matches Pillow (alpha ignored)")
local gray = Ops.convert(rgb, "gray8") :: any
local worst = { nearest = 0, bilinear = 0, lanczos = 0 }
for _, c in Fx.resize do
local src = if c.mode == "RGB" then rgb else gray
local r = Ops.resize(src, c.w, c.h, c.filter) :: any
t:check(r and r.width == c.w and r.height == c.h, "resize size")
local mx = diff(r.pixels, c.px)
worst[c.filter] = math.max(worst[c.filter], mx)
t:check(mx <= (if c.filter == "nearest" then 0 else 1), string.format("resize %s %s %dx%d: max error %d", c.filter, c.mode, c.w, c.h, mx))
end
t:note("resize vs Pillow (%d cases): max error nearest %d, bilinear %d, lanczos %d", #Fx.resize, worst.nearest, worst.bilinear, worst.lanczos)
local minPsnr = 99
for _, c in Fx.rotate do
local r = Ops.rotate(rgba, c.angle, { expand = c.expand }) :: any
t:check(r and r.width == c.w and r.height == c.h, string.format("rotate %d: size %dx%d, Pillow %dx%d", c.angle, r.width, r.height, c.w, c.h))
local _, psnr = diff(r.pixels, c.px)
minPsnr = math.min(minPsnr, psnr)
t:check(psnr > 40, string.format("rotate %d: PSNR %.1f", c.angle, psnr))
end
t:note("rotate vs Pillow (%d cases): min PSNR %.1f dB", #Fx.rotate, minPsnr)
local c = Ops.composite(rgba, rgba2) :: any
local mx = diff(c.pixels, Fx.composite)
t:check(mx == 0, "alpha_composite matches Pillow exactly (max error " .. mx .. ")")
end
-- conversions between every format
local FORMATS = { "rgba8", "rgba16", "rgbaf32", "rgb8", "gray8", "gray16", "graya8", "alpha8", "yuv420p" }
do
for _, f in FORMATS do
local c = Ops.convert(rgba, f) :: any
t:check(c and c.format == f and c.width == rgba.width, "convert to " .. f)
local back = Ops.convert(c, "rgba8") :: any
t:check(back and back.format == "rgba8", f .. " back to rgba8")
if f == "rgba16" or f == "rgbaf32" then
t:check(buffer.tostring(back.pixels) == buffer.tostring(rgba.pixels), f .. ": lossless round trip")
end
if f == "yuv420p" then
-- a smooth image (4:2:0 drops chroma detail)
local sm = Types.Image.new(40, 30)
for i = 0, 40 * 30 - 1 do
local x, y = i % 40, i // 40
buffer.writeu32(sm.pixels, i * 4, 0xFF000000 + (x * 6) + (y * 8) * 256 + ((x + y) * 3) * 65536)
end
local yb = Ops.convert(Ops.convert(sm, "yuv420p") :: any, "rgba8") :: any
local _, psnr = diff(yb.pixels, buffer.tostring(sm.pixels))
t:check(psnr > 38, string.format("yuv420p round trip PSNR %.1f", psnr))
end
for _, g in FORMATS do
t:check(Ops.convert(c, g) ~= nil, f .. " -> " .. g)
end
end
local g16 = Ops.convert(Ops.convert(rgb, "gray8") :: any, "gray16") :: any
t:eq(buffer.readu16(g16.pixels, 0), buffer.readu8((Ops.convert(rgb, "gray8") :: any).pixels, 0) * 257, "8 -> 16 bit is * 257")
local f = Types.Image.new(1, 1, "rgbaf32")
buffer.writef32(f.pixels, 0, 1.5)
buffer.writef32(f.pixels, 4, -0.2)
buffer.writef32(f.pixels, 8, 0.5)
buffer.writef32(f.pixels, 12, 1)
local b = Ops.convert(f, "rgba8") :: any
t:check(buffer.readu8(b.pixels, 0) == 255 and buffer.readu8(b.pixels, 1) == 0 and buffer.readu8(b.pixels, 2) == 128, "float -> 8 bit clamps and rounds")
end
-- geometry properties on every format
do
for _, f in FORMATS do
local img = Ops.convert(rgba, f) :: any
local s = buffer.tostring(img.pixels)
local r = img
for _ = 1, 4 do
r = Ops.rotate90(r, 1)
end
if f ~= "yuv420p" then
t:check(buffer.tostring(r.pixels) == s, f .. ": four quarter turns are the identity")
t:check(buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "h") :: any).pixels) == s, f .. ": flip h twice")
t:check(buffer.tostring((Ops.flip(Ops.flip(img, "v") :: any, "v") :: any).pixels) == s, f .. ": flip v twice")
local q = Ops.rotate90(img, 1) :: any
t:check(q.width == img.height and q.height == img.width, f .. ": a quarter turn swaps the size")
t:check(buffer.tostring((Ops.rotate90(img, 2) :: any).pixels) == buffer.tostring((Ops.flip(Ops.flip(img, "h") :: any, "v") :: any).pixels), f .. ": half turn = both flips")
t:check(buffer.tostring((Ops.rotate(img, 90) :: any).pixels) == buffer.tostring(q.pixels), f .. ": rotate 90 = one quarter turn")
end
local c = Ops.crop(img, -5, 10, 20, 100) :: any
t:check(c and c.width == 15 and c.height == img.height - 10, f .. ": crop clipped")
for _, filter in { "nearest", "bilinear", "lanczos" } do
local z = Ops.resize(img, 23, 31, filter) :: any
t:check(z and z.width == 23 and z.height == 31 and z.format == f, f .. ": resize " .. filter)
end
local rr = Ops.rotate(img, 33) :: any
t:check(rr and rr.format == f, f .. ": rotate 33")
end
-- crop content, nearest identity, ccw convention
local c = Ops.crop(rgba, 3, 4, 5, 6) :: any
t:check(buffer.readu32(c.pixels, 0) == buffer.readu32(rgba.pixels, (4 * rgba.width + 3) * 4), "crop origin")
t:check(buffer.tostring((Ops.resize(rgba, rgba.width, rgba.height, "lanczos") :: any).pixels) == buffer.tostring(rgba.pixels), "same-size resize is a copy")
local q = Ops.rotate90(rgba, 1) :: any -- ccw: the top-right pixel goes to the top-left
t:eq(buffer.readu32(q.pixels, 0), buffer.readu32(rgba.pixels, (rgba.width - 1) * 4), "rotate90 is counter-clockwise")
end
-- pixels, fill, premultiply
do
for _, f in FORMATS do
local img = Ops.new(3, 2, f) :: any
t:check(img and img.format == f, "new " .. f)
if f ~= "yuv420p" then
local max = if f == "rgba16" or f == "gray16" then 65535 elseif f == "rgbaf32" then 1 else 255
t:check(Ops.setPixel(img, 2, 1, max, max, max, max), f .. ": setPixel")
local r, g, b, a = Ops.getPixel(img, 2, 1)
t:check(r == max and g == max and b == max and a == max, f .. ": getPixel after setPixel")
Ops.fill(img, 0, 0, 0, 0)
local r2 = Ops.getPixel(img, 2, 1)
t:check(r2 == (if f == "alpha8" then 255 else 0), f .. ": fill")
else
t:check(Ops.setPixel(img, 0, 0, 1, 2, 3) == nil, "setPixel refuses yuv420p")
t:check(Ops.getPixel(img, 2, 1) ~= nil, "getPixel on yuv420p")
end
end
local p = Ops.premultiply(rgba) :: any
local u = Ops.unpremultiply(p) :: any
local worst = 0
for i = 0, rgba.width * rgba.height - 1 do
local a = buffer.readu8(rgba.pixels, i * 4 + 3)
t:check(buffer.readu8(p.pixels, i * 4) <= a, "premultiplied <= alpha")
if a >= 32 then
for c = 0, 2 do
worst = math.max(worst, math.abs(buffer.readu8(u.pixels, i * 4 + c) - buffer.readu8(rgba.pixels, i * 4 + c)))
end
end
end
t:check(worst <= 4, "premultiply round trip error " .. worst .. " (alpha >= 32)")
t:note("premultiply round trip: max error %d for alpha >= 32", worst)
end
-- blit
do
local dst = Ops.new(10, 10, "rgba8") :: any
Ops.fill(dst, 10, 20, 30, 255)
local src = Ops.new(4, 4, "rgba8") :: any
Ops.fill(src, 200, 100, 50, 255)
Ops.blit(dst, src, -2, 8)
t:check(select(1, Ops.getPixel(dst, 0, 8)) == 200 and select(1, Ops.getPixel(dst, 1, 9)) == 200, "blit clipped at the left / bottom")
t:check(select(1, Ops.getPixel(dst, 2, 8)) == 10 and select(1, Ops.getPixel(dst, 0, 7)) == 10, "blit stays inside its rectangle")
Ops.fill(src, 0, 0, 0, 0)
Ops.blit(dst, src, 0, 0)
t:check(select(1, Ops.getPixel(dst, 0, 0)) == 10, "over with a transparent source keeps dst")
Ops.blit(dst, src, 0, 0, { blend = "source" })
t:check(select(4, Ops.getPixel(dst, 0, 0)) == 0, "source blend copies alpha")
Ops.fill(src, 255, 255, 255, 255)
Ops.blit(dst, src, 5, 5, { opacity = 0.5 })
local r = Ops.getPixel(dst, 5, 5)
t:check(math.abs(r - 133) <= 1, "opacity 0.5 over (10 -> " .. r .. ")")
-- rgb8 destination, gray source, float destination
local d3 = Ops.convert(dst, "rgb8") :: any
t:check(Ops.blit(d3, Ops.convert(src, "graya8") :: any, 1, 1) == d3, "blit onto rgb8")
local df = Ops.convert(dst, "rgbaf32") :: any
t:check(Ops.blit(df, src, 0, 0, { opacity = 0.25 }) == df, "blit onto rgbaf32")
local dy = Ops.convert(dst, "yuv420p") :: any
t:check(Ops.blit(dy, src, 3, 3) == dy, "blit onto yuv420p")
end
-- animation helpers
do
local W, H = 6, 4
local function solid(w: number, h: number, r: number, a: number): any
local im = Ops.new(w, h, "rgba8") :: any
Ops.fill(im, r, 0, 0, a)
return im
end
local anim = Ops.new(W, H, "rgba8") :: any
anim.frames = {
{ image = solid(W, H, 10, 255), delay = 0.1, x = 0, y = 0, dispose = "none", blend = "source" },
{ image = solid(2, 2, 20, 255), delay = 0.2, x = 1, y = 1, dispose = "background", blend = "over" },
{ image = solid(2, 2, 30, 255), delay = 0.3, x = 3, y = 1, dispose = "previous", blend = "over" },
{ image = solid(1, 1, 40, 128), delay = 0.4, x = 5, y = 3, dispose = "none", blend = "over" },
}
local fr = Ops.coalesce(anim) :: any
t:eq(#fr, 4, "coalesce frame count")
local function at(i: number, x: number, y: number): (number, number)
local r, _, _, a = Ops.getPixel(fr[i], x, y)
return r, a
end
t:check(at(1, 0, 0) == 10 and at(1, 1, 1) == 10, "frame 1")
t:check(at(2, 1, 1) == 20 and at(2, 2, 2) == 20 and at(2, 0, 0) == 10, "frame 2 drawn at 1, 1")
local r3, a3 = at(3, 1, 1)
t:check(r3 == 0 and a3 == 0, "frame 2 disposed to background before frame 3")
t:check(at(3, 3, 1) == 30, "frame 3 drawn")
t:check(at(4, 3, 1) == 10, "frame 3 disposed to previous before frame 4")
local r4 = at(4, 5, 3)
t:check(r4 > 10 and r4 < 40, "frame 4 blends over")
t:eq(Ops.frameCount(anim), 4, "frameCount")
t:eq(Ops.durations(anim)[3], 0.3, "durations")
t:eq(Ops.frameCount(rgba), 1, "frameCount of a still")
t:check((Ops.coalesce(rgba) :: any)[1] == rgba, "coalesce of a still")
local made = Ops.fromFrames({ fr[1], fr[2], fr[3] }, { 0.5, 0.25 }) :: any
t:check(made and #made.frames == 3 and made.frames[2].delay == 0.25 and made.frames[3].delay == 0.1, "fromFrames delays")
t:check(buffer.tostring(made.pixels) == buffer.tostring(fr[1].pixels), "fromFrames pixels = frame 1")
local again = Ops.coalesce(made) :: any
t:check(buffer.tostring(again[3].pixels) == buffer.tostring(fr[3].pixels), "coalesce(fromFrames) round trip")
t:check(Ops.fromFrames({ fr[1], rgba }) == nil, "fromFrames refuses mixed sizes")
end
-- bad arguments: nil, Err, never a throw
do
local rand = T.rng(5)
local junk: { any } = { nil, 0, -1, 1.5, 2 ^ 40, "x", {}, true, 0 / 0, math.huge, -7 }
local imgs: { any } = { rgba, rgb, {}, { pixels = buffer.create(1), width = 5, height = 5, format = "rgba8" }, Types.Image.new(1, 1, "alpha8"), Ops.convert(rgba, "yuv420p") }
local calls = {
function(a: any, b: any, c: any, d: any)
return Ops.convert(a, b)
end,
function(a: any, b: any, c: any, d: any)
return Ops.crop(a, b, c, d, b)
end,
function(a: any, b: any, c: any, _d: any)
return Ops.resize(a, b, c, "lanczos")
end,
function(a: any, b: any, c: any, _d: any)
return Ops.resize(a, b, c, b)
end,
function(a: any, b: any, _c: any, _d: any)
return Ops.rotate(a, b)
end,
function(a: any, b: any, _c: any, _d: any)
return Ops.rotate90(a, b)
end,
function(a: any, b: any, _c: any, _d: any)
return Ops.flip(a, b)
end,
function(a: any, b: any, c: any, d: any)
return Ops.blit(a, d, b, c)
end,
function(a: any, b: any, c: any, d: any)
return Ops.blit(a, a, b, c, { opacity = d })
end,
function(a: any, b: any, c: any, _d: any)
return Ops.getPixel(a, b, c)
end,
function(a: any, b: any, c: any, d: any)
return Ops.setPixel(a, b, c, d, d, d)
end,
function(a: any, b: any, _c: any, _d: any)
return Ops.new(a, b, "rgba8")
end,
function(a: any, _b: any, _c: any, _d: any)
return Ops.coalesce(a)
end,
function(a: any, b: any, _c: any, _d: any)
return Ops.fromFrames({ a, b } :: any)
end,
function(a: any, b: any, c: any, d: any)
return Ops.fill(a, b, c, d)
end,
}
local tries, threw = 0, 0
for _ = 1, 600 do
local f = calls[1 + rand(#calls)]
local a = imgs[1 + rand(#imgs)]
local args = { junk[1 + rand(#junk)], junk[1 + rand(#junk)], junk[1 + rand(#junk)] }
if rand(3) == 0 then
args[3] = imgs[1 + rand(#imgs)]
end
tries += 1
local ok, err = pcall(f, a, args[1], args[2], args[3])
if not ok then
threw += 1
print(" THREW: " .. tostring(err))
end
end
t:check(threw == 0, "bad arguments never throw (" .. threw .. " of " .. tries .. ")")
t:note("bad arguments: %d calls, none threw", tries)
local _, e = Ops.resize(rgba, 100000, 100000)
t:check(e and e.code == Err.LIMIT, "resize over the pixel limit")
local _, e2 = Ops.crop(rgba, 100, 100, 5, 5)
t:check(e2 and e2.code == Err.ARG, "empty crop")
local _, e3 = Ops.convert(rgba, "cmyk")
t:check(e3 and e3.code == Err.ARG, "unknown format")
end
t:done()
+29
View File
@@ -125,3 +125,32 @@ do
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
+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)