image.pro\recipe\code_intake.mbt

95.2% · 20 / 21 points · 84 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/// # code-intake:把图里的条码 / 二维码解成结构化记录
  3. 3///
  4. 4/// 与另外三条 Recipe 不同的是它**不改像素**:`RecipeResult.bytes` 原样返回输入字节,
  5. 5/// `codes` 才是产物。这样 CLI / MCP / wasm 三个出口拿到的是同一份记录,
  6. 6/// 不需要各自再调一次 `image.codec/barcode`。
  7. 7
  8. 8///|
  9. 9/// 一条命中记录。`kind` 用短名(`ean13` / `upca` / `code128` / `qrcode` / `unknown`),
  10. 10/// 而不是枚举,方便直接落 JSON。
  11. 11pub(all) struct CodeHit {
  12. 12 kind : String
  13. 13 data : String
  14. 14 confidence : Double
  15. 15 x : Int32
  16. 16 y : Int32
  17. 17 width : Int32
  18. 18 height : Int32
  19. 19}
  20. 20
  21. 21///|
  22. 22fn barcode_kind_name(t : @barcode.BarcodeType) -> String {
  23. 23● match t {
  24. 24● @barcode.BarcodeType::Ean13 => "ean13"
  25. 25● @barcode.BarcodeType::UpcA => "upca"
  26. 26● @barcode.BarcodeType::Code128 => "code128"
  27. 27● @barcode.BarcodeType::QrCode => "qrcode"
  28. 28● @barcode.BarcodeType::Unknown => "unknown"
  29. 29○ @barcode.BarcodeType::.. => "unknown"
  30. 30 }
  31. 31}
  32. 32
  33. 33///|
  34. 34/// 解码后的图 → 结构化记录。顺序沿用 `decode_barcode` 的返回顺序(不重排、不去重):
  35. 35/// 同图多个码全部保留,调用方按坐标自行判定主次。
  36. 36pub fn scan_codes(img : @types.Image) -> Array[CodeHit] raise @types.ImageError {
  37. 37● let found = @barcode.decode_barcode(img) catch {
  38. 38● e => raise @types.image_error_from_load(e)
  39. 39 }
  40. 40 let out : Array[CodeHit] = []
  41. 41 for r in found {
  42. 42● out.push({
  43. 43● kind: barcode_kind_name(r.barcode_type),
  44. 44 data: r.data,
  45. 45 confidence: r.confidence,
  46. 46 x: r.x,
  47. 47 y: r.y,
  48. 48 width: r.width,
  49. 49 height: r.height,
  50. 50 })
  51. 51 }
  52. 52 out
  53. 53}
  54. 54
  55. 55///|
  56. 56/// Recipe 入口:解码 → 扫描 → 记步。不做编码,也不吃 `RecipeOpts` 的任何字段。
  57. 57fn recipe_code_intake(
  58. 58 data : Bytes,
  59. 59 opts : RecipeOpts,
  60. 60) -> RecipeResult raise @types.ImageError {
  61. 61● ignore(opts)
  62. 62 let steps : Array[StepRec] = []
  63. 63● let img = step_decode(data, steps)
  64. 64● let codes = scan_codes(img)
  65. 65● steps.push({
  66. 66 name: "scan",
  67. 67 note: "hits=\{codes.length()}",
  68. 68 width: img.width,
  69. 69 height: img.height,
  70. 70 bytes: -1,
  71. 71● ms: seg_ms(),
  72. 72 })
  73. 73 {
  74. 74 recipe: "code-intake",
  75. 75 image: img,
  76. 76 bytes: data,
  77. 77● format: @lib.detect_format(data),
  78. 78 steps,
  79. 79 quality: 0,
  80. 80 redacted: 0,
  81. 81 blurred: false,
  82. 82 codes,
  83. 83 }
  84. 84}