image.process\edge\canny.mbt
84.3% · 70 / 83 points · 229 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # Canny 边缘检测 canny - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// Canny 边缘检测(纯 MoonBit) - 7
- 8
///| - 9
/// Canny 边缘检测。 - 10
/// 步骤:高斯模糊 → Sobel 梯度 → 非极大值抑制 → 双阈值 + 滞后连接。 - 11
/// 适用于灰度图(channels=1)或 RGB/RGBA 图(channels=3/4,自动转灰度)。 - 12
/// low_threshold 和 high_threshold 为双阈值(low 应 < high)。 - 13
pub fn canny_edge( - 14
img : @types.Image, - 15
low_threshold~ : Int32 = 50, - 16
high_threshold~ : Int32 = 100, - 17
) -> @types.Image raise @types.LoadError { - 18
// 输入验证 - 19●
if img.width <= 0 || img.height <= 0 { - 20●
raise @types.LoadError::DecodeFailed( - 21
"canny_edge: 图像尺寸必须大于0", - 22
) - 23
} - 24
if img.channels != 1 && img.channels != 3 && img.channels != 4 { - 25●
raise @types.LoadError::DecodeFailed("canny_edge: 仅支持 channels=1/3/4") - 26
} - 27
let expected_size = img.width * img.height * img.channels - 28●
if img.data.length() != expected_size { - 29●
raise @types.LoadError::DecodeFailed( - 30
"canny_edge: 数据大小不匹配,期望 " + - 31●
expected_size.to_string() + - 32
",实际 " + - 33●
img.data.length().to_string(), - 34
) - 35
} - 36
if low_threshold < 0 || low_threshold > 255 { - 37●
raise @types.LoadError::DecodeFailed( - 38
"low_threshold 必须在 0..255 之间", - 39
) - 40
} - 41
if high_threshold < 0 || high_threshold > 255 { - 42●
raise @types.LoadError::DecodeFailed( - 43
"high_threshold 必须在 0..255 之间", - 44
) - 45
} - 46
if low_threshold > high_threshold { - 47●
raise @types.LoadError::DecodeFailed("low_threshold 应 <= high_threshold") - 48
} - 49
let w = img.width - 50
let h = img.height - 51
let n = w * h - 52
if n == 0 { - 53○
return img - 54
} - 55
// 转灰度 - 56●
let gray : Array[Int32] = Array::make(n, 0) - 57
let ch = img.channels - 58
for i in 0..<n { - 59●
if ch == 1 { - 60●
gray[i] = img.data[i].to_int() - 61
} else { - 62○
let r = img.data[i * ch].to_int() - 63○
let g = img.data[i * ch + 1].to_int() - 64○
let b = img.data[i * ch + 2].to_int() - 65
gray[i] = (r * 299 + g * 587 + b * 114) / 1000 - 66
} - 67
} - 68
// 1. 高斯模糊 (sigma=1.0, 5x5 核) - 69●
let blurred = canny_gaussian_blur(gray, w, h) - 70
// 2. Sobel 梯度 - 71●
let gradient : Array[Int32] = Array::make(n, 0) - 72●
let direction : Array[Int32] = Array::make(n, 0) // 0=0°, 1=45°, 2=90°, 3=135° - 73
for y in 1..<(h - 1) { - 74●
for x in 1..<(w - 1) { - 75●
let idx = y * w + x - 76
// Sobel X - 77
let gx = -blurred[(y - 1) * w + (x - 1)] - - 78
2 * blurred[y * w + (x - 1)] - - 79
blurred[(y + 1) * w + (x - 1)] + - 80
blurred[(y - 1) * w + (x + 1)] + - 81
2 * blurred[y * w + (x + 1)] + - 82
blurred[(y + 1) * w + (x + 1)] - 83
// Sobel Y - 84
let gy = -blurred[(y - 1) * w + (x - 1)] - - 85
2 * blurred[(y - 1) * w + x] - - 86
blurred[(y - 1) * w + (x + 1)] + - 87
blurred[(y + 1) * w + (x - 1)] + - 88
2 * blurred[(y + 1) * w + x] + - 89
blurred[(y + 1) * w + (x + 1)] - 90
// 梯度幅值(sqrt 比 powf(x, 0.5) 更快) - 91●
let mag = Float::from_int(gx * gx + gy * gy).sqrt().to_int() - 92
gradient[idx] = mag - 93
// 梯度方向量化到 4 个方向 - 94●
let angle = @math.atan2f(Float::from_int(gy), Float::from_int(gx)) * - 95
180.0F / - 96
3.14159265F - 97◐
let norm_angle = if angle < 0.0F { angle + 180.0F } else { angle } - 98
direction[idx] = if norm_angle < 22.5F || norm_angle >= 157.5F { - 99●
0 // 水平 - 100●
} else if norm_angle < 67.5F { - 101○
1 // 45° - 102●
} else if norm_angle < 112.5F { - 103●
2 // 垂直 - 104
} else { - 105○
3 // 135° - 106
} - 107
} - 108
} - 109
// 3. 非极大值抑制 - 110●
let nms : Array[Int32] = Array::make(n, 0) - 111
for y in 1..<(h - 1) { - 112●
for x in 1..<(w - 1) { - 113●
let idx = y * w + x - 114
let mag = gradient[idx] - 115
if mag == 0 { - 116●
continue - 117
} - 118
let dir = direction[idx] - 119●
let (n1, n2) = match dir { - 120●
0 => (gradient[idx - 1], gradient[idx + 1]) // 水平:比较左右 - 121○
1 => (gradient[(y - 1) * w + (x + 1)], gradient[(y + 1) * w + (x - 1)]) // 45° - 122●
2 => (gradient[(y - 1) * w + x], gradient[(y + 1) * w + x]) // 垂直:比较上下 - 123○
_ => (gradient[(y - 1) * w + (x - 1)], gradient[(y + 1) * w + (x + 1)]) // 135° - 124
} - 125
if mag >= n1 && mag >= n2 { - 126●
nms[idx] = mag - 127
} - 128
} - 129
} - 130
// 4. 双阈值 + 滞后连接 - 131●
let out : Array[Byte] = Array::make(n, b'\x00') - 132●
let strong : Array[Bool] = Array::make(n, false) - 133●
let weak : Array[Bool] = Array::make(n, false) - 134
for i in 0..<n { - 135●
if nms[i] >= high_threshold { - 136●
strong[i] = true - 137●
} else if nms[i] >= low_threshold { - 138○
weak[i] = true - 139
} - 140
} - 141
// 滞后连接:弱边缘如果与强边缘连通则保留 - 142
let stack : Array[Int32] = [] - 143
for i in 0..<n { - 144●
if strong[i] { - 145●
out[i] = b'\xFF' - 146●
stack.push(i) - 147
} - 148
} - 149●
while stack.length() > 0 { - 150●
let idx = stack.remove(stack.length() - 1) - 151
let x = idx % w - 152
let y = idx / w - 153
// 8 邻域 - 154
for dy in -1..<=1 { - 155●
for dx in -1..<=1 { - 156●
if dx == 0 && dy == 0 { - 157●
continue - 158
} - 159
let nx = x + dx - 160
let ny = y + dy - 161
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 162●
let nidx = ny * w + nx - 163
if weak[nidx] && !strong[nidx] { - 164○
strong[nidx] = true - 165
out[nidx] = b'\xFF' - 166○
stack.push(nidx) - 167
} - 168
} - 169
} - 170
} - 171
} - 172
@types.Image::{ - 173
width: w, - 174
height: h, - 175
channels: 1, - 176●
data: Bytes::from_array(out), - 177
} - 178
} - 179
- 180
///| - 181
/// 5x5 高斯模糊(sigma=1.0),分离内部/边界区域以消除热点 clamp 调用 - 182
fn canny_gaussian_blur( - 183
gray : Array[Int32], - 184
w : Int32, - 185
h : Int32, - 186
) -> Array[Int32] { - 187●
let n = w * h - 188●
let out : Array[Int32] = Array::make(n, 0) - 189
// 5x5 高斯核 (sigma=1.0) - 190
let kernel : Array[Int32] = [ - 191
2, 4, 5, 4, 2, 4, 9, 12, 9, 4, 5, 12, 15, 12, 5, 4, 9, 12, 9, 4, 2, 4, 5, 4, - 192
2, - 193
] - 194
let kernel_sum = 159 - 195
// 内部区域:x in [2, w-2), y in [2, h-2),5x5 核完全在图像内,无需 clamp - 196
for y in 2..<(h - 2) { - 197●
for x in 2..<(w - 2) { - 198●
let mut sum = 0 - 199
let base = (y - 2) * w + (x - 2) - 200
for ky in 0..<5 { - 201●
let row = base + ky * w - 202
let krow = ky * 5 - 203
for kx in 0..<5 { - 204●
sum += gray[row + kx] * kernel[krow + kx] - 205
} - 206
} - 207
out[y * w + x] = sum / kernel_sum - 208
} - 209
} - 210
// 边界区域:5x5 核可能超出图像,需要 clamp - 211
for y in 0..<h { - 212●
let y_inner = y >= 2 && y < h - 2 - 213
for x in 0..<w { - 214●
if y_inner && x >= 2 && x < w - 2 { - 215●
continue - 216
} - 217
let mut sum = 0 - 218
for ky in 0..<5 { - 219●
for kx in 0..<5 { - 220●
let px = (x + kx - 2).clamp(min=0, max=w - 1) - 221●
let py = (y + ky - 2).clamp(min=0, max=h - 1) - 222
sum += gray[py * w + px] * kernel[ky * 5 + kx] - 223
} - 224
} - 225
out[y * w + x] = sum / kernel_sum - 226
} - 227
} - 228
out - 229
}