image.codec\barcode\barcode_decode.mbt

88.5% · 208 / 235 points · 804 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/// # 条码解码 barcode/barcode_decode
  3. 3///
  4. 4/// 编解码工具模块
  5. 5/// 编解码工具模块 Codec utility module
  6. 6// 条形码/二维码识别(v11.0.0)
  7. 7// EAN-13 一维条码识别 + QR Code 基础定位与解码
  8. 8
  9. 9///|
  10. 10/// 条形码类型
  11. 11/// `#non_exhaustive` 表示未来可能添加新构造器
  12. 12#derive(Eq, @debug.Debug)
  13. 13#non_exhaustive
  14. 14pub(all) enum BarcodeType {
  15. 15 Ean13
  16. 16 UpcA
  17. 17 Code128
  18. 18 QrCode
  19. 19 Unknown
  20. 20}
  21. 21
  22. 22///|
  23. 23pub extend BarcodeType with Eq::{not_equal, equal}
  24. 24
  25. 25///|
  26. 26pub extend BarcodeType with @debug.Debug::{to_repr}
  27. 27
  28. 28///|
  29. 29/// 条形码识别结果
  30. 30#derive(Eq, @debug.Debug)
  31. 31pub(all) struct BarcodeResult {
  32. 32 barcode_type : BarcodeType
  33. 33 data : String
  34. 34 confidence : Double
  35. 35 x : Int32
  36. 36 y : Int32
  37. 37 width : Int32
  38. 38 height : Int32
  39. 39}
  40. 40
  41. 41///|
  42. 42pub extend BarcodeResult with Eq::{not_equal, equal}
  43. 43
  44. 44///|
  45. 45pub extend BarcodeResult with @debug.Debug::{to_repr}
  46. 46
  47. 47///|
  48. 48/// 条形码识别配置
  49. 49#derive(Eq, Default, @debug.Debug)
  50. 50pub(all) struct BarcodeConfig {
  51. 51 enable_ean13 : Bool
  52. 52 enable_upca : Bool
  53. 53 enable_code128 : Bool
  54. 54 enable_qrcode : Bool
  55. 55 min_bar_width : Int32 // 最小条宽(像素)
  56. 56 max_bar_width : Int32 // 最大条宽(像素)
  57. 57 scan_lines : Int32 // 扫描线数量
  58. 58 quiet_zone_required : Bool // 是否要求静区
  59. 59}
  60. 60
  61. 61///|
  62. 62pub extend BarcodeConfig with Eq::{not_equal, equal}
  63. 63
  64. 64///|
  65. 65pub extend BarcodeConfig with Default::{default}
  66. 66
  67. 67///|
  68. 68pub extend BarcodeConfig with @debug.Debug::{to_repr}
  69. 69
  70. 70///|
  71. 71/// 创建默认条形码识别配置
  72. 72pub fn barcode_default_config() -> BarcodeConfig {
  73. 73● BarcodeConfig::{
  74. 74 enable_ean13: true,
  75. 75 enable_upca: true,
  76. 76 enable_code128: false,
  77. 77 enable_qrcode: true,
  78. 78 min_bar_width: 1,
  79. 79 max_bar_width: 20,
  80. 80 scan_lines: 10,
  81. 81 quiet_zone_required: true,
  82. 82 }
  83. 83}
  84. 84
  85. 85// ==================== EAN-13 一维条码识别 ====================
  86. 86
  87. 87///|
  88. 88/// EAN-13 编码表(左侧奇偶编码)
  89. 89/// L码(奇数)和 G码(偶数)的编码模式
  90. 90let ean13_l_codes : Array[Array[Int32]] = [
  91. 91 [0, 0, 0, 1, 1, 0, 1], // 0
  92. 92 [0, 0, 1, 1, 0, 0, 1], // 1
  93. 93 [0, 0, 1, 0, 0, 1, 1], // 2
  94. 94 [0, 1, 1, 1, 1, 0, 1], // 3
  95. 95 [0, 1, 0, 0, 0, 1, 1], // 4
  96. 96 [0, 1, 1, 0, 0, 0, 1], // 5
  97. 97 [0, 1, 0, 1, 1, 1, 1], // 6
  98. 98 [0, 1, 1, 1, 0, 1, 1], // 7
  99. 99 [0, 1, 1, 0, 1, 1, 1], // 8
  100. 100 [0, 0, 0, 1, 0, 1, 1], // 9
  101. 101]
  102. 102
  103. 103///|
  104. 104/// EAN-13 G码(偶数编码)
  105. 105let ean13_g_codes : Array[Array[Int32]] = [
  106. 106 [0, 1, 0, 0, 1, 1, 1], // 0
  107. 107 [0, 1, 1, 0, 0, 1, 1], // 1
  108. 108 [0, 0, 1, 1, 0, 1, 1], // 2
  109. 109 [0, 1, 0, 0, 0, 0, 1], // 3
  110. 110 [0, 0, 1, 1, 1, 0, 1], // 4
  111. 111 [0, 1, 1, 1, 0, 0, 1], // 5
  112. 112 [0, 0, 0, 0, 1, 0, 1], // 6
  113. 113 [0, 0, 1, 0, 0, 0, 1], // 7
  114. 114 [0, 0, 0, 1, 0, 0, 1], // 8
  115. 115 [0, 0, 1, 0, 1, 1, 1], // 9
  116. 116]
  117. 117
  118. 118///|
  119. 119/// EAN-13 右侧编码(R码)
  120. 120let ean13_r_codes : Array[Array[Int32]] = [
  121. 121 [1, 1, 1, 0, 0, 1, 0], // 0
  122. 122 [1, 1, 0, 0, 1, 1, 0], // 1
  123. 123 [1, 1, 0, 1, 1, 0, 0], // 2
  124. 124 [1, 0, 0, 0, 0, 1, 0], // 3
  125. 125 [1, 0, 1, 1, 1, 0, 0], // 4
  126. 126 [1, 0, 0, 1, 1, 1, 0], // 5
  127. 127 [1, 0, 1, 0, 0, 0, 0], // 6
  128. 128 [1, 0, 0, 0, 1, 0, 0], // 7
  129. 129 [1, 0, 0, 1, 0, 0, 0], // 8
  130. 130 [1, 1, 1, 0, 1, 0, 0], // 9
  131. 131]
  132. 132
  133. 133///|
  134. 134/// EAN-13 前缀对应的奇偶编码模式
  135. 135let ean13_parity_patterns : Array[Array[Int32]] = [
  136. 136 [0, 0, 0, 0, 0, 0], // 0
  137. 137 [0, 0, 1, 0, 1, 1], // 1
  138. 138 [0, 0, 1, 1, 0, 1], // 2
  139. 139 [0, 0, 1, 1, 1, 0], // 3
  140. 140 [0, 1, 0, 0, 1, 1], // 4
  141. 141 [0, 1, 1, 0, 0, 1], // 5
  142. 142 [0, 1, 1, 1, 0, 0], // 6
  143. 143 [0, 1, 0, 1, 0, 1], // 7
  144. 144 [0, 1, 0, 1, 1, 0], // 8
  145. 145 [0, 1, 1, 0, 1, 0], // 9
  146. 146]
  147. 147
  148. 148///|
  149. 149/// 识别 EAN-13 条形码
  150. 150pub fn decode_ean13(
  151. 151 img : @types.Image,
  152. 152 config? : BarcodeConfig,
  153. 153) -> BarcodeResult? raise @types.LoadError {
  154. 154 // 输入验证
  155. 155● if img.width <= 0 || img.height <= 0 {
  156. 156● raise @types.LoadError::DecodeFailed(
  157. 157 "decode_ean13: 图像尺寸必须大于0",
  158. 158 )
  159. 159 }
  160. 160 if img.channels < 1 || img.channels > 4 {
  161. 161● raise @types.LoadError::DecodeFailed(
  162. 162 "decode_ean13: 通道数必须在1-4之间",
  163. 163 )
  164. 164 }
  165. 165 let expected_size = img.width * img.height * img.channels
  166. 166● if img.data.length() != expected_size {
  167. 167● raise @types.LoadError::DecodeFailed("decode_ean13: 数据大小不匹配")
  168. 168 }
  169. 169● let cfg = match config {
  170. 170● Some(c) => c
  171. 171● None => barcode_default_config()
  172. 172 }
  173. 173 if !cfg.enable_ean13 {
  174. 174● return None
  175. 175 }
  176. 176 let w = img.width
  177. 177 let h = img.height
  178. 178 let data = img.data
  179. 179 // 在多条水平扫描线上尝试解码
  180. 180 let mut best_result : BarcodeResult? = None
  181. 181 let mut best_confidence = 0.0
  182. 182 let line_step = h / (cfg.scan_lines + 1)
  183. 183 for line_idx in 1..<(cfg.scan_lines + 1) {
  184. 184● let y = line_idx * line_step
  185. 185 if y >= h {
  186. 186○ break
  187. 187 }
  188. 188 // 提取扫描线的像素值
  189. 189 let scan_line : Array[Int32] = []
  190. 190 for x in 0..<w {
  191. 191● scan_line.push(data[y * w + x].to_int())
  192. 192 }
  193. 193 // 二值化(Otsu或简单阈值)
  194. 194● let binary = binarize_scanline(scan_line)
  195. 195 // 尝试解码
  196. 196● let result = decode_ean13_from_binary(binary, y, w, h)
  197. 197● match result {
  198. 198 Some(r) =>
  199. 199● if r.confidence > best_confidence {
  200. 200● best_confidence = r.confidence
  201. 201 best_result = Some(r)
  202. 202 }
  203. 203● None => ignore(())
  204. 204 }
  205. 205 }
  206. 206 best_result
  207. 207}
  208. 208
  209. 209///|
  210. 210/// 扫描线二值化
  211. 211fn binarize_scanline(pixels : Array[Int32]) -> Array[Int32] {
  212. 212 // 计算阈值(简单均值)
  213. 213● let mut sum = 0
  214. 214 for p in pixels {
  215. 215● sum += p
  216. 216 }
  217. 217◐ let threshold = if pixels.length() > 0 { sum / pixels.length() } else { 128 }
  218. 218 let binary : Array[Int32] = []
  219. 219 for p in pixels {
  220. 220● binary.push(if p < threshold { 1 } else { 0 })
  221. 221 }
  222. 222 binary
  223. 223}
  224. 224
  225. 225///|
  226. 226/// 从 `i` 起同色连续像素数(`binary` 只含 0 / 1)。
  227. 227fn run_of(binary : Array[Int32], i : Int32) -> Int32 {
  228. 228● let w = binary.length()
  229. 229 if i < 0 || i >= w {
  230. 230● return 0
  231. 231 }
  232. 232 let v = binary[i]
  233. 233 let mut n = 0
  234. 234 let mut j = i
  235. 235 while j < w && binary[j] == v {
  236. 236● n += 1
  237. 237 j += 1
  238. 238 }
  239. 239 n
  240. 240}
  241. 241
  242. 242///|
  243. 243/// 从 `i` 起向左连续白(0)的个数——起始符左侧静区宽度。
  244. 244fn quiet_left_of(binary : Array[Int32], i : Int32) -> Int32 {
  245. 245● let mut n = 0
  246. 246 let mut j = i
  247. 247 while j >= 0 && binary[j] == 0 {
  248. 248● n += 1
  249. 249 j -= 1
  250. 250 }
  251. 251 n
  252. 252}
  253. 253
  254. 254///|
  255. 255/// 起始符 `101` 的候选:由「黑 - 白 - 黑」三段游程推模块宽,返回 (起点像素, 模块宽)。
  256. 256///
  257. 257/// 不能直接找相邻像素 `1,0,1`——模块宽 ≥2px 时该序列在像素层不存在(每模块是 `11` 或 `00`,
  258. 258/// 跨模块边界最多出现 `110` / `011`),这正是放大图恒解不出(GAP-57)的根因。
  259. 259fn start_guard_candidates(binary : Array[Int32]) -> Array[(Int32, Int32)] {
  260. 260● let out : Array[(Int32, Int32)] = []
  261. 261● let w = binary.length()
  262. 262 let mut i = 0
  263. 263● while i + 2 < w && out.length() < 4 {
  264. 264● if binary[i] == 1 && (i == 0 || binary[i - 1] == 0) {
  265. 265● let b1 = run_of(binary, i)
  266. 266● let b2 = run_of(binary, i + b1)
  267. 267● let b3 = run_of(binary, i + b1 + b2)
  268. 268● let mn0 = if b1 < b2 { b1 } else { b2 }
  269. 269● let mn = if mn0 < b3 { mn0 } else { b3 }
  270. 270● let mx0 = if b1 > b2 { b1 } else { b2 }
  271. 271● let mx = if mx0 > b3 { mx0 } else { b3 }
  272. 272 // 三段等宽(容差 ±50% + 1,兼容缩放/抗锯齿边缘的 ±1px 抖动)
  273. 273 if mn > 0 && mx - mn <= 1 + mn / 2 {
  274. 274● let mw = (b1 + b2 + b3 + 1) / 3
  275. 275 // 起始符左侧必须是静区(至少一个模块宽的白);码起于图首行(x=0)时图外视为白
  276. 276 let quiet_ok = if i == 0 {
  277. 277● true
  278. 278 } else {
  279. 279● quiet_left_of(binary, i - 1) >= mw
  280. 280 }
  281. 281 if quiet_ok {
  282. 282● out.push((i, mw))
  283. 283 }
  284. 284 }
  285. 285 }
  286. 286 i += 1
  287. 287 }
  288. 288 out
  289. 289}
  290. 290
  291. 291///|
  292. 292/// 以给定起点与模块宽解一条 EAN-13;解不出(含某位匹配不上)返回 `None`。
  293. 293fn decode_ean13_at(
  294. 294 binary : Array[Int32],
  295. 295 start_idx : Int32,
  296. 296 module_width : Int32,
  297. 297 y : Int32,
  298. 298) -> BarcodeResult? {
  299. 299 // 解析左侧6位数字
  300. 300● let left_digits : Array[Int32] = []
  301. 301 let left_parity : Array[Int32] = []
  302. 302 let mut pos = start_idx + 3 * module_width // 跳过起始符
  303. 303 for _ in 0..<6 {
  304. 304● let (digit, parity) = decode_ean13_digit(binary, pos, module_width, true)
  305. 305 if digit < 0 {
  306. 306● return None
  307. 307 }
  308. 308● left_digits.push(digit)
  309. 309● left_parity.push(parity)
  310. 310 pos += 7 * module_width
  311. 311 }
  312. 312 // 检查中间分隔符(01010)
  313. 313 pos += 5 * module_width // 跳过中间分隔符
  314. 314 // 解析右侧6位数字
  315. 315 let right_digits : Array[Int32] = []
  316. 316 for _ in 0..<6 {
  317. 317● let (digit, _) = decode_ean13_digit(binary, pos, module_width, false)
  318. 318 if digit < 0 {
  319. 319○ return None
  320. 320 }
  321. 321● right_digits.push(digit)
  322. 322 pos += 7 * module_width
  323. 323 }
  324. 324 // 根据奇偶编码模式确定第一位数字
  325. 325● let first_digit = match_parity_pattern(left_parity)
  326. 326 if first_digit < 0 {
  327. 327○ return None
  328. 328 }
  329. 329 // 组合完整条码
  330. 330● let mut barcode = first_digit.to_string()
  331. 331 for d in left_digits {
  332. 332● barcode += d.to_string()
  333. 333 }
  334. 334 for d in right_digits {
  335. 335● barcode += d.to_string()
  336. 336 }
  337. 337 // 验证校验位
  338. 338● let valid = validate_ean13_checksum(barcode)
  339. 339● let confidence = if valid { 0.95 } else { 0.5 }
  340. 340 Some(BarcodeResult::{
  341. 341 barcode_type: BarcodeType::Ean13,
  342. 342 data: barcode,
  343. 343 confidence,
  344. 344 x: start_idx,
  345. 345 y,
  346. 346 width: 95 * module_width,
  347. 347 height: 1,
  348. 348 })
  349. 349}
  350. 350
  351. 351///|
  352. 352/// 从二值化扫描线解码 EAN-13。起始符候选逐个试:checksum 通过的直接返回,否则留作兜底。
  353. 353fn decode_ean13_from_binary(
  354. 354 binary : Array[Int32],
  355. 355 y : Int32,
  356. 356 _img_width : Int32,
  357. 357 _img_height : Int32,
  358. 358) -> BarcodeResult? {
  359. 359● let w = binary.length()
  360. 360 if w < 95 { // EAN-13 至少需要 95 个模块
  361. 361● return None
  362. 362 }
  363. 363● let candidates = start_guard_candidates(binary)
  364. 364 let mut fallback : BarcodeResult? = None
  365. 365 for c in candidates {
  366. 366● match decode_ean13_at(binary, c.0, c.1, y) {
  367. 367 Some(r) =>
  368. 368● if r.confidence > 0.9 {
  369. 369● return Some(r)
  370. 370 } else {
  371. 371● match fallback {
  372. 372● None => fallback = Some(r)
  373. 373○ Some(_) => ignore(())
  374. 374 }
  375. 375 }
  376. 376● None => ignore(())
  377. 377 }
  378. 378 }
  379. 379 fallback
  380. 380}
  381. 381
  382. 382///|
  383. 383/// 解码单个 EAN-13 数字
  384. 384fn decode_ean13_digit(
  385. 385 binary : Array[Int32],
  386. 386 start : Int32,
  387. 387 module_width : Int32,
  388. 388 is_left : Bool,
  389. 389) -> (Int32, Int32) {
  390. 390 // 采样7个模块
  391. 391● let modules : Array[Int32] = []
  392. 392 for i in 0..<7 {
  393. 393● let pos = start + i * module_width + module_width / 2
  394. 394● if pos < binary.length() {
  395. 395● modules.push(binary[pos])
  396. 396 } else {
  397. 397○ modules.push(0)
  398. 398 }
  399. 399 }
  400. 400 // 匹配编码表
  401. 401 if is_left {
  402. 402 // 尝试 L 码(奇数)
  403. 403● for d in 0..<10 {
  404. 404● if modules == ean13_l_codes[d] {
  405. 405● return (d, 0) // 0 = L码(奇数)
  406. 406 }
  407. 407 }
  408. 408 // 尝试 G 码(偶数)
  409. 409 for d in 0..<10 {
  410. 410● if modules == ean13_g_codes[d] {
  411. 411● return (d, 1) // 1 = G码(偶数)
  412. 412 }
  413. 413 }
  414. 414 } else {
  415. 415 // 右侧 R 码
  416. 416● for d in 0..<10 {
  417. 417● if modules == ean13_r_codes[d] {
  418. 418● return (d, 0)
  419. 419 }
  420. 420 }
  421. 421 }
  422. 422 (-1, 0)
  423. 423}
  424. 424
  425. 425///|
  426. 426/// 根据奇偶编码模式匹配第一位数字
  427. 427fn match_parity_pattern(parity : Array[Int32]) -> Int32 {
  428. 428● for d in 0..<10 {
  429. 429● let mut is_match = true
  430. 430 for i in 0..<6 {
  431. 431● if parity[i] != ean13_parity_patterns[d][i] {
  432. 432● is_match = false
  433. 433 }
  434. 434 }
  435. 435 if is_match {
  436. 436● return d
  437. 437 }
  438. 438 }
  439. 439 -1
  440. 440}
  441. 441
  442. 442///|
  443. 443/// 验证 EAN-13 校验位
  444. 444fn validate_ean13_checksum(barcode : String) -> Bool {
  445. 445● if barcode.length() != 13 {
  446. 446○ return false
  447. 447 }
  448. 448 let mut sum = 0
  449. 449 for i in 0..<12 {
  450. 450● let digit = barcode[i].to_int() - '0'.to_int()
  451. 451 if i % 2 == 0 {
  452. 452● sum += digit // 奇数位(从0开始)权重1
  453. 453 } else {
  454. 454● sum += digit * 3 // 偶数位权重3
  455. 455 }
  456. 456 }
  457. 457 let checksum = (10 - sum % 10) % 10
  458. 458● let actual = barcode[12].to_int() - '0'.to_int()
  459. 459 checksum == actual
  460. 460}
  461. 461
  462. 462// ==================== QR Code 基础识别 ====================
  463. 463
  464. 464///|
  465. 465/// QR Code 定位图案(Finder Pattern)
  466. 466#derive(Eq, Default, @debug.Debug)
  467. 467pub(all) struct QrFinderPattern {
  468. 468 x : Double
  469. 469 y : Double
  470. 470 size : Double
  471. 471 quality : Double
  472. 472}
  473. 473
  474. 474///|
  475. 475pub extend QrFinderPattern with Eq::{not_equal, equal}
  476. 476
  477. 477///|
  478. 478pub extend QrFinderPattern with Default::{default}
  479. 479
  480. 480///|
  481. 481pub extend QrFinderPattern with @debug.Debug::{to_repr}
  482. 482
  483. 483///|
  484. 484/// 检测 QR Code 定位图案
  485. 485pub fn detect_qr_finder_patterns(
  486. 486 img : @types.Image,
  487. 487) -> Array[QrFinderPattern] raise @types.LoadError {
  488. 488 // 输入验证
  489. 489● if img.width <= 0 || img.height <= 0 {
  490. 490● raise @types.LoadError::DecodeFailed(
  491. 491 "detect_qr_finder_patterns: 图像尺寸必须大于0",
  492. 492 )
  493. 493 }
  494. 494 if img.channels < 1 || img.channels > 4 {
  495. 495● raise @types.LoadError::DecodeFailed(
  496. 496 "detect_qr_finder_patterns: 通道数必须在1-4之间",
  497. 497 )
  498. 498 }
  499. 499 let expected_size = img.width * img.height * img.channels
  500. 500● if img.data.length() != expected_size {
  501. 501● raise @types.LoadError::DecodeFailed(
  502. 502 "detect_qr_finder_patterns: 数据大小不匹配",
  503. 503 )
  504. 504 }
  505. 505 let w = img.width
  506. 506 let h = img.height
  507. 507 let data = img.data
  508. 508 let patterns : Array[QrFinderPattern] = []
  509. 509 // 水平扫描寻找 1:1:3:1:1 比例的图案
  510. 510 for y in 0..<h {
  511. 511● let mut x = 0
  512. 512 while x < w {
  513. 513 // 寻找起始黑条
  514. 514● if data[y * w + x].to_int() < 128 {
  515. 515● let (found, pattern_x, pattern_size) = scan_qr_pattern_horizontal(
  516. 516 data, w, x, y,
  517. 517 )
  518. 518 if found && pattern_size > 10 {
  519. 519 // 验证垂直方向
  520. 520● let vertical_valid = verify_qr_pattern_vertical(
  521. 521 data, w, h, pattern_x, y, pattern_size,
  522. 522 )
  523. 523 if vertical_valid {
  524. 524 // 统一语义:x/y 均为定位图案左上角(水平扫描命中的 y 是中心行)
  525. 525● let cell = pattern_size / 7
  526. 526 let top_y = y - 3 * cell
  527. 527◐ let top = if top_y < 0 { 0 } else { top_y }
  528. 528 let mut duplicate = false
  529. 529 for q in patterns {
  530. 530● if (q.x - pattern_x.to_double()).abs() < 1.0 &&
  531. 531● (q.y - top.to_double()).abs() <= (pattern_size / 2).to_double() {
  532. 532● duplicate = true
  533. 533 }
  534. 534 }
  535. 535 if !duplicate {
  536. 536● patterns.push(QrFinderPattern::{
  537. 537● x: pattern_x.to_double(),
  538. 538● y: top.to_double(),
  539. 539● size: pattern_size.to_double(),
  540. 540 quality: 0.8,
  541. 541 })
  542. 542 }
  543. 543 }
  544. 544 x = pattern_x + pattern_size + 1
  545. 545 } else {
  546. 546● x += 1
  547. 547 }
  548. 548 } else {
  549. 549● x += 1
  550. 550 }
  551. 551 }
  552. 552 }
  553. 553 patterns
  554. 554}
  555. 555
  556. 556///|
  557. 557/// 水平扫描 QR 定位图案(1:1:3:1:1 比例)
  558. 558fn scan_qr_pattern_horizontal(
  559. 559 data : Bytes,
  560. 560 w : Int32,
  561. 561 start_x : Int32,
  562. 562 y : Int32,
  563. 563) -> (Bool, Int32, Int32) {
  564. 564● let mut x = start_x
  565. 565 // 模块1:黑条
  566. 566 let mut m1 = 0
  567. 567● while x < w && data[y * w + x].to_int() < 128 {
  568. 568● m1 += 1
  569. 569 x += 1
  570. 570 }
  571. 571 // 模块2:白条
  572. 572 let mut m2 = 0
  573. 573● while x < w && data[y * w + x].to_int() >= 128 {
  574. 574● m2 += 1
  575. 575 x += 1
  576. 576 }
  577. 577 // 模块3:黑条(中心,应该是3倍)
  578. 578 let mut m3 = 0
  579. 579● while x < w && data[y * w + x].to_int() < 128 {
  580. 580● m3 += 1
  581. 581 x += 1
  582. 582 }
  583. 583 // 模块4:白条
  584. 584 let mut m4 = 0
  585. 585● while x < w && data[y * w + x].to_int() >= 128 {
  586. 586● m4 += 1
  587. 587 x += 1
  588. 588 }
  589. 589 // 模块5:黑条
  590. 590 let mut m5 = 0
  591. 591● while x < w && data[y * w + x].to_int() < 128 {
  592. 592● m5 += 1
  593. 593 x += 1
  594. 594 }
  595. 595 // 检查比例 1:1:3:1:1
  596. 596 let total = m1 + m2 + m3 + m4 + m5
  597. 597 if total < 20 {
  598. 598● return (false, 0, 0)
  599. 599 }
  600. 600 let module_val = total / 7
  601. 601● let m1d = m1.to_double()
  602. 602● let m2d = m2.to_double()
  603. 603● let m3d = m3.to_double()
  604. 604● let m4d = m4.to_double()
  605. 605● let m5d = m5.to_double()
  606. 606● let mod_d = module_val.to_double()
  607. 607 let ratio_ok = m1d >= mod_d * 0.5 &&
  608. 608 m1d <= mod_d * 1.5 &&
  609. 609 m2d >= mod_d * 0.5 &&
  610. 610 m2d <= mod_d * 1.5 &&
  611. 611 m3d >= mod_d * 2.5 &&
  612. 612 m3d <= mod_d * 3.5 &&
  613. 613 m4d >= mod_d * 0.5 &&
  614. 614 m4d <= mod_d * 1.5 &&
  615. 615 m5d >= mod_d * 0.5 &&
  616. 616 m5d <= mod_d * 1.5
  617. 617 if ratio_ok {
  618. 618● return (true, start_x, total)
  619. 619 }
  620. 620 (false, 0, 0)
  621. 621}
  622. 622
  623. 623///|
  624. 624/// 垂直验证 QR 定位图案
  625. 625fn verify_qr_pattern_vertical(
  626. 626 data : Bytes,
  627. 627 w : Int32,
  628. 628 h : Int32,
  629. 629 start_x : Int32,
  630. 630 start_y : Int32,
  631. 631 size : Int32,
  632. 632) -> Bool {
  633. 633● let center_x = start_x + size / 2
  634. 634 if center_x >= w {
  635. 635○ return false
  636. 636 }
  637. 637 // 水平扫描传入的 start_y 是图案中心行;垂直验证必须从图案顶部开始,
  638. 638 // 否则会把“中心黑块”当成第一个 run,比例永远不匹配(检测恒为 0)。
  639. 639 let cell = size / 7
  640. 640 let mut y = start_y - 3 * cell
  641. 641 if y < 0 {
  642. 642● y = 0
  643. 643 }
  644. 644 // 模块1:黑条
  645. 645 let mut m1 = 0
  646. 646● while y < h && data[y * w + center_x].to_int() < 128 {
  647. 647● m1 += 1
  648. 648 y += 1
  649. 649 }
  650. 650 // 模块2:白条
  651. 651 let mut m2 = 0
  652. 652● while y < h && data[y * w + center_x].to_int() >= 128 {
  653. 653● m2 += 1
  654. 654 y += 1
  655. 655 }
  656. 656 // 模块3:黑条
  657. 657 let mut m3 = 0
  658. 658● while y < h && data[y * w + center_x].to_int() < 128 {
  659. 659● m3 += 1
  660. 660 y += 1
  661. 661 }
  662. 662 // 模块4:白条
  663. 663 let mut m4 = 0
  664. 664● while y < h && data[y * w + center_x].to_int() >= 128 {
  665. 665● m4 += 1
  666. 666 y += 1
  667. 667 }
  668. 668 // 模块5:黑条
  669. 669 let mut m5 = 0
  670. 670● while y < h && data[y * w + center_x].to_int() < 128 {
  671. 671● m5 += 1
  672. 672 y += 1
  673. 673 }
  674. 674 let total = m1 + m2 + m3 + m4 + m5
  675. 675 if total < 20 {
  676. 676● return false
  677. 677 }
  678. 678 let module_val = total / 7
  679. 679● let m1d = m1.to_double()
  680. 680● let m2d = m2.to_double()
  681. 681● let m3d = m3.to_double()
  682. 682● let m4d = m4.to_double()
  683. 683● let m5d = m5.to_double()
  684. 684● let mod_d = module_val.to_double()
  685. 685 m1d >= mod_d * 0.5 &&
  686. 686 m1d <= mod_d * 1.5 &&
  687. 687 m2d >= mod_d * 0.5 &&
  688. 688 m2d <= mod_d * 1.5 &&
  689. 689 m3d >= mod_d * 2.5 &&
  690. 690 m3d <= mod_d * 3.5 &&
  691. 691 m4d >= mod_d * 0.5 &&
  692. 692 m4d <= mod_d * 1.5 &&
  693. 693 m5d >= mod_d * 0.5 &&
  694. 694 m5d <= mod_d * 1.5
  695. 695}
  696. 696
  697. 697///|
  698. 698/// 识别 QR Code(基础版:检测定位图案并估算版本)
  699. 699pub fn decode_qrcode(
  700. 700 img : @types.Image,
  701. 701 config? : BarcodeConfig,
  702. 702) -> BarcodeResult? raise @types.LoadError {
  703. 703 // 输入验证
  704. 704● if img.width <= 0 || img.height <= 0 {
  705. 705● raise @types.LoadError::DecodeFailed(
  706. 706 "decode_qrcode: 图像尺寸必须大于0",
  707. 707 )
  708. 708 }
  709. 709 if img.channels < 1 || img.channels > 4 {
  710. 710● raise @types.LoadError::DecodeFailed(
  711. 711 "decode_qrcode: 通道数必须在1-4之间",
  712. 712 )
  713. 713 }
  714. 714 let expected_size = img.width * img.height * img.channels
  715. 715● if img.data.length() != expected_size {
  716. 716● raise @types.LoadError::DecodeFailed("decode_qrcode: 数据大小不匹配")
  717. 717 }
  718. 718● let cfg = match config {
  719. 719● Some(c) => c
  720. 720● None => barcode_default_config()
  721. 721 }
  722. 722 if !cfg.enable_qrcode {
  723. 723● return None
  724. 724 }
  725. 725 // 检测定位图案
  726. 726● let patterns = detect_qr_finder_patterns(img)
  727. 727● if patterns.length() < 3 {
  728. 728● return None
  729. 729 }
  730. 730 // 取前3个定位图案(左上、右上、左下)
  731. 731 let p1 = patterns[0]
  732. 732 let p2 = patterns[1]
  733. 733 let p3 = patterns[2]
  734. 734 // 估算 QR Code 尺寸
  735. 735 let avg_size = (p1.size + p2.size + p3.size) / 3.0
  736. 736 let module_size = avg_size / 7.0
  737. 737○ let _ = (21.0 * module_size).to_int() // Version 1 是 21x21 模块
  738. 738 // 计算边界框
  739. 739○ let min_x = p1.x.min(p2.x).min(p3.x).to_int()
  740. 740○ let min_y = p1.y.min(p2.y).min(p3.y).to_int()
  741. 741○ let max_x = (p1.x + p1.size).max(p2.x + p2.size).max(p3.x + p3.size).to_int()
  742. 742○ let max_y = (p1.y + p1.size).max(p2.y + p2.size).max(p3.y + p3.size).to_int()
  743. 743 let width = max_x - min_x
  744. 744 let height = max_y - min_y
  745. 745 // 基础版:只检测定位,不做完整解码
  746. 746 // 返回检测结果,data 字段包含基本信息
  747. 747 let info = "QR Code detected: 3 finder patterns, ~" +
  748. 748○ module_size.to_int().to_string() +
  749. 749 "px/module_val, ~v1 size"
  750. 750 Some(BarcodeResult::{
  751. 751 barcode_type: BarcodeType::QrCode,
  752. 752 data: info,
  753. 753 confidence: 0.7,
  754. 754 x: min_x,
  755. 755 y: min_y,
  756. 756 width,
  757. 757 height,
  758. 758 })
  759. 759}
  760. 760
  761. 761///|
  762. 762/// 通用条形码识别(自动尝试所有启用的类型)
  763. 763pub fn decode_barcode(
  764. 764 img : @types.Image,
  765. 765 config? : BarcodeConfig,
  766. 766) -> Array[BarcodeResult] raise @types.LoadError {
  767. 767 // 输入验证
  768. 768● if img.width <= 0 || img.height <= 0 {
  769. 769● raise @types.LoadError::DecodeFailed(
  770. 770 "decode_barcode: 图像尺寸必须大于0",
  771. 771 )
  772. 772 }
  773. 773 if img.channels < 1 || img.channels > 4 {
  774. 774● raise @types.LoadError::DecodeFailed(
  775. 775 "decode_barcode: 通道数必须在1-4之间",
  776. 776 )
  777. 777 }
  778. 778 let expected_size = img.width * img.height * img.channels
  779. 779● if img.data.length() != expected_size {
  780. 780● raise @types.LoadError::DecodeFailed(
  781. 781 "decode_barcode: 数据大小不匹配",
  782. 782 )
  783. 783 }
  784. 784 let results : Array[BarcodeResult] = []
  785. 785 // 尝试 EAN-13
  786. 786● let ean13_result = match config {
  787. 787● Some(c) => decode_ean13(img, config=c)
  788. 788● None => decode_ean13(img)
  789. 789 }
  790. 790● match ean13_result {
  791. 791● Some(r) => results.push(r)
  792. 792● None => ignore(())
  793. 793 }
  794. 794 // 尝试 QR Code
  795. 795● let qr_result = match config {
  796. 796● Some(c) => decode_qrcode(img, config=c)
  797. 797● None => decode_qrcode(img)
  798. 798 }
  799. 799● match qr_result {
  800. 800○ Some(r) => results.push(r)
  801. 801● None => ignore(())
  802. 802 }
  803. 803 results
  804. 804}