image.vision\ocr\classifier.mbt
88.3% · 159 / 180 points · 535 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/classifier - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 简单分类器 - 7
// KNN、模板匹配、距离度量、分类结果 - 8
- 9
///| - 10
/// 分类结果结构体 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct ClassificationResult { - 13
label : String - 14
confidence : Double - 15
top_k : Array[(String, Double)] - 16
} - 17
- 18
///| - 19
pub extend ClassificationResult with Eq::{not_equal, equal} - 20
- 21
///| - 22
pub extend ClassificationResult with @debug.Debug::{to_repr} - 23
- 24
///| - 25
/// 训练样本结构体 - 26
#derive(Eq, @debug.Debug) - 27
pub(all) struct TrainingSample { - 28
features : Array[Double] - 29
label : String - 30
} - 31
- 32
///| - 33
pub extend TrainingSample with Eq::{not_equal, equal} - 34
- 35
///| - 36
pub extend TrainingSample with @debug.Debug::{to_repr} - 37
- 38
///| - 39
/// KNN 分类器 - 40
#derive(Eq, @debug.Debug) - 41
pub(all) struct KnnClassifier { - 42
samples : Array[TrainingSample] - 43
k : Int32 - 44
distance_metric : String - 45
} - 46
- 47
///| - 48
pub extend KnnClassifier with Eq::{not_equal, equal} - 49
- 50
///| - 51
pub extend KnnClassifier with @debug.Debug::{to_repr} - 52
- 53
///| - 54
/// 模板匹配分类器 - 55
#derive(Eq, @debug.Debug) - 56
pub(all) struct TemplateMatcher { - 57
templates : Array[(String, Array[Double])] - 58
distance_metric : String - 59
} - 60
- 61
///| - 62
pub extend TemplateMatcher with Eq::{not_equal, equal} - 63
- 64
///| - 65
pub extend TemplateMatcher with @debug.Debug::{to_repr} - 66
- 67
///| - 68
/// 距离度量类型 - 69
/// `#non_exhaustive` 表示未来可能添加新构造器 - 70
#derive(Eq, @debug.Debug) - 71
#non_exhaustive - 72
pub(all) enum DistanceMetric { - 73
Euclidean - 74
Manhattan - 75
Cosine - 76
Chebyshev - 77
} - 78
- 79
///| - 80
pub extend DistanceMetric with @debug.Debug::{to_repr} - 81
- 82
///| - 83
pub extend DistanceMetric with Eq::{not_equal, equal} - 84
- 85
///| - 86
/// 计算欧氏距离 - 87
pub fn euclidean_distance( - 88
a : Array[Double], - 89
b : Array[Double], - 90
) -> Double raise @types.LoadError { - 91
// 输入验证 - 92●
if a.length() == 0 { - 93●
raise @types.LoadError::DecodeFailed( - 94
"euclidean_distance: 向量a不能为空", - 95
) - 96
} - 97●
if b.length() == 0 { - 98●
raise @types.LoadError::DecodeFailed( - 99
"euclidean_distance: 向量b不能为空", - 100
) - 101
} - 102
- 103◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 104
let mut sum_sq = 0.0 - 105
for i in 0..<n { - 106●
let diff = a[i] - b[i] - 107
sum_sq += diff * diff - 108
} - 109●
sum_sq.sqrt() - 110
} - 111
- 112
///| - 113
/// 计算曼哈顿距离 - 114
pub fn manhattan_distance( - 115
a : Array[Double], - 116
b : Array[Double], - 117
) -> Double raise @types.LoadError { - 118
// 输入验证 - 119●
if a.length() == 0 { - 120●
raise @types.LoadError::DecodeFailed( - 121
"manhattan_distance: 向量a不能为空", - 122
) - 123
} - 124●
if b.length() == 0 { - 125●
raise @types.LoadError::DecodeFailed( - 126
"manhattan_distance: 向量b不能为空", - 127
) - 128
} - 129
- 130◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 131
let mut sum = 0.0 - 132
for i in 0..<n { - 133●
sum += (a[i] - b[i]).abs() - 134
} - 135
sum - 136
} - 137
- 138
///| - 139
/// 计算余弦相似度(返回距离 = 1 - 相似度) - 140
pub fn cosine_distance( - 141
a : Array[Double], - 142
b : Array[Double], - 143
) -> Double raise @types.LoadError { - 144
// 输入验证 - 145●
if a.length() == 0 { - 146●
raise @types.LoadError::DecodeFailed("cosine_distance: 向量a不能为空") - 147
} - 148●
if b.length() == 0 { - 149●
raise @types.LoadError::DecodeFailed("cosine_distance: 向量b不能为空") - 150
} - 151
- 152◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 153
let mut dot = 0.0 - 154
let mut norm_a = 0.0 - 155
let mut norm_b = 0.0 - 156
for i in 0..<n { - 157●
dot += a[i] * b[i] - 158
norm_a += a[i] * a[i] - 159
norm_b += b[i] * b[i] - 160
} - 161●
let denom = norm_a.sqrt() * norm_b.sqrt() - 162
if denom > 0.0 { - 163●
1.0 - dot / denom - 164
} else { - 165●
1.0 - 166
} - 167
} - 168
- 169
///| - 170
/// 计算切比雪夫距离 - 171
pub fn chebyshev_distance( - 172
a : Array[Double], - 173
b : Array[Double], - 174
) -> Double raise @types.LoadError { - 175
// 输入验证 - 176●
if a.length() == 0 { - 177●
raise @types.LoadError::DecodeFailed( - 178
"chebyshev_distance: 向量a不能为空", - 179
) - 180
} - 181●
if b.length() == 0 { - 182●
raise @types.LoadError::DecodeFailed( - 183
"chebyshev_distance: 向量b不能为空", - 184
) - 185
} - 186
- 187◐
let n = if a.length() < b.length() { a.length() } else { b.length() } - 188
let mut max_diff = 0.0 - 189
for i in 0..<n { - 190●
let diff = (a[i] - b[i]).abs() - 191
if diff > max_diff { - 192●
max_diff = diff - 193
} - 194
} - 195
max_diff - 196
} - 197
- 198
///| - 199
/// 计算距离(根据度量类型) - 200
pub fn compute_distance( - 201
a : Array[Double], - 202
b : Array[Double], - 203
metric : DistanceMetric, - 204
) -> Double raise @types.LoadError { - 205
// 输入验证 - 206●
if a.length() == 0 { - 207●
raise @types.LoadError::DecodeFailed( - 208
"compute_distance: 向量a不能为空", - 209
) - 210
} - 211●
if b.length() == 0 { - 212●
raise @types.LoadError::DecodeFailed( - 213
"compute_distance: 向量b不能为空", - 214
) - 215
} - 216
- 217●
match metric { - 218●
DistanceMetric::Euclidean => euclidean_distance(a, b) - 219●
DistanceMetric::Manhattan => manhattan_distance(a, b) - 220●
DistanceMetric::Cosine => cosine_distance(a, b) - 221●
DistanceMetric::Chebyshev => chebyshev_distance(a, b) - 222
} - 223
} - 224
- 225
///| - 226
/// 创建 KNN 分类器 - 227
pub fn knn_create( - 228
k~ : Int32 = 3, - 229
distance_metric~ : String = "euclidean", - 230
) -> KnnClassifier raise @types.LoadError { - 231
// 输入验证 - 232●
if k <= 0 { - 233●
raise @types.LoadError::DecodeFailed("knn_create: k必须大于0") - 234
} - 235
- 236
KnnClassifier::{ samples: [], k, distance_metric, } - 237
} - 238
- 239
///| - 240
/// 添加训练样本 - 241
pub fn knn_add_sample( - 242
classifier : KnnClassifier, - 243
features : Array[Double], - 244
label : String, - 245
) -> KnnClassifier raise @types.LoadError { - 246
// 输入验证 - 247●
if features.length() == 0 { - 248●
raise @types.LoadError::DecodeFailed( - 249
"knn_add_sample: 特征向量不能为空", - 250
) - 251
} - 252●
if label.length() == 0 { - 253○
raise @types.LoadError::DecodeFailed("knn_add_sample: 标签不能为空") - 254
} - 255
- 256
let new_samples = classifier.samples - 257●
new_samples.push(TrainingSample::{ features, label, }) - 258
KnnClassifier::{ - 259
samples: new_samples, - 260
k: classifier.k, - 261
distance_metric: classifier.distance_metric, - 262
} - 263
} - 264
- 265
///| - 266
/// 批量添加训练样本 - 267
pub fn knn_add_samples( - 268
classifier : KnnClassifier, - 269
samples : Array[(Array[Double], String)], - 270
) -> KnnClassifier raise @types.LoadError { - 271
// 输入验证 - 272●
if samples.length() == 0 { - 273○
raise @types.LoadError::DecodeFailed( - 274
"knn_add_samples: 样本列表不能为空", - 275
) - 276
} - 277
- 278
let new_samples = classifier.samples - 279
for _tup0 in samples { - 280●
let (features, label) = _tup0 - 281●
new_samples.push(TrainingSample::{ features, label, }) - 282
} - 283
KnnClassifier::{ - 284
samples: new_samples, - 285
k: classifier.k, - 286
distance_metric: classifier.distance_metric, - 287
} - 288
} - 289
- 290
///| - 291
/// KNN 预测 - 292
pub fn knn_predict( - 293
classifier : KnnClassifier, - 294
features : Array[Double], - 295
) -> ClassificationResult raise @types.LoadError { - 296
// 输入验证 - 297●
if features.length() == 0 { - 298●
raise @types.LoadError::DecodeFailed( - 299
"knn_predict: 特征向量不能为空", - 300
) - 301
} - 302●
if classifier.samples.length() == 0 { - 303●
raise @types.LoadError::DecodeFailed( - 304
"knn_predict: 分类器没有训练样本", - 305
) - 306
} - 307
- 308●
let metric = match classifier.distance_metric { - 309○
"manhattan" => DistanceMetric::Manhattan - 310○
"cosine" => DistanceMetric::Cosine - 311○
"chebyshev" => DistanceMetric::Chebyshev - 312●
_ => DistanceMetric::Euclidean - 313
} - 314
// 计算所有样本的距离 - 315
let distances : Array[(Double, String)] = [] - 316
for sample in classifier.samples { - 317●
let dist = compute_distance(features, sample.features, metric) - 318●
distances.push((dist, sample.label)) - 319
} - 320
// 按距离排序(冒泡排序,简单实现) - 321●
for _ in 0..<distances.length() { - 322●
for j in 0..<(distances.length() - 1) { - 323●
if distances[j].0 > distances[j + 1].0 { - 324●
let temp = distances[j] - 325
distances[j] = distances[j + 1] - 326
distances[j + 1] = temp - 327
} - 328
} - 329
} - 330
// 取前 k 个最近邻 - 331●
let k = if classifier.k < distances.length() { - 332●
classifier.k - 333
} else { - 334●
distances.length() - 335
} - 336
let top_k : Array[(String, Double)] = [] - 337
let label_votes : Array[(String, Int32)] = [] - 338
for i in 0..<k { - 339●
let (dist, label) = distances[i] - 340●
let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 } - 341●
top_k.push((label, confidence)) - 342
// 投票 - 343
let mut found = false - 344●
for j in 0..<label_votes.length() { - 345●
if label_votes[j].0 == label { - 346●
label_votes[j] = (label, label_votes[j].1 + 1) - 347
found = true - 348
} - 349
} - 350
if !found { - 351●
label_votes.push((label, 1)) - 352
} - 353
} - 354
// 找得票最多的标签 - 355
let mut best_label = "" - 356
let mut best_votes = 0 - 357
for _tup1 in label_votes { - 358●
let (label, votes) = _tup1 - 359
if votes > best_votes { - 360●
best_votes = votes - 361
best_label = label - 362
} - 363
} - 364
let confidence = if k > 0 { - 365●
best_votes.to_double() / k.to_double() - 366
} else { - 367○
0.0 - 368
} - 369
ClassificationResult::{ label: best_label, confidence, top_k, } - 370
} - 371
- 372
///| - 373
/// 创建模板匹配分类器 - 374
pub fn template_matcher_create( - 375
distance_metric~ : String = "euclidean", - 376
) -> TemplateMatcher { - 377
// 输入验证:distance_metric 不做强制验证,使用默认值兜底 - 378●
TemplateMatcher::{ templates: [], distance_metric, } - 379
} - 380
- 381
///| - 382
/// 添加模板 - 383
pub fn template_matcher_add( - 384
matcher : TemplateMatcher, - 385
label : String, - 386
template : Array[Double], - 387
) -> TemplateMatcher raise @types.LoadError { - 388
// 输入验证 - 389●
if template.length() == 0 { - 390●
raise @types.LoadError::DecodeFailed( - 391
"template_matcher_add: 模板特征向量不能为空", - 392
) - 393
} - 394●
if label.length() == 0 { - 395○
raise @types.LoadError::DecodeFailed( - 396
"template_matcher_add: 标签不能为空", - 397
) - 398
} - 399
- 400
let new_templates = matcher.templates - 401●
new_templates.push((label, template)) - 402
TemplateMatcher::{ - 403
templates: new_templates, - 404
distance_metric: matcher.distance_metric, - 405
} - 406
} - 407
- 408
///| - 409
/// 模板匹配预测 - 410
pub fn template_matcher_predict( - 411
matcher : TemplateMatcher, - 412
features : Array[Double], - 413
) -> ClassificationResult raise @types.LoadError { - 414
// 输入验证 - 415●
if features.length() == 0 { - 416●
raise @types.LoadError::DecodeFailed( - 417
"template_matcher_predict: 特征向量不能为空", - 418
) - 419
} - 420●
if matcher.templates.length() == 0 { - 421●
raise @types.LoadError::DecodeFailed( - 422
"template_matcher_predict: 模板匹配器没有模板", - 423
) - 424
} - 425
- 426●
let metric = match matcher.distance_metric { - 427○
"manhattan" => DistanceMetric::Manhattan - 428○
"cosine" => DistanceMetric::Cosine - 429●
"chebyshev" => DistanceMetric::Chebyshev - 430●
_ => DistanceMetric::Euclidean - 431
} - 432
// 计算与所有模板的距离 - 433
let distances : Array[(Double, String)] = [] - 434
for _tup2 in matcher.templates { - 435●
let (label, template) = _tup2 - 436●
let dist = compute_distance(features, template, metric) - 437●
distances.push((dist, label)) - 438
} - 439
// 按距离排序 - 440●
for _ in 0..<distances.length() { - 441●
for j in 0..<(distances.length() - 1) { - 442●
if distances[j].0 > distances[j + 1].0 { - 443●
let temp = distances[j] - 444
distances[j] = distances[j + 1] - 445
distances[j + 1] = temp - 446
} - 447
} - 448
} - 449
// 返回最佳匹配 - 450
let top_k : Array[(String, Double)] = [] - 451◐
let n = if 5 < distances.length() { 5 } else { distances.length() } - 452
for i in 0..<n { - 453●
let (dist, label) = distances[i] - 454●
let confidence = if dist > 0.0 { 1.0 / (1.0 + dist) } else { 1.0 } - 455●
top_k.push((label, confidence)) - 456
} - 457●
if distances.length() > 0 { - 458●
let (best_dist, best_label) = distances[0] - 459●
let confidence = if best_dist > 0.0 { 1.0 / (1.0 + best_dist) } else { 1.0 } - 460
ClassificationResult::{ label: best_label, confidence, top_k, } - 461
} else { - 462○
ClassificationResult::{ label: "", confidence: 0.0, top_k: [], } - 463
} - 464
} - 465
- 466
///| - 467
/// 特征归一化(Min-Max 归一化到 [0, 1]) - 468
pub fn normalize_features( - 469
features : Array[Double], - 470
) -> Array[Double] raise @types.LoadError { - 471
// 输入验证 - 472●
if features.length() == 0 { - 473●
raise @types.LoadError::DecodeFailed( - 474
"normalize_features: 特征向量不能为空", - 475
) - 476
} - 477
let mut min_val = features[0] - 478
let mut max_val = features[0] - 479
for v in features { - 480●
if v < min_val { - 481○
min_val = v - 482
} - 483
if v > max_val { - 484●
max_val = v - 485
} - 486
} - 487
let range = max_val - min_val - 488
let normalized : Array[Double] = [] - 489
if range > 0.0 { - 490●
for v in features { - 491●
normalized.push((v - min_val) / range) - 492
} - 493
} else { - 494●
for _ in features { - 495●
normalized.push(0.0) - 496
} - 497
} - 498
normalized - 499
} - 500
- 501
///| - 502
/// 特征标准化(Z-score 标准化,均值0,标准差1) - 503
pub fn standardize_features( - 504
features : Array[Double], - 505
) -> Array[Double] raise @types.LoadError { - 506
// 输入验证 - 507●
if features.length() == 0 { - 508●
raise @types.LoadError::DecodeFailed( - 509
"standardize_features: 特征向量不能为空", - 510
) - 511
} - 512
// 计算均值 - 513
let mut sum = 0.0 - 514
for v in features { - 515●
sum += v - 516
} - 517●
let mean = sum / features.length().to_double() - 518
// 计算标准差 - 519
let mut sum_sq = 0.0 - 520
for v in features { - 521●
let diff = v - mean - 522
sum_sq += diff * diff - 523
} - 524
let std = if sum_sq > 0.0 { - 525●
(sum_sq / features.length().to_double()).sqrt() - 526
} else { - 527○
1.0 - 528
} - 529
// 标准化 - 530
let standardized : Array[Double] = [] - 531
for v in features { - 532●
standardized.push((v - mean) / std) - 533
} - 534
standardized - 535
}