image.process\segment\segmentation.mbt

99.3% · 150 / 151 points · 417 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/// # 图像分割 segmentation
  3. 3///
  4. 4/// 图像处理算法模块
  5. 5/// 图像处理算法模块 Image processing algorithm module
  6. 6// 图像分割(v12.2.0)
  7. 7// 分水岭算法 + 区域生长 + 阈值分割
  8. 8
  9. 9///|
  10. 10/// 分割结果
  11. 11pub(all) struct SegmentationResult {
  12. 12 labels : Array[Int32] // 每个像素的标签
  13. 13 num_regions : Int32 // 区域数量
  14. 14 region_sizes : Array[Int32] // 每个区域的大小
  15. 15}
  16. 16
  17. 17///|
  18. 18/// 分水岭算法配置
  19. 19pub(all) struct WatershedConfig {
  20. 20 threshold : Double // 梯度阈值
  21. 21 min_region_size : Int32 // 最小区域大小
  22. 22 connectivity : Int32 // 连通性(4或8)
  23. 23}
  24. 24
  25. 25///|
  26. 26/// 创建默认分水岭配置
  27. 27pub fn watershed_default_config() -> WatershedConfig {
  28. 28● WatershedConfig::{ threshold: 10.0, min_region_size: 50, connectivity: 8, }
  29. 29}
  30. 30
  31. 31///|
  32. 32/// 计算图像梯度(Sobel)
  33. 33fn compute_gradient(img : @types.Image) -> Array[Double] {
  34. 34● let w = img.width
  35. 35 let h = img.height
  36. 36 let channels = img.channels
  37. 37 let data = img.data
  38. 38● let gradient : Array[Double] = Array::make(w * h, 0.0)
  39. 39 for y in 1..<(h - 1) {
  40. 40● for x in 1..<(w - 1) {
  41. 41● let _ = (y * w + x) * channels
  42. 42 // 灰度
  43. 43● let gray = (px, py) => {
  44. 44 let i = (py * w + px) * channels
  45. 45● let r = data[i].to_double()
  46. 46● let g = if channels >= 2 { data[i + 1].to_double() } else { r }
  47. 47● let b = if channels >= 3 { data[i + 2].to_double() } else { r }
  48. 48 0.299 * r + 0.587 * g + 0.114 * b
  49. 49 }
  50. 50● let gx = -gray(x - 1, y - 1) -
  51. 51● 2.0 * gray(x - 1, y) -
  52. 52● gray(x - 1, y + 1) +
  53. 53● gray(x + 1, y - 1) +
  54. 54● 2.0 * gray(x + 1, y) +
  55. 55● gray(x + 1, y + 1)
  56. 56● let gy = -gray(x - 1, y - 1) -
  57. 57● 2.0 * gray(x, y - 1) -
  58. 58● gray(x + 1, y - 1) +
  59. 59● gray(x - 1, y + 1) +
  60. 60● 2.0 * gray(x, y + 1) +
  61. 61● gray(x + 1, y + 1)
  62. 62● gradient[y * w + x] = (gx * gx + gy * gy).sqrt()
  63. 63 }
  64. 64 }
  65. 65 gradient
  66. 66}
  67. 67
  68. 68///|
  69. 69/// 分水岭算法(简化版)
  70. 70/// 基于梯度图像的区域生长分割
  71. 71pub fn watershed_segment(
  72. 72 img : @types.Image,
  73. 73 config? : WatershedConfig,
  74. 74) -> SegmentationResult {
  75. 75● let cfg = match config {
  76. 76● Some(c) => c
  77. 77● None => watershed_default_config()
  78. 78 }
  79. 79 let w = img.width
  80. 80 let h = img.height
  81. 81 // 1. 计算梯度
  82. 82● let gradient = compute_gradient(img)
  83. 83 // 2. 寻找局部最小值作为种子点
  84. 84● let labels : Array[Int32] = Array::make(w * h, 0)
  85. 85 let mut next_label = 1
  86. 86 let seeds : Array[(Int32, Int32)] = []
  87. 87 for y in 1..<(h - 1) {
  88. 88● for x in 1..<(w - 1) {
  89. 89● let g = gradient[y * w + x]
  90. 90 if g < cfg.threshold {
  91. 91 // 检查是否是局部最小值
  92. 92● let mut is_min = true
  93. 93 let neighbors = [
  94. 94 (-1, 0),
  95. 95 (1, 0),
  96. 96 (0, -1),
  97. 97 (0, 1),
  98. 98 (-1, -1),
  99. 99 (1, 1),
  100. 100 (-1, 1),
  101. 101 (1, -1),
  102. 102 ]
  103. 103 for _tup0 in neighbors {
  104. 104● let (dx, dy) = _tup0
  105. 105 if gradient[(y + dy) * w + (x + dx)] < g {
  106. 106● is_min = false
  107. 107 }
  108. 108 }
  109. 109 if is_min && labels[y * w + x] == 0 {
  110. 110● seeds.push((x, y))
  111. 111 labels[y * w + x] = next_label
  112. 112 next_label += 1
  113. 113 }
  114. 114 }
  115. 115 }
  116. 116 }
  117. 117 // 3. 区域生长(从种子点开始,按梯度从小到大扩展)
  118. 118 let mut changed = true
  119. 119 while changed {
  120. 120● changed = false
  121. 121 for y in 0..<h {
  122. 122● for x in 0..<w {
  123. 123● if labels[y * w + x] == 0 && gradient[y * w + x] < cfg.threshold * 2.0 {
  124. 124 // 检查邻域是否有已标记像素
  125. 125● let neighbors = if cfg.connectivity == 8 {
  126. 126● [
  127. 127 (-1, 0),
  128. 128 (1, 0),
  129. 129 (0, -1),
  130. 130 (0, 1),
  131. 131 (-1, -1),
  132. 132 (1, 1),
  133. 133 (-1, 1),
  134. 134 (1, -1),
  135. 135 ]
  136. 136 } else {
  137. 137● [(-1, 0), (1, 0), (0, -1), (0, 1)]
  138. 138 }
  139. 139 for _tup1 in neighbors {
  140. 140● let (dx, dy) = _tup1
  141. 141 let nx = x + dx
  142. 142 let ny = y + dy
  143. 143 if nx >= 0 && nx < w && ny >= 0 && ny < h && labels[ny * w + nx] > 0 {
  144. 144● labels[y * w + x] = labels[ny * w + nx]
  145. 145 changed = true
  146. 146 break
  147. 147 }
  148. 148 }
  149. 149 }
  150. 150 }
  151. 151 }
  152. 152 }
  153. 153 // 4. 合并小区域
  154. 154● let region_sizes : Array[Int32] = Array::make(next_label, 0)
  155. 155 for i in 0..<(w * h) {
  156. 156● if labels[i] > 0 {
  157. 157● region_sizes[labels[i]] += 1
  158. 158 }
  159. 159 }
  160. 160 // 小区域合并到相邻大区域
  161. 161 for label in 1..<next_label {
  162. 162● if region_sizes[label] < cfg.min_region_size {
  163. 163 // 找到第一个相邻的大区域
  164. 164● for y in 0..<h {
  165. 165● for x in 0..<w {
  166. 166● if labels[y * w + x] == label {
  167. 167● let neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
  168. 168 for _tup2 in neighbors {
  169. 169● let (dx, dy) = _tup2
  170. 170 let nx = x + dx
  171. 171 let ny = y + dy
  172. 172 if nx >= 0 &&
  173. 173 nx < w &&
  174. 174 ny >= 0 &&
  175. 175 ny < h &&
  176. 176 labels[ny * w + nx] > 0 &&
  177. 177 labels[ny * w + nx] != label &&
  178. 178 region_sizes[labels[ny * w + nx]] >= cfg.min_region_size {
  179. 179 // 合并
  180. 180● let old_label = label
  181. 181 let new_label = labels[ny * w + nx]
  182. 182 for i in 0..<(w * h) {
  183. 183● if labels[i] == old_label {
  184. 184● labels[i] = new_label
  185. 185 }
  186. 186 }
  187. 187 region_sizes[new_label] += region_sizes[old_label]
  188. 188 region_sizes[old_label] = 0
  189. 189 break
  190. 190 }
  191. 191 }
  192. 192 }
  193. 193 }
  194. 194 }
  195. 195 }
  196. 196 }
  197. 197 // 5. 重新编号标签
  198. 198● let label_map : Array[Int32] = Array::make(next_label, 0)
  199. 199 let mut new_num = 1
  200. 200 let new_sizes : Array[Int32] = []
  201. 201 for label in 1..<next_label {
  202. 202● if region_sizes[label] > 0 {
  203. 203● label_map[label] = new_num
  204. 204● new_sizes.push(region_sizes[label])
  205. 205 new_num += 1
  206. 206 }
  207. 207 }
  208. 208 for i in 0..<(w * h) {
  209. 209● if labels[i] > 0 {
  210. 210● labels[i] = label_map[labels[i]]
  211. 211 }
  212. 212 }
  213. 213 SegmentationResult::{
  214. 214 labels,
  215. 215 num_regions: new_num - 1,
  216. 216 region_sizes: new_sizes,
  217. 217 }
  218. 218}
  219. 219
  220. 220///|
  221. 221/// 区域生长分割
  222. 222/// 从种子点开始,根据相似度生长区域
  223. 223pub fn region_growing(
  224. 224 img : @types.Image,
  225. 225 seeds : Array[(Int32, Int32)],
  226. 226 threshold~ : Double = 30.0,
  227. 227) -> SegmentationResult {
  228. 228● let thresh = threshold
  229. 229 let w = img.width
  230. 230 let h = img.height
  231. 231 let channels = img.channels
  232. 232 let data = img.data
  233. 233● let labels : Array[Int32] = Array::make(w * h, 0)
  234. 234 let region_sizes : Array[Int32] = []
  235. 235 let mut label = 1
  236. 236 for _tup3 in seeds {
  237. 237● let (sx, sy) = _tup3
  238. 238 if sx < 0 || sx >= w || sy < 0 || sy >= h {
  239. 239● continue
  240. 240 }
  241. 241 if labels[sy * w + sx] > 0 {
  242. 242● continue
  243. 243 }
  244. 244 // 种子点颜色
  245. 245 let seed_idx = (sy * w + sx) * channels
  246. 246● let seed_r = data[seed_idx].to_double()
  247. 247 let seed_g = if channels >= 2 {
  248. 248● data[seed_idx + 1].to_double()
  249. 249 } else {
  250. 250● seed_r
  251. 251 }
  252. 252 let seed_b = if channels >= 3 {
  253. 253● data[seed_idx + 2].to_double()
  254. 254 } else {
  255. 255● seed_r
  256. 256 }
  257. 257 // 区域生长(洪水填充)
  258. 258 let stack : Array[(Int32, Int32)] = []
  259. 259● stack.push((sx, sy))
  260. 260 labels[sy * w + sx] = label
  261. 261 let mut size = 0
  262. 262● while stack.length() > 0 {
  263. 263● match stack.pop() {
  264. 264● Some((x, y)) => {
  265. 265 size += 1
  266. 266 let neighbors = [(-1, 0), (1, 0), (0, -1), (0, 1)]
  267. 267 for _tup4 in neighbors {
  268. 268● let (dx, dy) = _tup4
  269. 269 let nx = x + dx
  270. 270 let ny = y + dy
  271. 271 if nx >= 0 &&
  272. 272 nx < w &&
  273. 273 ny >= 0 &&
  274. 274 ny < h &&
  275. 275 labels[ny * w + nx] == 0 {
  276. 276● let idx = (ny * w + nx) * channels
  277. 277● let r = data[idx].to_double()
  278. 278● let g = if channels >= 2 { data[idx + 1].to_double() } else { r }
  279. 279● let b = if channels >= 3 { data[idx + 2].to_double() } else { r }
  280. 280 let dist = ((r - seed_r) * (r - seed_r) +
  281. 281 (g - seed_g) * (g - seed_g) +
  282. 282● (b - seed_b) * (b - seed_b)).sqrt()
  283. 283 if dist < thresh {
  284. 284● labels[ny * w + nx] = label
  285. 285● stack.push((nx, ny))
  286. 286 }
  287. 287 }
  288. 288 }
  289. 289 }
  290. 290○ None => ignore(())
  291. 291 }
  292. 292 }
  293. 293● region_sizes.push(size)
  294. 294 label += 1
  295. 295 }
  296. 296 SegmentationResult::{ labels, num_regions: label - 1, region_sizes, }
  297. 297}
  298. 298
  299. 299///|
  300. 300/// 阈值分割(Otsu 自动阈值)
  301. 301pub fn threshold_otsu(img : @types.Image) -> @types.Image {
  302. 302● let w = img.width
  303. 303 let h = img.height
  304. 304 let channels = img.channels
  305. 305 let data = img.data
  306. 306 // 计算灰度直方图
  307. 307● let histogram : Array[Int32] = Array::make(256, 0)
  308. 308 for i in 0..<(w * h) {
  309. 309● let idx = i * channels
  310. 310● let r = data[idx].to_int()
  311. 311● let g = if channels >= 2 { data[idx + 1].to_int() } else { r }
  312. 312● let b = if channels >= 3 { data[idx + 2].to_int() } else { r }
  313. 313● let gray = (0.299 * r.to_double() +
  314. 314● 0.587 * g.to_double() +
  315. 315● 0.114 * b.to_double()).to_int()
  316. 316 histogram[gray] += 1
  317. 317 }
  318. 318 // Otsu 阈值计算
  319. 319 let total = w * h
  320. 320 let mut sum = 0
  321. 321 for t in 0..<256 {
  322. 322● sum += t * histogram[t]
  323. 323 }
  324. 324 let mut sum_b = 0
  325. 325 let mut w_b = 0
  326. 326 let mut max_variance = 0.0
  327. 327 let mut threshold = 128
  328. 328 for t in 0..<256 {
  329. 329● w_b += histogram[t]
  330. 330 if w_b == 0 {
  331. 331● continue
  332. 332 }
  333. 333 let w_f = total - w_b
  334. 334 if w_f == 0 {
  335. 335● break
  336. 336 }
  337. 337 sum_b += t * histogram[t]
  338. 338● let m_b = sum_b.to_double() / w_b.to_double()
  339. 339● let m_f = (sum - sum_b).to_double() / w_f.to_double()
  340. 340● let variance = w_b.to_double() * w_f.to_double() * (m_b - m_f) * (m_b - m_f)
  341. 341 if variance > max_variance {
  342. 342● max_variance = variance
  343. 343 threshold = t
  344. 344 }
  345. 345 }
  346. 346 // 应用阈值
  347. 347● let out_data : Array[Byte] = Array::make(w * h * channels, b'\x00')
  348. 348 for i in 0..<(w * h) {
  349. 349● let idx = i * channels
  350. 350● let r = data[idx].to_int()
  351. 351● let g = if channels >= 2 { data[idx + 1].to_int() } else { r }
  352. 352● let b = if channels >= 3 { data[idx + 2].to_int() } else { r }
  353. 353● let gray = (0.299 * r.to_double() +
  354. 354● 0.587 * g.to_double() +
  355. 355● 0.114 * b.to_double()).to_int()
  356. 356● let value = if gray > threshold { 255 } else { 0 }
  357. 357 for c in 0..<channels {
  358. 358● out_data[idx + c] = value.to_byte()
  359. 359 }
  360. 360 }
  361. 361 @types.Image::{
  362. 362 width: w,
  363. 363 height: h,
  364. 364 channels,
  365. 365● data: Bytes::from_array(out_data),
  366. 366 }
  367. 367}
  368. 368
  369. 369///|
  370. 370/// 将分割结果可视化为彩色图像
  371. 371pub fn segmentation_to_color(
  372. 372 result : SegmentationResult,
  373. 373 width : Int32,
  374. 374 height : Int32,
  375. 375) -> @types.Image {
  376. 376● let colors = [
  377. 377 (255, 0, 0),
  378. 378 (0, 255, 0),
  379. 379 (0, 0, 255),
  380. 380 (255, 255, 0),
  381. 381 (255, 0, 255),
  382. 382 (0, 255, 255),
  383. 383 (128, 0, 0),
  384. 384 (0, 128, 0),
  385. 385 (0, 0, 128),
  386. 386 (128, 128, 0),
  387. 387 (128, 0, 128),
  388. 388 (0, 128, 128),
  389. 389 (192, 192, 192),
  390. 390 (128, 128, 128),
  391. 391 (255, 128, 0),
  392. 392 (255, 0, 128),
  393. 393 ]
  394. 394● let out_data : Array[Byte] = Array::make(width * height * 3, b'\x00')
  395. 395 for y in 0..<height {
  396. 396● for x in 0..<width {
  397. 397● let label = result.labels[y * width + x]
  398. 398 let idx = (y * width + x) * 3
  399. 399● if label > 0 && label <= colors.length() {
  400. 400● let (r, g, b) = colors[label - 1]
  401. 401● out_data[idx] = r.to_byte()
  402. 402● out_data[idx + 1] = g.to_byte()
  403. 403● out_data[idx + 2] = b.to_byte()
  404. 404 } else {
  405. 405● out_data[idx] = b'\x00'
  406. 406 out_data[idx + 1] = b'\x00'
  407. 407 out_data[idx + 2] = b'\x00'
  408. 408 }
  409. 409 }
  410. 410 }
  411. 411 @types.Image::{
  412. 412 width,
  413. 413 height,
  414. 414 channels: 3,
  415. 415● data: Bytes::from_array(out_data),
  416. 416 }
  417. 417}