image.vision\ocr\english_ocr.mbt
95.9% · 142 / 148 points · 400 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 英文 OCR ocr/english_ocr - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 英文 OCR - 7
// 数字+字母识别(0-9, A-Z, a-z) - 8
- 9
///| - 10
/// 英文 OCR 配置 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct EnglishOcrConfig { - 13
min_char_width : Int32 - 14
max_char_width : Int32 - 15
target_size : Int32 - 16
distance_metric : String - 17
case_sensitive : Bool - 18
} - 19
- 20
///| - 21
pub extend EnglishOcrConfig with Eq::{not_equal, equal} - 22
- 23
///| - 24
pub extend EnglishOcrConfig with @debug.Debug::{to_repr} - 25
- 26
///| - 27
/// 创建默认英文 OCR 配置 - 28
pub fn english_ocr_default_config() -> EnglishOcrConfig { - 29●
EnglishOcrConfig::{ - 30
min_char_width: 5, - 31
max_char_width: 60, - 32
target_size: 32, - 33
distance_metric: "euclidean", - 34
case_sensitive: false, - 35
} - 36
} - 37
- 38
///| - 39
/// 生成英文字符模板(0-9, A-Z / 可选 a-z)。 - 40
/// - 41
/// 模板不是手画形状,而是从内建 5×7 字库(`glyph_bank.mbt`)**用与样本同一条链路渲染**: - 42
/// 渲染 → 裁到墨迹包围盒 → 缩放到 `target_size` → 取 `grid×grid` 密度。 - 43
/// 每个字符给 `scales` 里的每个整数倍各出一份模板(默认 3/4/5),匹配时取最小距离, - 44
/// 用来吸收"同一字符被渲染成不同像素密度"时的取整抖动。 - 45
pub fn generate_english_templates( - 46
case_sensitive~ : Bool = false, - 47
target_size~ : Int32 = 32, - 48
grid_size~ : Int32 = 8, - 49
scales~ : Array[Int32] = [3, 4, 5], - 50
) -> Array[(String, Array[Double])] { - 51●
let templates : Array[(String, Array[Double])] = [] - 52●
let push_char = (label : String, ch : Char) => { - 53
for scale in scales { - 54●
match glyph_template_features(ch, scale, target_size, grid_size) { - 55●
Some(features) => templates.push((label, features)) - 56○
None => () - 57
} - 58
} - 59
} - 60
// 数字 0-9 - 61
for digit in 0..<10 { - 62●
match (48 + digit).to_char() { - 63●
Some(ch) => push_char(ch.to_string(), ch) - 64○
None => () - 65
} - 66
} - 67
// 大写字母 A-Z - 68
for code in 65..<91 { - 69●
match code.to_char() { - 70●
Some(ch) => push_char(ch.to_string(), ch) - 71○
None => () - 72
} - 73
} - 74
// 区分大小写时补小写(字库折叠到大写,但标签要保留小写) - 75
if case_sensitive { - 76●
for code in 97..<123 { - 77●
match code.to_char() { - 78●
Some(ch) => push_char(ch.to_string(), ch) - 79○
None => () - 80
} - 81
} - 82
} - 83
templates - 84
} - 85
- 86
///| - 87
/// 墨迹包围盒(白底 255 / 黑字 <= 128)。 - 88
fn glyph_ink_box(img : @types.Image) -> (Int32, Int32, Int32, Int32) { - 89●
let w = img.width - 90
let h = img.height - 91
let mut min_x = w - 92
let mut min_y = h - 93
let mut max_x = -1 - 94
let mut max_y = -1 - 95
for y in 0..<h { - 96●
for x in 0..<w { - 97●
if img.data[y * w + x].to_int() > 128 { - 98●
if x < min_x { - 99●
min_x = x - 100
} - 101
if y < min_y { - 102●
min_y = y - 103
} - 104
if x > max_x { - 105●
max_x = x - 106
} - 107
if y > max_y { - 108●
max_y = y - 109
} - 110
} - 111
} - 112
} - 113
if max_x < 0 || max_y < 0 { - 114○
return (0, 0, w, h) - 115
} - 116
(min_x, min_y, max_x - min_x + 1, max_y - min_y + 1) - 117
} - 118
- 119
///| - 120
/// 单个字符在给定渲染倍率下的模板特征。 - 121
/// - 122
/// 与 `recognize_english` 的样本路径逐段对齐:同一渲染器 → 同一 bbox 裁剪 → - 123
/// 同一 `extract_char_region_english` 缩放 → 同一 `extract_char_features_english` 密度。 - 124
fn glyph_template_features( - 125
ch : Char, - 126
scale : Int32, - 127
target_size : Int32, - 128
grid_size : Int32, - 129
) -> Array[Double]? { - 130●
match render_glyph(ch, scale~, margin=4) { - 131○
None => None - 132●
Some(img) => { - 133●
let (bx, by, bw, bh) = glyph_ink_box(img) - 134●
let norm = extract_char_region_english(img, bx, by, bw, bh, target_size) - 135●
Some(extract_char_features_english(norm, grid_size)) - 136
} - 137
} - 138
} - 139
- 140
///| - 141
/// 英文 OCR 识别(完整流水线) - 142
pub fn recognize_english( - 143
img : @types.Image, - 144
config? : EnglishOcrConfig, - 145
) -> OcrResult raise @types.LoadError { - 146
// 输入验证 - 147●
if img.width <= 0 || img.height <= 0 { - 148●
raise @types.LoadError::DecodeFailed( - 149
"recognize_english: 图像尺寸必须大于0", - 150
) - 151
} - 152
if img.channels != 1 { - 153●
raise @types.LoadError::DecodeFailed( - 154
"recognize_english: 仅支持单通道灰度图", - 155
) - 156
} - 157
let expected_size = img.width * img.height - 158●
if img.data.length() != expected_size { - 159●
raise @types.LoadError::DecodeFailed( - 160
"recognize_english: 数据大小不匹配,期望 " + - 161●
expected_size.to_string() + - 162
",实际 " + - 163●
img.data.length().to_string(), - 164
) - 165
} - 166
- 167●
let cfg = match config { - 168●
Some(c) => c - 169●
None => english_ocr_default_config() - 170
} - 171
// 配置验证 - 172
if cfg.min_char_width <= 0 { - 173●
raise @types.LoadError::DecodeFailed( - 174
"recognize_english: min_char_width必须大于0", - 175
) - 176
} - 177
if cfg.max_char_width < cfg.min_char_width { - 178●
raise @types.LoadError::DecodeFailed( - 179
"recognize_english: max_char_width不能小于min_char_width", - 180
) - 181
} - 182
if cfg.target_size <= 0 { - 183●
raise @types.LoadError::DecodeFailed( - 184
"recognize_english: target_size必须大于0", - 185
) - 186
} - 187
// 1. 预处理 - 188
// 极性归一 + 二值快路径:整链前景约定是「墨=亮」,输入可能是白底黑字 - 189●
let preprocessed = ocr_prepare_ink(img) - 190
// 2. 字符分割 - 191●
let char_regions = complete_char_segmentation( - 192
preprocessed, - 193
min_char_width=cfg.min_char_width, - 194
max_char_width=cfg.max_char_width, - 195
) - 196
// 3. 生成模板 - 197●
let templates = generate_english_templates( - 198
case_sensitive=cfg.case_sensitive, - 199
target_size=cfg.target_size, - 200
) - 201
// 4. 对每个字符进行识别 - 202
let char_results : Array[OcrCharResult] = [] - 203
let mut text = "" - 204
let mut total_confidence = 0.0 - 205
for _tup0 in char_regions { - 206●
let (x, y, w, h) = _tup0 - 207
// 提取字符图像 - 208●
let char_img = extract_char_region_english( - 209
preprocessed, - 210
x, - 211
y, - 212
w, - 213
h, - 214
cfg.target_size, - 215
) - 216
// 提取特征 - 217●
let features = extract_char_features_english(char_img, 8) - 218
// 模板匹配 - 219●
let result = match_template_english( - 220
features, - 221
templates, - 222
cfg.distance_metric, - 223
) - 224
text += result.0 - 225
total_confidence += result.1 - 226●
char_results.push(OcrCharResult::{ - 227
char: result.0, - 228
confidence: result.1, - 229
x, - 230
y, - 231
width: w, - 232
height: h, - 233
}) - 234
} - 235●
let avg_confidence = if char_results.length() > 0 { - 236●
total_confidence / char_results.length().to_double() - 237
} else { - 238●
0.0 - 239
} - 240
OcrResult::{ text, confidence: avg_confidence, characters: char_results, } - 241
} - 242
- 243
///| - 244
/// 提取字符区域(英文OCR专用) - 245
fn extract_char_region_english( - 246
img : @types.Image, - 247
x : Int32, - 248
y : Int32, - 249
width : Int32, - 250
height : Int32, - 251
target_size : Int32, - 252
) -> @types.Image { - 253●
let w = img.width - 254
let h = img.height - 255●
let crop_w = if x + width > w { w - x } else { width } - 256●
let crop_h = if y + height > h { h - y } else { height } - 257
if crop_w <= 0 || crop_h <= 0 { - 258●
let empty : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 259
return @types.Image::{ - 260
width: target_size, - 261
height: target_size, - 262
channels: 1, - 263●
data: Bytes::from_array(empty), - 264
} - 265
} - 266
let scale = if crop_w > crop_h { - 267●
target_size.to_double() / crop_w.to_double() - 268
} else { - 269●
target_size.to_double() / crop_h.to_double() - 270
} - 271●
let new_w = @types.int_max(1, (crop_w.to_double() * scale).to_int()) - 272●
let new_h = @types.int_max(1, (crop_h.to_double() * scale).to_int()) - 273
let offset_x = (target_size - new_w) / 2 - 274
let offset_y = (target_size - new_h) / 2 - 275●
let out : Array[Byte] = Array::make(target_size * target_size, b'\x00') - 276
let data = img.data - 277
for py in 0..<new_h { - 278●
for px in 0..<new_w { - 279●
let src_x = x + px * crop_w / new_w - 280
let src_y = y + py * crop_h / new_h - 281
if src_x < w && src_y < h { - 282●
out[(offset_y + py) * target_size + (offset_x + px)] = data[src_y * w + - 283
src_x] - 284
} - 285
} - 286
} - 287
@types.Image::{ - 288
width: target_size, - 289
height: target_size, - 290
channels: 1, - 291●
data: Bytes::from_array(out), - 292
} - 293
} - 294
- 295
///| - 296
/// 提取字符特征(英文OCR专用) - 297
fn extract_char_features_english( - 298
char_img : @types.Image, - 299
grid_size : Int32, - 300
) -> Array[Double] { - 301●
let w = char_img.width - 302
let h = char_img.height - 303
let data = char_img.data - 304
let cell_w = w / grid_size - 305
let cell_h = h / grid_size - 306
let features : Array[Double] = [] - 307
for r in 0..<grid_size { - 308●
for c in 0..<grid_size { - 309●
let mut count = 0 - 310
let mut total = 0 - 311
for py in 0..<cell_h { - 312●
for px in 0..<cell_w { - 313●
let sx = c * cell_w + px - 314
let sy = r * cell_h + py - 315
if sx < w && sy < h { - 316●
total += 1 - 317●
if data[sy * w + sx].to_int() > 128 { - 318●
count += 1 - 319
} - 320
} - 321
} - 322
} - 323
let density = if total > 0 { - 324●
count.to_double() / total.to_double() - 325
} else { - 326●
0.0 - 327
} - 328●
features.push(density) - 329
} - 330
} - 331
features - 332
} - 333
- 334
///| - 335
/// 模板匹配(英文OCR专用) - 336
fn match_template_english( - 337
features : Array[Double], - 338
templates : Array[(String, Array[Double])], - 339
distance_metric : String, - 340
) -> (String, Double) { - 341●
let mut best_label = "?" - 342
let mut best_dist = 1000000.0 - 343
for _tup1 in templates { - 344●
let (label, template) = _tup1 - 345●
let dist = match distance_metric { - 346●
"manhattan" => manhattan_distance_eng(features, template) - 347●
"cosine" => cosine_distance_eng(features, template) - 348●
_ => euclidean_distance_eng(features, template) - 349
} - 350
if dist < best_dist { - 351●
best_dist = dist - 352
best_label = label - 353
} - 354
} - 355●
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 356
(best_label, confidence) - 357
} - 358
- 359
///| - 360
/// 局部欧氏距离 - 361
fn euclidean_distance_eng(a : Array[Double], b : Array[Double]) -> Double { - 362●
let n = if a.length() < b.length() { a.length() } else { b.length() } - 363
let mut sum_sq = 0.0 - 364
for i in 0..<n { - 365●
let diff = a[i] - b[i] - 366
sum_sq += diff * diff - 367
} - 368●
sum_sq.sqrt() - 369
} - 370
- 371
///| - 372
/// 局部曼哈顿距离 - 373
fn manhattan_distance_eng(a : Array[Double], b : Array[Double]) -> Double { - 374●
let n = if a.length() < b.length() { a.length() } else { b.length() } - 375
let mut sum = 0.0 - 376
for i in 0..<n { - 377●
sum += (a[i] - b[i]).abs() - 378
} - 379
sum - 380
} - 381
- 382
///| - 383
/// 局部余弦距离 - 384
fn cosine_distance_eng(a : Array[Double], b : Array[Double]) -> Double { - 385●
let n = if a.length() < b.length() { a.length() } else { b.length() } - 386
let mut dot = 0.0 - 387
let mut norm_a = 0.0 - 388
let mut norm_b = 0.0 - 389
for i in 0..<n { - 390●
dot += a[i] * b[i] - 391
norm_a += a[i] * a[i] - 392
norm_b += b[i] * b[i] - 393
} - 394●
let denom = norm_a.sqrt() * norm_b.sqrt() - 395
if denom > 0.0 { - 396●
1.0 - dot / denom - 397
} else { - 398●
1.0 - 399
} - 400
}