image.vision\ocr\feature_extraction.mbt
93.5% · 202 / 216 points · 614 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/feature_extraction - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 特征提取 - 7
// HOG、LBP、投影特征、网格特征、统计特征 - 8
- 9
///| - 10
/// HOG 特征描述子 - 11
#derive(Eq, @debug.Debug) - 12
pub(all) struct HogFeatures { - 13
features : Array[Double] - 14
cell_size : Int32 - 15
num_bins : Int32 - 16
width : Int32 - 17
height : Int32 - 18
} - 19
- 20
///| - 21
pub extend HogFeatures with Eq::{not_equal, equal} - 22
- 23
///| - 24
pub extend HogFeatures with @debug.Debug::{to_repr} - 25
- 26
///| - 27
/// LBP 特征描述子 - 28
#derive(Eq, @debug.Debug) - 29
pub(all) struct LbpFeatures { - 30
features : Array[Double] - 31
num_bins : Int32 - 32
radius : Int32 - 33
num_points : Int32 - 34
} - 35
- 36
///| - 37
pub extend LbpFeatures with Eq::{not_equal, equal} - 38
- 39
///| - 40
pub extend LbpFeatures with @debug.Debug::{to_repr} - 41
- 42
///| - 43
/// 投影特征 - 44
#derive(Eq, @debug.Debug) - 45
pub(all) struct ProjectionFeatures { - 46
horizontal : Array[Double] - 47
vertical : Array[Double] - 48
horizontal_mean : Double - 49
horizontal_std : Double - 50
vertical_mean : Double - 51
vertical_std : Double - 52
} - 53
- 54
///| - 55
pub extend ProjectionFeatures with Eq::{not_equal, equal} - 56
- 57
///| - 58
pub extend ProjectionFeatures with @debug.Debug::{to_repr} - 59
- 60
///| - 61
/// 网格特征 - 62
#derive(Eq, @debug.Debug) - 63
pub(all) struct GridFeatures { - 64
features : Array[Double] - 65
grid_rows : Int32 - 66
grid_cols : Int32 - 67
} - 68
- 69
///| - 70
pub extend GridFeatures with Eq::{not_equal, equal} - 71
- 72
///| - 73
pub extend GridFeatures with @debug.Debug::{to_repr} - 74
- 75
///| - 76
/// 统计特征 - 77
#derive(Eq, @debug.Debug) - 78
pub(all) struct StatisticalFeatures { - 79
mean : Double - 80
std : Double - 81
skewness : Double - 82
kurtosis : Double - 83
entropy : Double - 84
energy : Double - 85
contrast : Double - 86
homogeneity : Double - 87
} - 88
- 89
///| - 90
pub extend StatisticalFeatures with Eq::{not_equal, equal} - 91
- 92
///| - 93
pub extend StatisticalFeatures with @debug.Debug::{to_repr} - 94
- 95
///| - 96
/// 计算 HOG 特征(方向梯度直方图) - 97
pub fn hog_features( - 98
img : @types.Image, - 99
cell_size~ : Int32 = 8, - 100
num_bins~ : Int32 = 9, - 101
) -> HogFeatures raise @types.LoadError { - 102
// 输入验证 - 103●
if img.width <= 0 || img.height <= 0 { - 104●
raise @types.LoadError::DecodeFailed( - 105
"hog_features: 图像尺寸必须大于0", - 106
) - 107
} - 108
if img.channels != 1 { - 109●
raise @types.LoadError::DecodeFailed( - 110
"hog_features: 仅支持单通道灰度图", - 111
) - 112
} - 113
let expected_size = img.width * img.height - 114●
if img.data.length() != expected_size { - 115●
raise @types.LoadError::DecodeFailed( - 116
"hog_features: 数据大小不匹配,期望 " + - 117●
expected_size.to_string() + - 118
",实际 " + - 119●
img.data.length().to_string(), - 120
) - 121
} - 122
if cell_size <= 0 { - 123●
raise @types.LoadError::DecodeFailed("hog_features: cell_size必须大于0") - 124
} - 125
if num_bins <= 0 { - 126●
raise @types.LoadError::DecodeFailed("hog_features: num_bins必须大于0") - 127
} - 128
- 129
let w = img.width - 130
let h = img.height - 131
let data = img.data - 132
// 计算梯度 - 133●
let grad_x : Array[Double] = Array::make(w * h, 0.0) - 134●
let grad_y : Array[Double] = Array::make(w * h, 0.0) - 135●
let magnitude : Array[Double] = Array::make(w * h, 0.0) - 136●
let orientation : Array[Double] = Array::make(w * h, 0.0) - 137
for y in 1..<(h - 1) { - 138●
for x in 1..<(w - 1) { - 139●
let gx = data[y * w + (x + 1)].to_int() - data[y * w + (x - 1)].to_int() - 140●
let gy = data[(y + 1) * w + x].to_int() - data[(y - 1) * w + x].to_int() - 141●
grad_x[y * w + x] = gx.to_double() - 142●
grad_y[y * w + x] = gy.to_double() - 143●
magnitude[y * w + x] = (gx.to_double() * gx.to_double() + - 144●
gy.to_double() * gy.to_double()).sqrt() - 145●
let mut angle = @math.atan2(gy.to_double(), gx.to_double()) * - 146
180.0 / - 147
3.141592653589793 - 148
if angle < 0.0 { - 149●
angle += 180.0 - 150
} - 151
orientation[y * w + x] = angle - 152
} - 153
} - 154
// 计算每个 cell 的直方图 - 155
let cells_x = w / cell_size - 156
let cells_y = h / cell_size - 157
let features : Array[Double] = [] - 158
for cy in 0..<cells_y { - 159●
for cx in 0..<cells_x { - 160●
let hist : Array[Double] = Array::make(num_bins, 0.0) - 161
for y in 0..<cell_size { - 162●
for x in 0..<cell_size { - 163●
let px = cx * cell_size + x - 164
let py = cy * cell_size + y - 165
if px < w && py < h { - 166●
let mag = magnitude[py * w + px] - 167
let angle = orientation[py * w + px] - 168●
let bin = (angle / (180.0 / num_bins.to_double())).to_int() - 169●
let bin_idx = if bin >= num_bins { num_bins - 1 } else { bin } - 170
hist[bin_idx] += mag - 171
} - 172
} - 173
} - 174
// L2 归一化 - 175
let mut sum_sq = 0.0 - 176
for i in 0..<num_bins { - 177●
sum_sq += hist[i] * hist[i] - 178
} - 179●
let norm = if sum_sq > 0.0 { sum_sq.sqrt() } else { 1.0 } - 180
for i in 0..<num_bins { - 181●
features.push(hist[i] / norm) - 182
} - 183
} - 184
} - 185
HogFeatures::{ - 186
features, - 187
cell_size, - 188
num_bins, - 189
width: cells_x, - 190
height: cells_y, - 191
} - 192
} - 193
- 194
///| - 195
/// 计算 LBP 特征(局部二值模式) - 196
pub fn lbp_features( - 197
img : @types.Image, - 198
radius~ : Int32 = 1, - 199
num_points~ : Int32 = 8, - 200
num_bins~ : Int32 = 256, - 201
) -> LbpFeatures raise @types.LoadError { - 202
// 输入验证 - 203●
if img.width <= 0 || img.height <= 0 { - 204●
raise @types.LoadError::DecodeFailed( - 205
"lbp_features: 图像尺寸必须大于0", - 206
) - 207
} - 208
if img.channels != 1 { - 209●
raise @types.LoadError::DecodeFailed( - 210
"lbp_features: 仅支持单通道灰度图", - 211
) - 212
} - 213
let expected_size = img.width * img.height - 214●
if img.data.length() != expected_size { - 215●
raise @types.LoadError::DecodeFailed( - 216
"lbp_features: 数据大小不匹配,期望 " + - 217●
expected_size.to_string() + - 218
",实际 " + - 219●
img.data.length().to_string(), - 220
) - 221
} - 222
if radius <= 0 { - 223○
raise @types.LoadError::DecodeFailed("lbp_features: radius必须大于0") - 224
} - 225
if num_points <= 0 { - 226○
raise @types.LoadError::DecodeFailed( - 227
"lbp_features: num_points必须大于0", - 228
) - 229
} - 230
if num_bins <= 0 { - 231○
raise @types.LoadError::DecodeFailed("lbp_features: num_bins必须大于0") - 232
} - 233
- 234
let w = img.width - 235
let h = img.height - 236
let data = img.data - 237
// 计算 LBP 码 - 238●
let lbp_codes : Array[Int32] = Array::make(w * h, 0) - 239
for y in radius..<(h - radius) { - 240●
for x in radius..<(w - radius) { - 241●
let center = data[y * w + x].to_int() - 242
let mut code = 0 - 243
for i in 0..<num_points { - 244●
let angle = 2.0 * - 245
3.141592653589793 * - 246●
i.to_double() / - 247●
num_points.to_double() - 248●
let nx = (x.to_double() + radius.to_double() * @math.cos(angle)).to_int() - 249●
let ny = (y.to_double() + radius.to_double() * @math.sin(angle)).to_int() - 250
if nx >= 0 && nx < w && ny >= 0 && ny < h { - 251●
let neighbor = data[ny * w + nx].to_int() - 252
if neighbor >= center { - 253●
code = code | (1 << i) - 254
} - 255
} - 256
} - 257
lbp_codes[y * w + x] = code - 258
} - 259
} - 260
// 计算直方图 - 261●
let hist : Array[Double] = Array::make(num_bins, 0.0) - 262
let mut total = 0 - 263
for i in 0..<(w * h) { - 264●
let code = lbp_codes[i] - 265
if code < num_bins { - 266●
hist[code] += 1.0 - 267
total += 1 - 268
} - 269
} - 270
// 归一化 - 271
if total > 0 { - 272●
for i in 0..<num_bins { - 273●
hist[i] /= total.to_double() - 274
} - 275
} - 276
LbpFeatures::{ features: hist, num_bins, radius, num_points, } - 277
} - 278
- 279
///| - 280
/// 计算投影特征 - 281
pub fn projection_features( - 282
img : @types.Image, - 283
) -> ProjectionFeatures raise @types.LoadError { - 284
// 输入验证 - 285●
if img.width <= 0 || img.height <= 0 { - 286●
raise @types.LoadError::DecodeFailed( - 287
"projection_features: 图像尺寸必须大于0", - 288
) - 289
} - 290
if img.channels != 1 { - 291●
raise @types.LoadError::DecodeFailed( - 292
"projection_features: 仅支持单通道二值图", - 293
) - 294
} - 295
let expected_size = img.width * img.height - 296●
if img.data.length() != expected_size { - 297●
raise @types.LoadError::DecodeFailed( - 298
"projection_features: 数据大小不匹配,期望 " + - 299●
expected_size.to_string() + - 300
",实际 " + - 301●
img.data.length().to_string(), - 302
) - 303
} - 304
- 305
let w = img.width - 306
let h = img.height - 307
let data = img.data - 308
// 水平投影 - 309●
let horizontal : Array[Double] = Array::make(h, 0.0) - 310
for y in 0..<h { - 311●
let mut count = 0 - 312
for x in 0..<w { - 313●
if data[y * w + x].to_int() > 128 { - 314○
count += 1 - 315
} - 316
} - 317●
horizontal[y] = count.to_double() / w.to_double() - 318
} - 319
// 垂直投影 - 320●
let vertical : Array[Double] = Array::make(w, 0.0) - 321
for x in 0..<w { - 322●
let mut count = 0 - 323
for y in 0..<h { - 324●
if data[y * w + x].to_int() > 128 { - 325○
count += 1 - 326
} - 327
} - 328●
vertical[x] = count.to_double() / h.to_double() - 329
} - 330
// 计算统计量 - 331●
let h_mean = mean_array(horizontal) - 332●
let h_std = std_array(horizontal, h_mean) - 333●
let v_mean = mean_array(vertical) - 334●
let v_std = std_array(vertical, v_mean) - 335
ProjectionFeatures::{ - 336
horizontal, - 337
vertical, - 338
horizontal_mean: h_mean, - 339
horizontal_std: h_std, - 340
vertical_mean: v_mean, - 341
vertical_std: v_std, - 342
} - 343
} - 344
- 345
///| - 346
/// 计算网格特征(将图像分成网格,每个格子计算像素密度) - 347
pub fn grid_features( - 348
img : @types.Image, - 349
grid_rows~ : Int32 = 4, - 350
grid_cols~ : Int32 = 4, - 351
) -> GridFeatures raise @types.LoadError { - 352
// 输入验证 - 353●
if img.width <= 0 || img.height <= 0 { - 354●
raise @types.LoadError::DecodeFailed( - 355
"grid_features: 图像尺寸必须大于0", - 356
) - 357
} - 358
if img.channels != 1 { - 359●
raise @types.LoadError::DecodeFailed( - 360
"grid_features: 仅支持单通道二值图", - 361
) - 362
} - 363
let expected_size = img.width * img.height - 364●
if img.data.length() != expected_size { - 365●
raise @types.LoadError::DecodeFailed( - 366
"grid_features: 数据大小不匹配,期望 " + - 367●
expected_size.to_string() + - 368
",实际 " + - 369●
img.data.length().to_string(), - 370
) - 371
} - 372
if grid_rows <= 0 { - 373○
raise @types.LoadError::DecodeFailed( - 374
"grid_features: grid_rows必须大于0", - 375
) - 376
} - 377
if grid_cols <= 0 { - 378○
raise @types.LoadError::DecodeFailed( - 379
"grid_features: grid_cols必须大于0", - 380
) - 381
} - 382
- 383
let w = img.width - 384
let h = img.height - 385
let data = img.data - 386
let cell_w = w / grid_cols - 387
let cell_h = h / grid_rows - 388
let features : Array[Double] = [] - 389
for r in 0..<grid_rows { - 390●
for c in 0..<grid_cols { - 391●
let mut count = 0 - 392
let mut total = 0 - 393
for y in 0..<cell_h { - 394●
for x in 0..<cell_w { - 395●
let px = c * cell_w + x - 396
let py = r * cell_h + y - 397
if px < w && py < h { - 398●
total += 1 - 399●
if data[py * w + px].to_int() > 128 { - 400●
count += 1 - 401
} - 402
} - 403
} - 404
} - 405
let density = if total > 0 { - 406●
count.to_double() / total.to_double() - 407
} else { - 408○
0.0 - 409
} - 410●
features.push(density) - 411
} - 412
} - 413
GridFeatures::{ features, grid_rows, grid_cols, } - 414
} - 415
- 416
///| - 417
/// 计算统计特征 - 418
pub fn statistical_features( - 419
img : @types.Image, - 420
) -> StatisticalFeatures raise @types.LoadError { - 421
// 输入验证 - 422●
if img.width <= 0 || img.height <= 0 { - 423●
raise @types.LoadError::DecodeFailed( - 424
"statistical_features: 图像尺寸必须大于0", - 425
) - 426
} - 427
if img.channels != 1 { - 428●
raise @types.LoadError::DecodeFailed( - 429
"statistical_features: 仅支持单通道灰度图", - 430
) - 431
} - 432
let expected_size = img.width * img.height - 433●
if img.data.length() != expected_size { - 434●
raise @types.LoadError::DecodeFailed( - 435
"statistical_features: 数据大小不匹配,期望 " + - 436●
expected_size.to_string() + - 437
",实际 " + - 438●
img.data.length().to_string(), - 439
) - 440
} - 441
- 442
let w = img.width - 443
let h = img.height - 444
let n = w * h - 445
let data = img.data - 446
// 计算直方图 - 447●
let hist : Array[Double] = Array::make(256, 0.0) - 448
for i in 0..<n { - 449●
hist[data[i].to_int()] += 1.0 - 450
} - 451
// 归一化 - 452
for i in 0..<256 { - 453●
hist[i] /= n.to_double() - 454
} - 455
// 均值 - 456
let mut mean = 0.0 - 457
for i in 0..<256 { - 458●
mean += i.to_double() * hist[i] - 459
} - 460
// 方差/标准差 - 461
let mut variance = 0.0 - 462
for i in 0..<256 { - 463●
let diff = i.to_double() - mean - 464
variance += diff * diff * hist[i] - 465
} - 466●
let std = if variance > 0.0 { variance.sqrt() } else { 0.0 } - 467
// 偏度 - 468
let mut skewness = 0.0 - 469
if std > 0.0 { - 470●
for i in 0..<256 { - 471●
let diff = (i.to_double() - mean) / std - 472
skewness += diff * diff * diff * hist[i] - 473
} - 474
} - 475
// 峰度 - 476
let mut kurtosis = 0.0 - 477
if std > 0.0 { - 478●
for i in 0..<256 { - 479●
let diff = (i.to_double() - mean) / std - 480
kurtosis += diff * diff * diff * diff * hist[i] - 481
} - 482
kurtosis -= 3.0 // 超额峰度 - 483
} - 484
// 熵 - 485
let mut entropy = 0.0 - 486
for i in 0..<256 { - 487●
if hist[i] > 0.0 { - 488●
entropy -= hist[i] * @math.log2(hist[i]) - 489
} - 490
} - 491
// 能量 - 492
let mut energy = 0.0 - 493
for i in 0..<256 { - 494●
energy += hist[i] * hist[i] - 495
} - 496
// 对比度(简化版) - 497
let mut contrast = 0.0 - 498
for i in 0..<256 { - 499●
contrast += (i.to_double() - mean) * (i.to_double() - mean) * hist[i] - 500
} - 501
// 同质性(简化版) - 502
let mut homogeneity = 0.0 - 503
for i in 0..<256 { - 504●
homogeneity += hist[i] / (1.0 + (i.to_double() - mean).abs()) - 505
} - 506
StatisticalFeatures::{ - 507
mean, - 508
std, - 509
skewness, - 510
kurtosis, - 511
entropy, - 512
energy, - 513
contrast, - 514
homogeneity, - 515
} - 516
} - 517
- 518
///| - 519
/// 组合特征(将多种特征拼接成一个向量) - 520
pub fn combined_features( - 521
img : @types.Image, - 522
) -> Array[Double] raise @types.LoadError { - 523
// 输入验证 - 524●
if img.width <= 0 || img.height <= 0 { - 525●
raise @types.LoadError::DecodeFailed( - 526
"combined_features: 图像尺寸必须大于0", - 527
) - 528
} - 529
if img.channels != 1 { - 530●
raise @types.LoadError::DecodeFailed( - 531
"combined_features: 仅支持单通道灰度图", - 532
) - 533
} - 534
let expected_size = img.width * img.height - 535●
if img.data.length() != expected_size { - 536●
raise @types.LoadError::DecodeFailed( - 537
"combined_features: 数据大小不匹配,期望 " + - 538●
expected_size.to_string() + - 539
",实际 " + - 540●
img.data.length().to_string(), - 541
) - 542
} - 543
- 544●
let hog = hog_features(img) - 545●
let lbp = lbp_features(img) - 546●
let proj = projection_features(img) - 547●
let grid = grid_features(img) - 548●
let stats = statistical_features(img) - 549
let combined : Array[Double] = [] - 550
// HOG 特征 - 551
for f in hog.features { - 552●
combined.push(f) - 553
} - 554
// LBP 特征(降采样,只取前64维) - 555●
let lbp_dim = if lbp.features.length() > 64 { - 556●
64 - 557
} else { - 558○
lbp.features.length() - 559
} - 560
for i in 0..<lbp_dim { - 561●
combined.push(lbp.features[i]) - 562
} - 563
// 投影特征统计量 - 564●
combined.push(proj.horizontal_mean) - 565●
combined.push(proj.horizontal_std) - 566●
combined.push(proj.vertical_mean) - 567●
combined.push(proj.vertical_std) - 568
// 网格特征 - 569
for f in grid.features { - 570●
combined.push(f) - 571
} - 572
// 统计特征 - 573●
combined.push(stats.mean / 255.0) - 574●
combined.push(stats.std / 128.0) - 575●
combined.push(stats.skewness) - 576●
combined.push(stats.kurtosis) - 577●
combined.push(stats.entropy / 8.0) - 578●
combined.push(stats.energy) - 579●
combined.push(stats.contrast / 65025.0) - 580●
combined.push(stats.homogeneity) - 581
combined - 582
} - 583
- 584
///| - 585
/// 辅助函数:计算数组均值 - 586
fn mean_array(arr : Array[Double]) -> Double { - 587●
if arr.length() == 0 { - 588○
return 0.0 - 589
} - 590
let mut sum = 0.0 - 591
for v in arr { - 592●
sum += v - 593
} - 594●
sum / arr.length().to_double() - 595
} - 596
- 597
///| - 598
/// 辅助函数:计算数组标准差 - 599
fn std_array(arr : Array[Double], mean : Double) -> Double { - 600●
if arr.length() == 0 { - 601○
return 0.0 - 602
} - 603
let mut sum_sq = 0.0 - 604
for v in arr { - 605●
let diff = v - mean - 606
sum_sq += diff * diff - 607
} - 608●
let variance = sum_sq / arr.length().to_double() - 609
if variance > 0.0 { - 610○
variance.sqrt() - 611
} else { - 612●
0.0 - 613
} - 614
}