image.process\segment\segment.mbt

93.2% · 124 / 133 points · 461 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/// # 分割 segment
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 图像分割(纯 MoonBit):kmeans_segment / region_growing_segment / flood_fill / segment_to_color
  7. 7
  8. 8///|
  9. 9/// 分割标签图
  10. 10pub(all) struct SegmentLabelImage {
  11. 11 width : Int32
  12. 12 height : Int32
  13. 13 labels : Array[Int32] // 每个像素的标签(0=背景,1..N=区域)
  14. 14 num_regions : Int32
  15. 15}
  16. 16
  17. 17///|
  18. 18/// 分割区域信息
  19. 19pub struct SegmentRegion {
  20. 20 label : Int32 // 标签号
  21. 21 area : Int32 // 像素数
  22. 22 mean_r : Int32 // 平均颜色 R
  23. 23 mean_g : Int32 // 平均颜色 G
  24. 24 mean_b : Int32 // 平均颜色 B
  25. 25 bbox_x : Int32
  26. 26 bbox_y : Int32
  27. 27 bbox_w : Int32
  28. 28 bbox_h : Int32
  29. 29}
  30. 30
  31. 31///|
  32. 32/// K-means 颜色分割。将图像像素按颜色聚为 k 类,返回标签图和区域信息。
  33. 33/// 适用于 RGB/RGBA 图像(channels=3/4)。
  34. 34pub fn kmeans_segment(
  35. 35 img : @types.Image,
  36. 36 k : Int32,
  37. 37 max_iters~ : Int32 = 20,
  38. 38) -> (SegmentLabelImage, Array[SegmentRegion]) raise @types.LoadError {
  39. 39● if k < 1 || k > 256 {
  40. 40● raise @types.LoadError::DecodeFailed("k 必须在 1..256 之间")
  41. 41 }
  42. 42 if img.channels != 3 && img.channels != 4 {
  43. 43● raise @types.LoadError::DecodeFailed(
  44. 44 "kmeans_segment 需要 RGB/RGBA 图像",
  45. 45 )
  46. 46 }
  47. 47 let ch = img.channels
  48. 48 let w = img.width
  49. 49 let h = img.height
  50. 50 let n = w * h
  51. 51 if n == 0 {
  52. 52● return (
  53. 53 SegmentLabelImage::{ width: w, height: h, labels: [], num_regions: 0, },
  54. 54 [],
  55. 55 )
  56. 56 }
  57. 57 // 初始化聚类中心
  58. 58● let centroids_r : Array[Int32] = Array::make(k, 0)
  59. 59● let centroids_g : Array[Int32] = Array::make(k, 0)
  60. 60● let centroids_b : Array[Int32] = Array::make(k, 0)
  61. 61● let data_int : Array[Int32] = Array::make(n * ch, 0)
  62. 62 for i in 0..<(n * ch) {
  63. 63● data_int[i] = img.data[i].to_int()
  64. 64 }
  65. 65● let step = if n > k { n / k } else { 1 }
  66. 66 for i in 0..<k {
  67. 67● let idx = (i * step).clamp(min=0, max=n - 1)
  68. 68 centroids_r[i] = data_int[idx * ch]
  69. 69 centroids_g[i] = data_int[idx * ch + 1]
  70. 70 centroids_b[i] = data_int[idx * ch + 2]
  71. 71 }
  72. 72● let labels : Array[Int32] = Array::make(n, 0)
  73. 73◐ let iters = if max_iters < 1 { 20 } else { max_iters }
  74. 74 for _ in 0..<iters {
  75. 75● let mut changed = false
  76. 76 for i in 0..<n {
  77. 77● let r = data_int[i * ch]
  78. 78 let g = data_int[i * ch + 1]
  79. 79 let b = data_int[i * ch + 2]
  80. 80 let mut best = 0
  81. 81● let mut best_dist = color_dist_sq(
  82. 82 r,
  83. 83 g,
  84. 84 b,
  85. 85 centroids_r[0],
  86. 86 centroids_g[0],
  87. 87 centroids_b[0],
  88. 88 )
  89. 89 for j in 1..<k {
  90. 90● let d = color_dist_sq(
  91. 91 r,
  92. 92 g,
  93. 93 b,
  94. 94 centroids_r[j],
  95. 95 centroids_g[j],
  96. 96 centroids_b[j],
  97. 97 )
  98. 98 if d < best_dist {
  99. 99● best_dist = d
  100. 100 best = j
  101. 101 }
  102. 102 }
  103. 103 if labels[i] != best {
  104. 104● changed = true
  105. 105 labels[i] = best
  106. 106 }
  107. 107 }
  108. 108 if !changed {
  109. 109● break
  110. 110 }
  111. 111● let sum_r : Array[Int32] = Array::make(k, 0)
  112. 112● let sum_g : Array[Int32] = Array::make(k, 0)
  113. 113● let sum_b : Array[Int32] = Array::make(k, 0)
  114. 114● let cnt : Array[Int32] = Array::make(k, 0)
  115. 115 for i in 0..<n {
  116. 116● let label = labels[i]
  117. 117 sum_r[label] += data_int[i * ch]
  118. 118 sum_g[label] += data_int[i * ch + 1]
  119. 119 sum_b[label] += data_int[i * ch + 2]
  120. 120 cnt[label] += 1
  121. 121 }
  122. 122 for j in 0..<k {
  123. 123● if cnt[j] > 0 {
  124. 124● centroids_r[j] = sum_r[j] / cnt[j]
  125. 125 centroids_g[j] = sum_g[j] / cnt[j]
  126. 126 centroids_b[j] = sum_b[j] / cnt[j]
  127. 127 }
  128. 128 }
  129. 129 }
  130. 130● let regions = compute_regions(data_int, labels, w, h, ch, k)
  131. 131 (SegmentLabelImage::{ width: w, height: h, labels, num_regions: k, }, regions)
  132. 132}
  133. 133
  134. 134///|
  135. 135/// 区域生长分割。从指定种子点出发,按颜色相似性(阈值 threshold)生长区域。
  136. 136/// seeds 为种子点坐标数组 [(x, y), ...]。
  137. 137/// 适用于 RGB/RGBA 图像(channels=3/4)。
  138. 138pub fn region_growing_segment(
  139. 139 img : @types.Image,
  140. 140 seeds : Array[(Int32, Int32)],
  141. 141 threshold~ : Int32 = 30,
  142. 142) -> (SegmentLabelImage, Array[SegmentRegion]) raise @types.LoadError {
  143. 143● if img.channels != 3 && img.channels != 4 {
  144. 144● raise @types.LoadError::DecodeFailed(
  145. 145 "region_growing_segment 需要 RGB/RGBA 图像",
  146. 146 )
  147. 147 }
  148. 148 let ch = img.channels
  149. 149 let w = img.width
  150. 150 let h = img.height
  151. 151 let n = w * h
  152. 152● let labels : Array[Int32] = Array::make(n, 0)
  153. 153 let regions : Array[SegmentRegion] = []
  154. 154● let data_int : Array[Int32] = Array::make(n * ch, 0)
  155. 155 for i in 0..<(n * ch) {
  156. 156● data_int[i] = img.data[i].to_int()
  157. 157 }
  158. 158 let mut current_label = 0
  159. 159 for seed in seeds {
  160. 160● let (sx, sy) = seed
  161. 161 if sx < 0 || sx >= w || sy < 0 || sy >= h {
  162. 162● continue
  163. 163 }
  164. 164 let seed_idx = sy * w + sx
  165. 165 if labels[seed_idx] != 0 {
  166. 166○ continue // 已分配
  167. 167 }
  168. 168 current_label += 1
  169. 169 let seed_r = data_int[seed_idx * ch]
  170. 170 let seed_g = data_int[seed_idx * ch + 1]
  171. 171 let seed_b = data_int[seed_idx * ch + 2]
  172. 172 // BFS 区域生长
  173. 173 let stack : Array[Int32] = [seed_idx]
  174. 174 labels[seed_idx] = current_label
  175. 175 let mut area = 0
  176. 176 let mut sum_r = 0
  177. 177 let mut sum_g = 0
  178. 178 let mut sum_b = 0
  179. 179 let mut min_x = sx
  180. 180 let mut max_x = sx
  181. 181 let mut min_y = sy
  182. 182 let mut max_y = sy
  183. 183● while stack.length() > 0 {
  184. 184● let idx = stack.remove(stack.length() - 1)
  185. 185 let px = idx % w
  186. 186 let py = idx / w
  187. 187 area += 1
  188. 188 sum_r += data_int[idx * ch]
  189. 189 sum_g += data_int[idx * ch + 1]
  190. 190 sum_b += data_int[idx * ch + 2]
  191. 191 if px < min_x {
  192. 192○ min_x = px
  193. 193 }
  194. 194 if px > max_x {
  195. 195● max_x = px
  196. 196 }
  197. 197 if py < min_y {
  198. 198○ min_y = py
  199. 199 }
  200. 200 if py > max_y {
  201. 201● max_y = py
  202. 202 }
  203. 203 // 4 邻域
  204. 204 let neighbors = [(px + 1, py), (px - 1, py), (px, py + 1), (px, py - 1)]
  205. 205 for nb in neighbors {
  206. 206● let (nx, ny) = nb
  207. 207 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  208. 208● let nidx = ny * w + nx
  209. 209 if labels[nidx] == 0 {
  210. 210● let nr = data_int[nidx * ch]
  211. 211 let ng = data_int[nidx * ch + 1]
  212. 212 let nb2 = data_int[nidx * ch + 2]
  213. 213● let dist = color_dist_sq(seed_r, seed_g, seed_b, nr, ng, nb2)
  214. 214 if dist <= threshold * threshold {
  215. 215● labels[nidx] = current_label
  216. 216● stack.push(nidx)
  217. 217 }
  218. 218 }
  219. 219 }
  220. 220 }
  221. 221 }
  222. 222● regions.push(SegmentRegion::{
  223. 223 label: current_label,
  224. 224 area,
  225. 225 mean_r: if area > 0 {
  226. 226● sum_r / area
  227. 227 } else {
  228. 228○ 0
  229. 229 },
  230. 230 mean_g: if area > 0 {
  231. 231● sum_g / area
  232. 232 } else {
  233. 233○ 0
  234. 234 },
  235. 235 mean_b: if area > 0 {
  236. 236● sum_b / area
  237. 237 } else {
  238. 238○ 0
  239. 239 },
  240. 240 bbox_x: min_x,
  241. 241 bbox_y: min_y,
  242. 242 bbox_w: max_x - min_x + 1,
  243. 243 bbox_h: max_y - min_y + 1,
  244. 244 })
  245. 245 }
  246. 246 (
  247. 247 SegmentLabelImage::{
  248. 248 width: w,
  249. 249 height: h,
  250. 250 labels,
  251. 251 num_regions: current_label,
  252. 252 },
  253. 253 regions,
  254. 254 )
  255. 255}
  256. 256
  257. 257///|
  258. 258/// 泛洪填充。从种子点 (seed_x, seed_y) 出发,填充与种子点颜色差异 <= threshold 的连通区域,
  259. 259/// 用 fill_color 替换。返回填充后的图像。
  260. 260/// 适用于 RGB/RGBA 图像(channels=3/4)。
  261. 261pub fn flood_fill(
  262. 262 img : @types.Image,
  263. 263 seed_x : Int32,
  264. 264 seed_y : Int32,
  265. 265 fill_color : Array[Byte],
  266. 266 threshold~ : Int32 = 0,
  267. 267) -> @types.Image raise @types.LoadError {
  268. 268● if img.channels != 3 && img.channels != 4 {
  269. 269● raise @types.LoadError::DecodeFailed("flood_fill 需要 RGB/RGBA 图像")
  270. 270 }
  271. 271 let ch = img.channels
  272. 272 let w = img.width
  273. 273 let h = img.height
  274. 274 let n = w * h
  275. 275 if seed_x < 0 || seed_x >= w || seed_y < 0 || seed_y >= h {
  276. 276● raise @types.LoadError::DecodeFailed("种子点越界")
  277. 277 }
  278. 278● let out : Array[Byte] = Array::make(n * ch, b'\x00')
  279. 279 for i in 0..<(n * ch) {
  280. 280● out[i] = img.data[i]
  281. 281 }
  282. 282● let data_int : Array[Int32] = Array::make(n * ch, 0)
  283. 283 for i in 0..<(n * ch) {
  284. 284● data_int[i] = img.data[i].to_int()
  285. 285 }
  286. 286 let seed_idx = seed_y * w + seed_x
  287. 287 let seed_r = data_int[seed_idx * ch]
  288. 288 let seed_g = data_int[seed_idx * ch + 1]
  289. 289 let seed_b = data_int[seed_idx * ch + 2]
  290. 290● let visited : Array[Bool] = Array::make(n, false)
  291. 291 let stack : Array[Int32] = [seed_idx]
  292. 292 visited[seed_idx] = true
  293. 293◐ let fill_ch = if ch >= 3 { 3 } else { 1 }
  294. 294● while stack.length() > 0 {
  295. 295● let idx = stack.remove(stack.length() - 1)
  296. 296 let px = idx % w
  297. 297 let py = idx / w
  298. 298 // 填充
  299. 299 for c in 0..<fill_ch {
  300. 300● if c < fill_color.length() {
  301. 301● out[idx * ch + c] = fill_color[c]
  302. 302 }
  303. 303 }
  304. 304 // 4 邻域
  305. 305 let neighbors = [(px + 1, py), (px - 1, py), (px, py + 1), (px, py - 1)]
  306. 306 for nb in neighbors {
  307. 307● let (nx, ny) = nb
  308. 308 if nx >= 0 && nx < w && ny >= 0 && ny < h {
  309. 309● let nidx = ny * w + nx
  310. 310 if !visited[nidx] {
  311. 311● let nr = data_int[nidx * ch]
  312. 312 let ng = data_int[nidx * ch + 1]
  313. 313 let nb2 = data_int[nidx * ch + 2]
  314. 314● let dist = color_dist_sq(seed_r, seed_g, seed_b, nr, ng, nb2)
  315. 315 if dist <= threshold * threshold {
  316. 316● visited[nidx] = true
  317. 317● stack.push(nidx)
  318. 318 }
  319. 319 }
  320. 320 }
  321. 321 }
  322. 322 }
  323. 323 @types.Image::{
  324. 324 width: w,
  325. 325 height: h,
  326. 326 channels: ch,
  327. 327● data: Bytes::from_array(out),
  328. 328 }
  329. 329}
  330. 330
  331. 331///|
  332. 332/// 将分割标签图可视化为彩色图像。每个标签分配一个不同颜色。
  333. 333pub fn segment_to_color(
  334. 334 seg : SegmentLabelImage,
  335. 335) -> @types.Image raise @types.LoadError {
  336. 336● let w = seg.width
  337. 337 let h = seg.height
  338. 338 let n = w * h
  339. 339● let out : Array[Byte] = Array::make(n * 3, b'\x00')
  340. 340 let num = seg.num_regions
  341. 341 for i in 0..<n {
  342. 342● let label = seg.labels[i]
  343. 343 if label >= 0 && label < num {
  344. 344● let hue = Float::from_int(
  345. 345◐ label * 360 / (if num > 0 { num } else { 1 }) % 360,
  346. 346 )
  347. 347● let (r, g, b) = @color.hsv_to_rgb(hue, 1.0F, 1.0F)
  348. 348● out[i * 3] = r.to_byte()
  349. 349● out[i * 3 + 1] = g.to_byte()
  350. 350● out[i * 3 + 2] = b.to_byte()
  351. 351 }
  352. 352 }
  353. 353 @types.Image::{
  354. 354 width: w,
  355. 355 height: h,
  356. 356 channels: 3,
  357. 357● data: Bytes::from_array(out),
  358. 358 }
  359. 359}
  360. 360
  361. 361///|
  362. 362fn color_dist_sq(
  363. 363 r1 : Int32,
  364. 364 g1 : Int32,
  365. 365 b1 : Int32,
  366. 366 r2 : Int32,
  367. 367 g2 : Int32,
  368. 368 b2 : Int32,
  369. 369) -> Int32 {
  370. 370● let dr = r1 - r2
  371. 371 let dg = g1 - g2
  372. 372 let db = b1 - b2
  373. 373 dr * dr + dg * dg + db * db
  374. 374}
  375. 375
  376. 376///|
  377. 377fn compute_regions(
  378. 378 data_int : Array[Int32],
  379. 379 labels : Array[Int32],
  380. 380 w : Int32,
  381. 381 h : Int32,
  382. 382 ch : Int32,
  383. 383 k : Int32,
  384. 384) -> Array[SegmentRegion] {
  385. 385● let sum_r : Array[Int32] = Array::make(k, 0)
  386. 386● let sum_g : Array[Int32] = Array::make(k, 0)
  387. 387● let sum_b : Array[Int32] = Array::make(k, 0)
  388. 388● let cnt : Array[Int32] = Array::make(k, 0)
  389. 389● let min_x : Array[Int32] = Array::make(k, w)
  390. 390● let min_y : Array[Int32] = Array::make(k, h)
  391. 391● let max_x : Array[Int32] = Array::make(k, 0)
  392. 392● let max_y : Array[Int32] = Array::make(k, 0)
  393. 393 for y in 0..<h {
  394. 394● for x in 0..<w {
  395. 395● let idx = y * w + x
  396. 396 let label = labels[idx]
  397. 397 if label >= 0 && label < k {
  398. 398● sum_r[label] += data_int[idx * ch]
  399. 399 sum_g[label] += data_int[idx * ch + 1]
  400. 400 sum_b[label] += data_int[idx * ch + 2]
  401. 401 cnt[label] += 1
  402. 402 if x < min_x[label] {
  403. 403● min_x[label] = x
  404. 404 }
  405. 405 if x > max_x[label] {
  406. 406● max_x[label] = x
  407. 407 }
  408. 408 if y < min_y[label] {
  409. 409● min_y[label] = y
  410. 410 }
  411. 411 if y > max_y[label] {
  412. 412● max_y[label] = y
  413. 413 }
  414. 414 }
  415. 415 }
  416. 416 }
  417. 417 let regions : Array[SegmentRegion] = []
  418. 418 for j in 0..<k {
  419. 419● let area = cnt[j]
  420. 420● regions.push(SegmentRegion::{
  421. 421 label: j,
  422. 422 area,
  423. 423 mean_r: if area > 0 {
  424. 424● sum_r[j] / area
  425. 425 } else {
  426. 426● 0
  427. 427 },
  428. 428 mean_g: if area > 0 {
  429. 429● sum_g[j] / area
  430. 430 } else {
  431. 431● 0
  432. 432 },
  433. 433 mean_b: if area > 0 {
  434. 434● sum_b[j] / area
  435. 435 } else {
  436. 436● 0
  437. 437 },
  438. 438 bbox_x: if area > 0 {
  439. 439● min_x[j]
  440. 440 } else {
  441. 441● 0
  442. 442 },
  443. 443 bbox_y: if area > 0 {
  444. 444● min_y[j]
  445. 445 } else {
  446. 446● 0
  447. 447 },
  448. 448 bbox_w: if area > 0 {
  449. 449● max_x[j] - min_x[j] + 1
  450. 450 } else {
  451. 451● 0
  452. 452 },
  453. 453 bbox_h: if area > 0 {
  454. 454● max_y[j] - min_y[j] + 1
  455. 455 } else {
  456. 456● 0
  457. 457 },
  458. 458 })
  459. 459 }
  460. 460 regions
  461. 461}