image.vision\ocr\connected_components.mbt

76.6% · 82 / 107 points · 403 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/// # 连通域 ocr/connected_components
  3. 3///
  4. 4/// 图像处理库子模块
  5. 5/// 图像处理库子模块 Image processing library submodule
  6. 6// 连通域分析
  7. 7// 完整的连通域标记、筛选、合并
  8. 8
  9. 9///|
  10. 10/// 连通域结构体
  11. 11#derive(Eq, @debug.Debug)
  12. 12pub(all) struct OcrConnectedComponent {
  13. 13 label : Int32
  14. 14 x : Int32
  15. 15 y : Int32
  16. 16 width : Int32
  17. 17 height : Int32
  18. 18 area : Int32
  19. 19 pixel_count : Int32
  20. 20 bounding_box : (Int32, Int32, Int32, Int32)
  21. 21 centroid : (Double, Double)
  22. 22}
  23. 23
  24. 24///|
  25. 25pub extend OcrConnectedComponent with Eq::{not_equal, equal}
  26. 26
  27. 27///|
  28. 28pub extend OcrConnectedComponent with @debug.Debug::{to_repr}
  29. 29
  30. 30///|
  31. 31/// 连通域标记结果
  32. 32#derive(Eq, @debug.Debug)
  33. 33pub(all) struct OcrConnectedComponentsResult {
  34. 34 labels : Array[Int32]
  35. 35 num_components : Int32
  36. 36 components : Array[OcrConnectedComponent]
  37. 37}
  38. 38
  39. 39///|
  40. 40pub extend OcrConnectedComponentsResult with Eq::{not_equal, equal}
  41. 41
  42. 42///|
  43. 43pub extend OcrConnectedComponentsResult with @debug.Debug::{to_repr}
  44. 44
  45. 45///|
  46. 46/// 二值图像连通域标记(4邻域或8邻域)
  47. 47/// 使用两遍扫描算法
  48. 48pub fn connected_components_analysis(
  49. 49 img : @types.Image,
  50. 50 connectivity~ : Int32 = 8,
  51. 51) -> OcrConnectedComponentsResult raise @types.LoadError {
  52. 52 // 输入验证
  53. 53● if img.width <= 0 || img.height <= 0 {
  54. 54● raise @types.LoadError::DecodeFailed(
  55. 55 "connected_components_analysis: 图像尺寸必须大于0",
  56. 56 )
  57. 57 }
  58. 58 if img.channels != 1 {
  59. 59● raise @types.LoadError::DecodeFailed(
  60. 60 "connected_components_analysis: 仅支持单通道二值图",
  61. 61 )
  62. 62 }
  63. 63 let expected_size = img.width * img.height
  64. 64● if img.data.length() != expected_size {
  65. 65● raise @types.LoadError::DecodeFailed(
  66. 66 "connected_components_analysis: 数据大小不匹配,期望 " +
  67. 67● expected_size.to_string() +
  68. 68 ",实际 " +
  69. 69● img.data.length().to_string(),
  70. 70 )
  71. 71 }
  72. 72 if connectivity != 4 && connectivity != 8 {
  73. 73● raise @types.LoadError::DecodeFailed(
  74. 74 "connected_components_analysis: connectivity必须为4或8",
  75. 75 )
  76. 76 }
  77. 77
  78. 78 let w = img.width
  79. 79 let h = img.height
  80. 80 let n = w * h
  81. 81 let data = img.data
  82. 82 // 第一遍:临时标记
  83. 83● let labels : Array[Int32] = Array::make(n, 0)
  84. 84 let mut next_label = 1
  85. 85 // 并查集(用于等价标签合并)
  86. 86● let parent : Array[Int32] = Array::make(n + 1, 0)
  87. 87 for i in 0..<(n + 1) {
  88. 88● parent[i] = i
  89. 89 }
  90. 90 // find 函数(路径压缩)
  91. 91 fn find(x : Int32, parent : Array[Int32]) -> Int32 {
  92. 92● let mut root = x
  93. 93 while parent[root] != root {
  94. 94● root = parent[root]
  95. 95 }
  96. 96 // 路径压缩
  97. 97 let mut curr = x
  98. 98 while parent[curr] != curr {
  99. 99● let next = parent[curr]
  100. 100 parent[curr] = root
  101. 101 curr = next
  102. 102 }
  103. 103 root
  104. 104 }
  105. 105 // union 函数
  106. 106 fn union(x : Int32, y : Int32, parent : Array[Int32]) -> Unit {
  107. 107● let rx = find(x, parent)
  108. 108● let ry = find(y, parent)
  109. 109 if rx != ry {
  110. 110● parent[rx] = ry
  111. 111 }
  112. 112 }
  113. 113 // 第一遍扫描
  114. 114 for y in 0..<h {
  115. 115● for x in 0..<w {
  116. 116● let idx = y * w + x
  117. 117● if data[idx].to_int() > 128 {
  118. 118 // 前景像素
  119. 119● let neighbors : Array[Int32] = []
  120. 120 // 左邻域
  121. 121 if x > 0 && labels[idx - 1] > 0 {
  122. 122● neighbors.push(labels[idx - 1])
  123. 123 }
  124. 124 // 上邻域
  125. 125 if y > 0 && labels[idx - w] > 0 {
  126. 126● neighbors.push(labels[idx - w])
  127. 127 }
  128. 128 if connectivity == 8 {
  129. 129 // 左上
  130. 130● if x > 0 && y > 0 && labels[idx - w - 1] > 0 {
  131. 131● neighbors.push(labels[idx - w - 1])
  132. 132 }
  133. 133 // 右上
  134. 134 if x < w - 1 && y > 0 && labels[idx - w + 1] > 0 {
  135. 135● neighbors.push(labels[idx - w + 1])
  136. 136 }
  137. 137 }
  138. 138● if neighbors.length() == 0 {
  139. 139 // 新标签
  140. 140● labels[idx] = next_label
  141. 141 next_label += 1
  142. 142 } else {
  143. 143 // 使用最小邻居标签
  144. 144● let mut min_label = neighbors[0]
  145. 145● for i in 1..<neighbors.length() {
  146. 146● if neighbors[i] < min_label {
  147. 147● min_label = neighbors[i]
  148. 148 }
  149. 149 }
  150. 150 labels[idx] = min_label
  151. 151 // 合并等价标签
  152. 152 for label in neighbors {
  153. 153● union(min_label, label, parent)
  154. 154 }
  155. 155 }
  156. 156 }
  157. 157 }
  158. 158 }
  159. 159 // 第二遍:应用并查集
  160. 160● let final_labels : Array[Int32] = Array::make(n, 0)
  161. 161● let label_map : Array[Int32] = Array::make(next_label, 0)
  162. 162 let mut num_components = 0
  163. 163 for i in 0..<n {
  164. 164● if labels[i] > 0 {
  165. 165● let root = find(labels[i], parent)
  166. 166 if label_map[root] == 0 {
  167. 167● num_components += 1
  168. 168 label_map[root] = num_components
  169. 169 }
  170. 170 final_labels[i] = label_map[root]
  171. 171 }
  172. 172 }
  173. 173 // 计算每个连通域的属性
  174. 174 let components : Array[OcrConnectedComponent] = []
  175. 175 for c in 1..<(num_components + 1) {
  176. 176● let mut min_x = w
  177. 177 let mut max_x = 0
  178. 178 let mut min_y = h
  179. 179 let mut max_y = 0
  180. 180 let mut pixel_count = 0
  181. 181 let mut sum_x = 0
  182. 182 let mut sum_y = 0
  183. 183 for y in 0..<h {
  184. 184● for x in 0..<w {
  185. 185● if final_labels[y * w + x] == c {
  186. 186● pixel_count += 1
  187. 187 sum_x += x
  188. 188 sum_y += y
  189. 189 if x < min_x {
  190. 190● min_x = x
  191. 191 }
  192. 192 if x > max_x {
  193. 193● max_x = x
  194. 194 }
  195. 195 if y < min_y {
  196. 196● min_y = y
  197. 197 }
  198. 198 if y > max_y {
  199. 199● max_y = y
  200. 200 }
  201. 201 }
  202. 202 }
  203. 203 }
  204. 204 if pixel_count > 0 {
  205. 205● let comp = OcrConnectedComponent::{
  206. 206 label: c,
  207. 207 x: min_x,
  208. 208 y: min_y,
  209. 209 width: max_x - min_x + 1,
  210. 210 height: max_y - min_y + 1,
  211. 211 area: (max_x - min_x + 1) * (max_y - min_y + 1),
  212. 212 pixel_count,
  213. 213 bounding_box: (min_x, min_y, max_x - min_x + 1, max_y - min_y + 1),
  214. 214 centroid: (
  215. 215● sum_x.to_double() / pixel_count.to_double(),
  216. 216● sum_y.to_double() / pixel_count.to_double(),
  217. 217 ),
  218. 218 }
  219. 219● components.push(comp)
  220. 220 }
  221. 221 }
  222. 222 OcrConnectedComponentsResult::{
  223. 223 labels: final_labels,
  224. 224 num_components,
  225. 225 components,
  226. 226 }
  227. 227}
  228. 228
  229. 229///|
  230. 230/// 按面积筛选连通域
  231. 231pub fn filter_components_by_area(
  232. 232 result : OcrConnectedComponentsResult,
  233. 233 min_area : Int32,
  234. 234 max_area : Int32,
  235. 235) -> Array[OcrConnectedComponent] raise @types.LoadError {
  236. 236 // 输入验证
  237. 237● if result.components.length() == 0 {
  238. 238○ raise @types.LoadError::DecodeFailed(
  239. 239 "filter_components_by_area: 连通域列表不能为空",
  240. 240 )
  241. 241 }
  242. 242 if min_area < 0 {
  243. 243○ raise @types.LoadError::DecodeFailed(
  244. 244 "filter_components_by_area: min_area不能为负数",
  245. 245 )
  246. 246 }
  247. 247 if max_area < min_area {
  248. 248○ raise @types.LoadError::DecodeFailed(
  249. 249 "filter_components_by_area: max_area不能小于min_area",
  250. 250 )
  251. 251 }
  252. 252
  253. 253 let filtered : Array[OcrConnectedComponent] = []
  254. 254 for comp in result.components {
  255. 255● if comp.pixel_count >= min_area && comp.pixel_count <= max_area {
  256. 256● filtered.push(comp)
  257. 257 }
  258. 258 }
  259. 259 filtered
  260. 260}
  261. 261
  262. 262///|
  263. 263/// 按宽高比筛选连通域
  264. 264pub fn filter_components_by_aspect_ratio(
  265. 265 result : OcrConnectedComponentsResult,
  266. 266 min_ratio : Double,
  267. 267 max_ratio : Double,
  268. 268) -> Array[OcrConnectedComponent] raise @types.LoadError {
  269. 269 // 输入验证
  270. 270● if result.components.length() == 0 {
  271. 271○ raise @types.LoadError::DecodeFailed(
  272. 272 "filter_components_by_aspect_ratio: 连通域列表不能为空",
  273. 273 )
  274. 274 }
  275. 275 if min_ratio < 0.0 {
  276. 276○ raise @types.LoadError::DecodeFailed(
  277. 277 "filter_components_by_aspect_ratio: min_ratio不能为负数",
  278. 278 )
  279. 279 }
  280. 280 if max_ratio < min_ratio {
  281. 281○ raise @types.LoadError::DecodeFailed(
  282. 282 "filter_components_by_aspect_ratio: max_ratio不能小于min_ratio",
  283. 283 )
  284. 284 }
  285. 285
  286. 286 let filtered : Array[OcrConnectedComponent] = []
  287. 287 for comp in result.components {
  288. 288● if comp.height > 0 {
  289. 289● let ratio = comp.width.to_double() / comp.height.to_double()
  290. 290 if ratio >= min_ratio && ratio <= max_ratio {
  291. 291● filtered.push(comp)
  292. 292 }
  293. 293 }
  294. 294 }
  295. 295 filtered
  296. 296}
  297. 297
  298. 298///|
  299. 299/// 按位置筛选连通域(在指定矩形内)
  300. 300pub fn filter_components_by_position(
  301. 301 result : OcrConnectedComponentsResult,
  302. 302 x : Int32,
  303. 303 y : Int32,
  304. 304 width : Int32,
  305. 305 height : Int32,
  306. 306) -> Array[OcrConnectedComponent] raise @types.LoadError {
  307. 307 // 输入验证
  308. 308○ if result.components.length() == 0 {
  309. 309○ raise @types.LoadError::DecodeFailed(
  310. 310 "filter_components_by_position: 连通域列表不能为空",
  311. 311 )
  312. 312 }
  313. 313 if width <= 0 || height <= 0 {
  314. 314○ raise @types.LoadError::DecodeFailed(
  315. 315 "filter_components_by_position: 矩形尺寸必须大于0",
  316. 316 )
  317. 317 }
  318. 318
  319. 319 let filtered : Array[OcrConnectedComponent] = []
  320. 320 for comp in result.components {
  321. 321○ let cx = comp.x + comp.width / 2
  322. 322 let cy = comp.y + comp.height / 2
  323. 323 if cx >= x && cx <= x + width && cy >= y && cy <= y + height {
  324. 324○ filtered.push(comp)
  325. 325 }
  326. 326 }
  327. 327 filtered
  328. 328}
  329. 329
  330. 330///|
  331. 331/// 合并相邻连通域(用于字符合并)
  332. 332pub fn merge_adjacent_components(
  333. 333 components : Array[OcrConnectedComponent],
  334. 334 max_gap : Int32,
  335. 335) -> Array[OcrConnectedComponent] raise @types.LoadError {
  336. 336 // 输入验证
  337. 337● if components.length() == 0 {
  338. 338○ raise @types.LoadError::DecodeFailed(
  339. 339 "merge_adjacent_components: 连通域列表不能为空",
  340. 340 )
  341. 341 }
  342. 342 if max_gap < 0 {
  343. 343○ raise @types.LoadError::DecodeFailed(
  344. 344 "merge_adjacent_components: max_gap不能为负数",
  345. 345 )
  346. 346 }
  347. 347
  348. 348 let merged : Array[OcrConnectedComponent] = []
  349. 349 let mut current = components[0]
  350. 350● for i in 1..<components.length() {
  351. 351○ let next = components[i]
  352. 352 // 检查是否相邻(水平方向)
  353. 353 let gap = next.x - (current.x + current.width)
  354. 354○ let vertical_overlap = min(current.y + current.height, next.y + next.height) -
  355. 355○ max(current.y, next.y)
  356. 356 if gap <= max_gap && vertical_overlap > 0 {
  357. 357 // 合并
  358. 358○ let new_x = min(current.x, next.x)
  359. 359○ let new_y = min(current.y, next.y)
  360. 360○ let new_max_x = max(current.x + current.width, next.x + next.width)
  361. 361○ let new_max_y = max(current.y + current.height, next.y + next.height)
  362. 362 current = OcrConnectedComponent::{
  363. 363 label: current.label,
  364. 364 x: new_x,
  365. 365 y: new_y,
  366. 366 width: new_max_x - new_x,
  367. 367 height: new_max_y - new_y,
  368. 368 area: (new_max_x - new_x) * (new_max_y - new_y),
  369. 369 pixel_count: current.pixel_count + next.pixel_count,
  370. 370 bounding_box: (new_x, new_y, new_max_x - new_x, new_max_y - new_y),
  371. 371 centroid: (
  372. 372 (current.centroid.0 + next.centroid.0) / 2.0,
  373. 373 (current.centroid.1 + next.centroid.1) / 2.0,
  374. 374 ),
  375. 375 }
  376. 376 } else {
  377. 377○ merged.push(current)
  378. 378 current = next
  379. 379 }
  380. 380 }
  381. 381● merged.push(current)
  382. 382 merged
  383. 383}
  384. 384
  385. 385///|
  386. 386/// 辅助函数:最小值
  387. 387fn min(a : Int32, b : Int32) -> Int32 {
  388. 388● if a < b {
  389. 389● a
  390. 390 } else {
  391. 391● b
  392. 392 }
  393. 393}
  394. 394
  395. 395///|
  396. 396/// 辅助函数:最大值
  397. 397fn max(a : Int32, b : Int32) -> Int32 {
  398. 398● if a > b {
  399. 399● a
  400. 400 } else {
  401. 401● b
  402. 402 }
  403. 403}