image.process\edge\canny.mbt

84.3% · 70 / 83 points · 229 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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