///|
/// # 图像金字塔 pyramid
///
/// 图像处理算法模块
/// 图像处理算法模块 Image processing algorithm module
// 图像金字塔(纯 MoonBit)
///|
/// 高斯金字塔下采样。将图像尺寸减半(宽高各 /2),使用 2x2 均值滤波。
pub fn pyr_down(img : @types.Image) -> @types.Image raise @types.LoadError {
if img.channels != 1 && img.channels != 3 && img.channels != 4 {
raise @types.LoadError::DecodeFailed("pyr_down 仅支持 channels=1/3/4")
}
let ch = img.channels
let w = img.width
let h = img.height
let new_w = w / 2
let new_h = h / 2
if new_w == 0 || new_h == 0 {
raise @types.LoadError::DecodeFailed("图像太小,无法下采样")
}
let data_int : Array[Int32] = Array::make(w * h * ch, 0)
for i in 0..<(w * h * ch) {
data_int[i] = img.data[i].to_int()
}
let out : Array[Byte] = Array::make(new_w * new_h * ch, b'\x00')
for y in 0.. @types.Image raise @types.LoadError {
if img.channels != 1 && img.channels != 3 && img.channels != 4 {
raise @types.LoadError::DecodeFailed("pyr_up 仅支持 channels=1/3/4")
}
let ch = img.channels
let w = img.width
let h = img.height
let new_w = w * 2
let new_h = h * 2
let data_int : Array[Int32] = Array::make(w * h * ch, 0)
for i in 0..<(w * h * ch) {
data_int[i] = img.data[i].to_int()
}
// 预计算 x 方向插值参数
let x0_arr : Array[Int32] = Array::make(new_w, 0)
let x1_arr : Array[Int32] = Array::make(new_w, 0)
let wx_arr : Array[Float] = Array::make(new_w, 0.0F)
for x in 0.. 255.0F {
255
} else {
v.to_int()
}
out[(y * new_w + x) * ch + c] = clamped.to_byte()
}
}
}
@types.Image::{
width: new_w,
height: new_h,
channels: ch,
data: Bytes::from_array(out),
}
}
///|
/// 构建高斯金字塔。返回各级图像(从原图到最小级),levels 为最大层数(0=自动到 1x1)。
pub fn build_gaussian_pyramid(
img : @types.Image,
levels : Int32,
) -> Array[@types.Image] raise @types.LoadError {
let result : Array[@types.Image] = [img]
let mut current = img
let max_levels = if levels == 0 { 100 } else { levels }
for _ in 1.. Array[@types.Image] raise @types.LoadError {
let gaussian = build_gaussian_pyramid(img, levels)
let result : Array[@types.Image] = []
for i in 0..<(gaussian.length() - 1) {
let upsampled = pyr_up(gaussian[i + 1])
let lap = laplacian_diff(gaussian[i], upsampled)
result.push(lap)
}
result.push(gaussian[gaussian.length() - 1])
result
}
///|
fn laplacian_diff(a : @types.Image, b : @types.Image) -> @types.Image {
let ch = a.channels
let w = a.width
let h = a.height
let a_int : Array[Int32] = Array::make(w * h * ch, 0)
for i in 0..<(w * h * ch) {
a_int[i] = a.data[i].to_int()
}
let bw = b.width
let bh = b.height
let b_int : Array[Int32] = Array::make(bw * bh * ch, 0)
for i in 0..<(bw * bh * ch) {
b_int[i] = b.data[i].to_int()
}
let out : Array[Byte] = Array::make(w * h * ch, b'\x00')
for y in 0.. 255 { 255 } else { diff }
out[(y * w + x) * ch + c] = clamped.to_byte()
}
}
}
@types.Image::{
width: w,
height: h,
channels: ch,
data: Bytes::from_array(out),
}
}