image.process\edge\canny_16f.mbt

93.9% · 169 / 180 points · 462 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 边缘检测 16-bit/float 变体 Canny edge detection 16-bit/float variants
  3. 3///
  4. 4/// 16位/浮点 Canny 边缘检测 canny_16 / canny_f
  5. 5/// 16位/浮点 Canny 边缘检测 16-bit/float Canny edge detection
  6. 6// Canny 边缘检测 16-bit/float 变体
  7. 7// 支持 Image16 / ImageF 两种类型
  8. 8
  9. 9// ========== 辅助函数 ==========
  10. 10
  11. 11///|
  12. 12fn read_u16_le_c(data : Bytes, offset : Int32) -> Int32 {
  13. 13● data[offset].to_int() + data[offset + 1].to_int() * 256
  14. 14}
  15. 15
  16. 16///|
  17. 17fn write_u16_le_c(buf : Array[Byte], offset : Int32, val : Int32) -> Unit {
  18. 18● buf[offset] = (val & 0xFF).to_byte()
  19. 19● buf[offset + 1] = ((val >> 8) & 0xFF).to_byte()
  20. 20}
  21. 21
  22. 22///|
  23. 23fn read_float_le_c(data : Bytes, offset : Int32) -> Float {
  24. 24● let b0 = data[offset].to_int()
  25. 25● let b1 = data[offset + 1].to_int()
  26. 26● let b2 = data[offset + 2].to_int()
  27. 27● let b3 = data[offset + 3].to_int()
  28. 28 let bits = b0 | (b1 << 8) | (b2 << 16) | (b3 << 24)
  29. 29● Float::reinterpret_from_int(bits)
  30. 30}
  31. 31
  32. 32///|
  33. 33fn write_f32_le_c(buf : Array[Byte], offset : Int32, val : Float) -> Unit {
  34. 34● let bits = val.reinterpret_as_int()
  35. 35● buf[offset] = (bits & 0xFF).to_byte()
  36. 36● buf[offset + 1] = ((bits >> 8) & 0xFF).to_byte()
  37. 37● buf[offset + 2] = ((bits >> 16) & 0xFF).to_byte()
  38. 38● buf[offset + 3] = ((bits >> 24) & 0xFF).to_byte()
  39. 39}
  40. 40
  41. 41///|
  42. 42
  43. 43// 5x5 高斯模糊 (sigma=1.0)
  44. 44
  45. 45///|
  46. 46fn canny_gaussian_blur_16(
  47. 47 gray : Array[Int32],
  48. 48 w : Int32,
  49. 49 h : Int32,
  50. 50) -> Array[Int32] {
  51. 51● let n = w * h
  52. 52● let out : Array[Int32] = Array::make(n, 0)
  53. 53 let kernel : Array[Int32] = [
  54. 54 2, 4, 5, 4, 2, 4, 9, 12, 9, 4, 5, 12, 15, 12, 5, 4, 9, 12, 9, 4, 2, 4, 5, 4,
  55. 55 2,
  56. 56 ]
  57. 57 let kernel_sum = 159
  58. 58 for y in 2..<(h - 2) {
  59. 59● for x in 2..<(w - 2) {
  60. 60● let mut sum = 0
  61. 61 let base = (y - 2) * w + (x - 2)
  62. 62 for ky in 0..<5 {
  63. 63● let row = base + ky * w
  64. 64 let krow = ky * 5
  65. 65 for kx in 0..<5 {
  66. 66● sum += gray[row + kx] * kernel[krow + kx]
  67. 67 }
  68. 68 }
  69. 69 out[y * w + x] = sum / kernel_sum
  70. 70 }
  71. 71 }
  72. 72 for y in 0..<h {
  73. 73● let y_inner = y >= 2 && y < h - 2
  74. 74 for x in 0..<w {
  75. 75● if y_inner && x >= 2 && x < w - 2 {
  76. 76● continue
  77. 77 }
  78. 78 let mut sum = 0
  79. 79 for ky in 0..<5 {
  80. 80● for kx in 0..<5 {
  81. 81● let px = @types.clamp_int(x + kx - 2, 0, w - 1)
  82. 82● let py = @types.clamp_int(y + ky - 2, 0, h - 1)
  83. 83 sum += gray[py * w + px] * kernel[ky * 5 + kx]
  84. 84 }
  85. 85 }
  86. 86 out[y * w + x] = sum / kernel_sum
  87. 87 }
  88. 88 }
  89. 89 out
  90. 90}
  91. 91
  92. 92// ========== 16-bit Canny ==========
  93. 93
  94. 94///|
  95. 95/// 16-bit Canny 边缘检测。阈值范围 0-65535,输出二值图像(0/65535)。
  96. 96/// @see canny_edge 8-bit 版本,本函数为 Image16 变体
  97. 97pub fn canny_edge_16(
  98. 98 img : @types.Image16,
  99. 99 low_threshold~ : Int32 = 12800,
  100. 100 high_threshold~ : Int32 = 25600,
  101. 101) -> @types.Image16 raise @types.LoadError {
  102. 102 // 输入验证
  103. 103● if img.width <= 0 || img.height <= 0 {
  104. 104● raise @types.LoadError::DecodeFailed(
  105. 105 "canny_edge_16: 图像尺寸必须大于0",
  106. 106 )
  107. 107 }
  108. 108 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  109. 109● raise @types.LoadError::DecodeFailed(
  110. 110 "canny_edge_16: 仅支持 channels=1/3/4",
  111. 111 )
  112. 112 }
  113. 113 let expected_size = img.width * img.height * img.channels * 2
  114. 114● if img.data.length() != expected_size {
  115. 115● raise @types.LoadError::DecodeFailed(
  116. 116 "canny_edge_16: 数据大小不匹配,期望 " +
  117. 117● expected_size.to_string() +
  118. 118 ",实际 " +
  119. 119● img.data.length().to_string(),
  120. 120 )
  121. 121 }
  122. 122 if low_threshold < 0 || low_threshold > 65535 {
  123. 123● raise @types.LoadError::DecodeFailed(
  124. 124 "low_threshold 必须在 0..65535 之间",
  125. 125 )
  126. 126 }
  127. 127 if high_threshold < 0 || high_threshold > 65535 {
  128. 128● raise @types.LoadError::DecodeFailed(
  129. 129 "high_threshold 必须在 0..65535 之间",
  130. 130 )
  131. 131 }
  132. 132 if low_threshold > high_threshold {
  133. 133● raise @types.LoadError::DecodeFailed("low_threshold 应 <= high_threshold")
  134. 134 }
  135. 135 let w = img.width
  136. 136 let h = img.height
  137. 137 let n = w * h
  138. 138 if n == 0 {
  139. 139○ return img
  140. 140 }
  141. 141 let ch = img.channels
  142. 142 let bpp = ch * 2
  143. 143 // 转灰度
  144. 144● let gray : Array[Int32] = Array::make(n, 0)
  145. 145 for i in 0..<n {
  146. 146● if ch == 1 {
  147. 147● gray[i] = read_u16_le_c(img.data, i * 2)
  148. 148 } else {
  149. 149● let r = read_u16_le_c(img.data, i * bpp)
  150. 150● let g = read_u16_le_c(img.data, i * bpp + 2)
  151. 151● let b = read_u16_le_c(img.data, i * bpp + 4)
  152. 152 gray[i] = (r * 299 + g * 587 + b * 114) / 1000
  153. 153 }
  154. 154 }
  155. 155 // 1. 高斯模糊
  156. 156● let blurred = canny_gaussian_blur_16(gray, w, h)
  157. 157 // 2. Sobel 梯度
  158. 158● let gradient : Array[Int32] = Array::make(n, 0)
  159. 159● let direction : Array[Int32] = Array::make(n, 0)
  160. 160 for y in 1..<(h - 1) {
  161. 161● for x in 1..<(w - 1) {
  162. 162● let idx = y * w + x
  163. 163 let gx = -blurred[(y - 1) * w + (x - 1)] -
  164. 164 2 * blurred[y * w + (x - 1)] -
  165. 165 blurred[(y + 1) * w + (x - 1)] +
  166. 166 blurred[(y - 1) * w + (x + 1)] +
  167. 167 2 * blurred[y * w + (x + 1)] +
  168. 168 blurred[(y + 1) * w + (x + 1)]
  169. 169 let gy = -blurred[(y - 1) * w + (x - 1)] -
  170. 170 2 * blurred[(y - 1) * w + x] -
  171. 171 blurred[(y - 1) * w + (x + 1)] +
  172. 172 blurred[(y + 1) * w + (x - 1)] +
  173. 173 2 * blurred[(y + 1) * w + x] +
  174. 174 blurred[(y + 1) * w + (x + 1)]
  175. 175● let mag = Float::from_int(gx * gx + gy * gy).sqrt().to_int()
  176. 176 gradient[idx] = mag
  177. 177● let angle = @math.atan2f(Float::from_int(gy), Float::from_int(gx)) *
  178. 178 180.0F /
  179. 179 3.14159265F
  180. 180● let norm_angle = if angle < 0.0F { angle + 180.0F } else { angle }
  181. 181 direction[idx] = if norm_angle < 22.5F || norm_angle >= 157.5F {
  182. 182● 0
  183. 183● } else if norm_angle < 67.5F {
  184. 184○ 1
  185. 185● } else if norm_angle < 112.5F {
  186. 186● 2
  187. 187 } else {
  188. 188○ 3
  189. 189 }
  190. 190 }
  191. 191 }
  192. 192 // 3. 非极大值抑制
  193. 193● let nms : Array[Int32] = Array::make(n, 0)
  194. 194 for y in 1..<(h - 1) {
  195. 195● for x in 1..<(w - 1) {
  196. 196● let idx = y * w + x
  197. 197 let mag = gradient[idx]
  198. 198 if mag == 0 {
  199. 199● continue
  200. 200 }
  201. 201 let dir = direction[idx]
  202. 202● let (n1, n2) = match dir {
  203. 203○ 0 => (gradient[idx - 1], gradient[idx + 1])
  204. 204○ 1 => (gradient[(y - 1) * w + (x + 1)], gradient[(y + 1) * w + (x - 1)])
  205. 205● 2 => (gradient[(y - 1) * w + x], gradient[(y + 1) * w + x])
  206. 206○ _ => (gradient[(y - 1) * w + (x - 1)], gradient[(y + 1) * w + (x + 1)])
  207. 207 }
  208. 208 if mag >= n1 && mag >= n2 {
  209. 209● nms[idx] = mag
  210. 210 }
  211. 211 }
  212. 212 }
  213. 213 // 4. 双阈值 + 滞后连接
  214. 214● let out : Array[Byte] = Array::make(n * 2, b'\x00')
  215. 215● let strong : Array[Bool] = Array::make(n, false)
  216. 216● let weak : Array[Bool] = Array::make(n, false)
  217. 217 for i in 0..<n {
  218. 218● if nms[i] >= high_threshold {
  219. 219● strong[i] = true
  220. 220● } else if nms[i] >= low_threshold {
  221. 221○ weak[i] = true
  222. 222 }
  223. 223 }
  224. 224 let stack : Array[Int32] = []
  225. 225 for i in 0..<n {
  226. 226● if strong[i] {
  227. 227● write_u16_le_c(out, i * 2, 65535)
  228. 228● stack.push(i)
  229. 229 }
  230. 230 }
  231. 231● while stack.length() > 0 {
  232. 232● let idx = stack.remove(stack.length() - 1)
  233. 233 let x = idx % w
  234. 234 let y = idx / w
  235. 235 for dy in -1..<=1 {
  236. 236● for dx in -1..<=1 {
  237. 237● if dx == 0 && dy == 0 {
  238. 238● continue
  239. 239 }
  240. 240 let nx = x + dx
  241. 241 let ny = y + dy
  242. 242 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  243. 243● let nidx = ny * w + nx
  244. 244 if weak[nidx] && !strong[nidx] {
  245. 245○ strong[nidx] = true
  246. 246○ write_u16_le_c(out, nidx * 2, 65535)
  247. 247○ stack.push(nidx)
  248. 248 }
  249. 249 }
  250. 250 }
  251. 251 }
  252. 252 }
  253. 253 @types.Image16::{
  254. 254 width: w,
  255. 255 height: h,
  256. 256 channels: 1,
  257. 257● data: Bytes::from_array(out),
  258. 258 }
  259. 259}
  260. 260
  261. 261// ========== float Canny ==========
  262. 262
  263. 263///|
  264. 264/// float Canny 边缘检测。阈值范围 0.0-1.0,输出二值图像(0.0/1.0)。
  265. 265/// @see canny_edge 8-bit 版本,本函数为 ImageF 变体
  266. 266pub fn canny_edge_f(
  267. 267 img : @types.ImageF,
  268. 268 low_threshold~ : Float = 0.2F,
  269. 269 high_threshold~ : Float = 0.4F,
  270. 270) -> @types.ImageF raise @types.LoadError {
  271. 271 // 输入验证
  272. 272● if img.width <= 0 || img.height <= 0 {
  273. 273● raise @types.LoadError::DecodeFailed(
  274. 274 "canny_edge_f: 图像尺寸必须大于0",
  275. 275 )
  276. 276 }
  277. 277 if img.channels != 1 && img.channels != 3 && img.channels != 4 {
  278. 278● raise @types.LoadError::DecodeFailed(
  279. 279 "canny_edge_f: 仅支持 channels=1/3/4",
  280. 280 )
  281. 281 }
  282. 282 let expected_size = img.width * img.height * img.channels * 4
  283. 283● if img.data.length() != expected_size {
  284. 284● raise @types.LoadError::DecodeFailed(
  285. 285 "canny_edge_f: 数据大小不匹配,期望 " +
  286. 286● expected_size.to_string() +
  287. 287 ",实际 " +
  288. 288● img.data.length().to_string(),
  289. 289 )
  290. 290 }
  291. 291 if low_threshold < 0.0F || low_threshold > 1.0F {
  292. 292● raise @types.LoadError::DecodeFailed(
  293. 293 "low_threshold 必须在 0.0..1.0 之间",
  294. 294 )
  295. 295 }
  296. 296 if high_threshold < 0.0F || high_threshold > 1.0F {
  297. 297● raise @types.LoadError::DecodeFailed(
  298. 298 "high_threshold 必须在 0.0..1.0 之间",
  299. 299 )
  300. 300 }
  301. 301 if low_threshold > high_threshold {
  302. 302● raise @types.LoadError::DecodeFailed("low_threshold 应 <= high_threshold")
  303. 303 }
  304. 304 let w = img.width
  305. 305 let h = img.height
  306. 306 let n = w * h
  307. 307 if n == 0 {
  308. 308○ return img
  309. 309 }
  310. 310 let ch = img.channels
  311. 311 let bpp = ch * 4
  312. 312 // 转灰度
  313. 313● let gray : Array[Float] = Array::make(n, 0.0F)
  314. 314 for i in 0..<n {
  315. 315● if ch == 1 {
  316. 316● gray[i] = read_float_le_c(img.data, i * 4)
  317. 317 } else {
  318. 318● let r = read_float_le_c(img.data, i * bpp)
  319. 319● let g = read_float_le_c(img.data, i * bpp + 4)
  320. 320● let b = read_float_le_c(img.data, i * bpp + 8)
  321. 321 gray[i] = r * 0.299F + g * 0.587F + b * 0.114F
  322. 322 }
  323. 323 }
  324. 324 // 1. 高斯模糊 (5x5, sigma=1.0)
  325. 325● let blurred : Array[Float] = Array::make(n, 0.0F)
  326. 326 let kernel : Array[Float] = [
  327. 327 2.0F, 4.0F, 5.0F, 4.0F, 2.0F, 4.0F, 9.0F, 12.0F, 9.0F, 4.0F, 5.0F, 12.0F, 15.0F,
  328. 328 12.0F, 5.0F, 4.0F, 9.0F, 12.0F, 9.0F, 4.0F, 2.0F, 4.0F, 5.0F, 4.0F, 2.0F,
  329. 329 ]
  330. 330 let kernel_sum = 159.0F
  331. 331 for y in 2..<(h - 2) {
  332. 332● for x in 2..<(w - 2) {
  333. 333● let mut sum = 0.0F
  334. 334 let base = (y - 2) * w + (x - 2)
  335. 335 for ky in 0..<5 {
  336. 336● let row = base + ky * w
  337. 337 let krow = ky * 5
  338. 338 for kx in 0..<5 {
  339. 339● sum += gray[row + kx] * kernel[krow + kx]
  340. 340 }
  341. 341 }
  342. 342 blurred[y * w + x] = sum / kernel_sum
  343. 343 }
  344. 344 }
  345. 345 for y in 0..<h {
  346. 346● let y_inner = y >= 2 && y < h - 2
  347. 347 for x in 0..<w {
  348. 348● if y_inner && x >= 2 && x < w - 2 {
  349. 349● continue
  350. 350 }
  351. 351 let mut sum = 0.0F
  352. 352 for ky in 0..<5 {
  353. 353● for kx in 0..<5 {
  354. 354● let px = @types.clamp_int(x + kx - 2, 0, w - 1)
  355. 355● let py = @types.clamp_int(y + ky - 2, 0, h - 1)
  356. 356 sum += gray[py * w + px] * kernel[ky * 5 + kx]
  357. 357 }
  358. 358 }
  359. 359 blurred[y * w + x] = sum / kernel_sum
  360. 360 }
  361. 361 }
  362. 362 // 2. Sobel 梯度
  363. 363● let gradient : Array[Float] = Array::make(n, 0.0F)
  364. 364● let direction : Array[Int32] = Array::make(n, 0)
  365. 365 for y in 1..<(h - 1) {
  366. 366● for x in 1..<(w - 1) {
  367. 367● let idx = y * w + x
  368. 368 let gx = -blurred[(y - 1) * w + (x - 1)] -
  369. 369 2.0F * blurred[y * w + (x - 1)] -
  370. 370 blurred[(y + 1) * w + (x - 1)] +
  371. 371 blurred[(y - 1) * w + (x + 1)] +
  372. 372 2.0F * blurred[y * w + (x + 1)] +
  373. 373 blurred[(y + 1) * w + (x + 1)]
  374. 374 let gy = -blurred[(y - 1) * w + (x - 1)] -
  375. 375 2.0F * blurred[(y - 1) * w + x] -
  376. 376 blurred[(y - 1) * w + (x + 1)] +
  377. 377 blurred[(y + 1) * w + (x - 1)] +
  378. 378 2.0F * blurred[(y + 1) * w + x] +
  379. 379 blurred[(y + 1) * w + (x + 1)]
  380. 380● let mag = (gx * gx + gy * gy).sqrt()
  381. 381 gradient[idx] = mag
  382. 382● let angle = @math.atan2f(gy, gx) * 180.0F / 3.14159265F
  383. 383● let norm_angle = if angle < 0.0F { angle + 180.0F } else { angle }
  384. 384 direction[idx] = if norm_angle < 22.5F || norm_angle >= 157.5F {
  385. 385● 0
  386. 386● } else if norm_angle < 67.5F {
  387. 387● 1
  388. 388● } else if norm_angle < 112.5F {
  389. 389● 2
  390. 390 } else {
  391. 391● 3
  392. 392 }
  393. 393 }
  394. 394 }
  395. 395 // 3. 非极大值抑制
  396. 396● let nms : Array[Float] = Array::make(n, 0.0F)
  397. 397 for y in 1..<(h - 1) {
  398. 398● for x in 1..<(w - 1) {
  399. 399● let idx = y * w + x
  400. 400 let mag = gradient[idx]
  401. 401 if mag == 0.0F {
  402. 402● continue
  403. 403 }
  404. 404 let dir = direction[idx]
  405. 405● let (n1, n2) = match dir {
  406. 406● 0 => (gradient[idx - 1], gradient[idx + 1])
  407. 407● 1 => (gradient[(y - 1) * w + (x + 1)], gradient[(y + 1) * w + (x - 1)])
  408. 408● 2 => (gradient[(y - 1) * w + x], gradient[(y + 1) * w + x])
  409. 409● _ => (gradient[(y - 1) * w + (x - 1)], gradient[(y + 1) * w + (x + 1)])
  410. 410 }
  411. 411 if mag >= n1 && mag >= n2 {
  412. 412● nms[idx] = mag
  413. 413 }
  414. 414 }
  415. 415 }
  416. 416 // 4. 双阈值 + 滞后连接
  417. 417● let out : Array[Byte] = Array::make(n * 4, b'\x00')
  418. 418● let strong : Array[Bool] = Array::make(n, false)
  419. 419● let weak : Array[Bool] = Array::make(n, false)
  420. 420 for i in 0..<n {
  421. 421● if nms[i] >= high_threshold {
  422. 422● strong[i] = true
  423. 423● } else if nms[i] >= low_threshold {
  424. 424● weak[i] = true
  425. 425 }
  426. 426 }
  427. 427 let stack : Array[Int32] = []
  428. 428 for i in 0..<n {
  429. 429● if strong[i] {
  430. 430● write_f32_le_c(out, i * 4, 1.0F)
  431. 431● stack.push(i)
  432. 432 }
  433. 433 }
  434. 434● while stack.length() > 0 {
  435. 435● let idx = stack.remove(stack.length() - 1)
  436. 436 let x = idx % w
  437. 437 let y = idx / w
  438. 438 for dy in -1..<=1 {
  439. 439● for dx in -1..<=1 {
  440. 440● if dx == 0 && dy == 0 {
  441. 441● continue
  442. 442 }
  443. 443 let nx = x + dx
  444. 444 let ny = y + dy
  445. 445 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  446. 446● let nidx = ny * w + nx
  447. 447 if weak[nidx] && !strong[nidx] {
  448. 448● strong[nidx] = true
  449. 449● write_f32_le_c(out, nidx * 4, 1.0F)
  450. 450● stack.push(nidx)
  451. 451 }
  452. 452 }
  453. 453 }
  454. 454 }
  455. 455 }
  456. 456 @types.ImageF::{
  457. 457 width: w,
  458. 458 height: h,
  459. 459 channels: 1,
  460. 460● data: Bytes::from_array(out),
  461. 461 }
  462. 462}