imgA-ops: ops/ImageOps (convert between every pixel format incl. yuv420p, crop, resize nearest/bilinear/Lanczos-3 as Pillow, flip, rotate90, rotate bilinear+expand as Pillow, blit/composite with Pillow's alpha_composite, premultiply, get/setPixel, fill, coalesce/fromFrames/frameCount/durations) with Pillow fixtures, tests on both runtimes, bench block
This commit is contained in:
1 parent
2eee0bc1a6
commit
e2b338db7e
5 files changed
+1624
No files matched your search
@@ -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
|
||||
@@ -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
|
||||
Reference in new issue
Block a user