image.domain\retrieval\content_based_retrieval.mbt
93.2% · 150 / 161 points · 696 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 基于内容检索 retrieval/content_based_retrieval - 3
/// - 4
/// 图像处理库子模块 - 5
/// 图像处理库子模块 Image processing library submodule - 6
// 图像检索增强(v22.0.0) - 7
// 基于内容的图像检索、特征提取、相似度计算、图像索引 - 8
- 9
///| - 10
/// 图像特征类型 - 11
/// `#non_exhaustive` 表示未来可能添加新构造器 - 12
#derive(Eq) - 13
#non_exhaustive - 14
pub(all) enum FeatureType { - 15
ColorHistogram - 16
ColorCorrelogram - 17
Texture - 18
Shape - 19
SIFT - 20
SURF - 21
ORB - 22
HOG - 23
LBP - 24
Gabor - 25
DeepFeature - 26
Combined - 27
Unknown - 28
} - 29
- 30
///| - 31
pub extend FeatureType with Eq::{not_equal, equal} - 32
- 33
///| - 34
/// 图像特征 - 35
pub(all) struct CBIRImageFeature { - 36
feature_type : FeatureType - 37
feature_vector : Array[Double] - 38
feature_length : Int32 - 39
image_id : String - 40
image_path : String - 41
width : Int32 - 42
height : Int32 - 43
extraction_time_ms : Double - 44
} - 45
- 46
///| - 47
/// 检索结果 - 48
#derive(Eq, Default, @debug.Debug) - 49
pub(all) struct CBIRRetrievalResult { - 50
image_id : String - 51
image_path : String - 52
similarity : Double - 53
distance : Double - 54
rank : Int32 - 55
width : Int32 - 56
height : Int32 - 57
} - 58
- 59
///| - 60
pub extend CBIRRetrievalResult with @debug.Debug::{to_repr} - 61
- 62
///| - 63
pub extend CBIRRetrievalResult with Eq::{not_equal, equal} - 64
- 65
///| - 66
pub extend CBIRRetrievalResult with Default::{default} - 67
- 68
///| - 69
/// 检索结果列表 - 70
#derive(Eq, Default, @debug.Debug) - 71
pub(all) struct CBIRRetrievalResultList { - 72
results : Array[CBIRRetrievalResult] - 73
num_results : Int32 - 74
query_image_id : String - 75
retrieval_time_ms : Double - 76
total_images_in_index : Int32 - 77
} - 78
- 79
///| - 80
pub extend CBIRRetrievalResultList with @debug.Debug::{to_repr} - 81
- 82
///| - 83
pub extend CBIRRetrievalResultList with Eq::{not_equal, equal} - 84
- 85
///| - 86
pub extend CBIRRetrievalResultList with Default::{default} - 87
- 88
///| - 89
/// 图像索引 - 90
pub(all) struct CBIRImageIndex { - 91
features : Array[CBIRImageFeature] - 92
num_images : Int32 - 93
index_type : String - 94
built : Bool - 95
build_time_ms : Double - 96
} - 97
- 98
///| - 99
/// 相似度度量类型 - 100
/// `#non_exhaustive` 表示未来可能添加新构造器 - 101
#derive(Eq) - 102
#non_exhaustive - 103
pub(all) enum SimilarityMetric { - 104
Cosine - 105
Euclidean - 106
Manhattan - 107
Chebyshev - 108
Correlation - 109
Intersection - 110
ChiSquare - 111
Hellinger - 112
JensenShannon - 113
Unknown - 114
} - 115
- 116
///| - 117
pub extend SimilarityMetric with Eq::{not_equal, equal} - 118
- 119
///| - 120
/// 颜色直方图配置 - 121
#derive(Eq, Default, @debug.Debug) - 122
pub(all) struct ColorHistogramConfig { - 123
num_bins : Int32 - 124
color_space : String // "RGB" / "HSV" / "Gray" - 125
normalize : Bool - 126
cumulative : Bool - 127
} - 128
- 129
///| - 130
pub extend ColorHistogramConfig with @debug.Debug::{to_repr} - 131
- 132
///| - 133
pub extend ColorHistogramConfig with Eq::{not_equal, equal} - 134
- 135
///| - 136
pub extend ColorHistogramConfig with Default::{default} - 137
- 138
///| - 139
/// LBP 特征配置 - 140
#derive(Eq, Default, @debug.Debug) - 141
pub(all) struct LBPConfig { - 142
radius : Int32 - 143
num_points : Int32 - 144
uniform : Bool - 145
rotation_invariant : Bool - 146
} - 147
- 148
///| - 149
pub extend LBPConfig with @debug.Debug::{to_repr} - 150
- 151
///| - 152
pub extend LBPConfig with Eq::{not_equal, equal} - 153
- 154
///| - 155
pub extend LBPConfig with Default::{default} - 156
- 157
///| - 158
/// HOG 特征配置 - 159
#derive(Eq, Default, @debug.Debug) - 160
pub(all) struct HOGConfig { - 161
cell_size : Int32 - 162
block_size : Int32 - 163
num_bins : Int32 - 164
normalize : Bool - 165
} - 166
- 167
///| - 168
pub extend HOGConfig with @debug.Debug::{to_repr} - 169
- 170
///| - 171
pub extend HOGConfig with Eq::{not_equal, equal} - 172
- 173
///| - 174
pub extend HOGConfig with Default::{default} - 175
- 176
///| - 177
/// Gabor 特征配置 - 178
#derive(Eq, Default, @debug.Debug) - 179
pub(all) struct GaborConfig { - 180
num_scales : Int32 - 181
num_orientations : Int32 - 182
wavelength : Double - 183
aspect_ratio : Double - 184
} - 185
- 186
///| - 187
pub extend GaborConfig with @debug.Debug::{to_repr} - 188
- 189
///| - 190
pub extend GaborConfig with Eq::{not_equal, equal} - 191
- 192
///| - 193
pub extend GaborConfig with Default::{default} - 194
- 195
///| - 196
/// 创建默认颜色直方图配置 - 197
pub fn create_default_color_histogram_config() -> ColorHistogramConfig { - 198●
ColorHistogramConfig::{ - 199
num_bins: 256, - 200
color_space: "Gray", - 201
normalize: true, - 202
cumulative: false, - 203
} - 204
} - 205
- 206
///| - 207
/// 创建默认 LBP 配置 - 208
pub fn create_default_lbp_config() -> LBPConfig { - 209●
LBPConfig::{ - 210
radius: 1, - 211
num_points: 8, - 212
uniform: true, - 213
rotation_invariant: false, - 214
} - 215
} - 216
- 217
///| - 218
/// 创建默认 HOG 配置 - 219
pub fn create_default_hog_config() -> HOGConfig { - 220●
HOGConfig::{ cell_size: 8, block_size: 2, num_bins: 9, normalize: true, } - 221
} - 222
- 223
///| - 224
/// 提取颜色直方图特征 - 225
pub fn extract_color_histogram( - 226
img : @types.Image, - 227
config : ColorHistogramConfig, - 228
) -> CBIRImageFeature { - 229●
let w = img.width - 230
let h = img.height - 231
let total = w * h - 232
let histogram : Array[Double] = [] - 233
for _ in 0..<config.num_bins { - 234●
histogram.push(0.0) - 235
} - 236
- 237
for i in 0..<total { - 238●
let pixel = img.data[i].to_int() - 239
let bin = if config.num_bins > 0 { - 240●
pixel * config.num_bins / 256 - 241
} else { - 242○
0 - 243
} - 244
if bin >= 0 && bin < config.num_bins { - 245●
histogram[bin] += 1.0 - 246
} - 247
} - 248
- 249
// 归一化 - 250
if config.normalize && total > 0 { - 251●
for i in 0..<config.num_bins { - 252●
histogram[i] /= total.to_double() - 253
} - 254
} - 255
- 256
CBIRImageFeature::{ - 257
feature_type: FeatureType::ColorHistogram, - 258
feature_vector: histogram, - 259
feature_length: config.num_bins, - 260
image_id: "", - 261
image_path: "", - 262
width: w, - 263
height: h, - 264
extraction_time_ms: 0.0, - 265
} - 266
} - 267
- 268
///| - 269
/// 提取 LBP 特征 - 270
pub fn extract_lbp_feature( - 271
img : @types.Image, - 272
config : LBPConfig, - 273
) -> CBIRImageFeature { - 274●
ignore(config) - 275
let w = img.width - 276
let h = img.height - 277
let _ = w * h - 278
let num_bins = 256 - 279
let histogram : Array[Double] = [] - 280
for _ in 0..<num_bins { - 281●
histogram.push(0.0) - 282
} - 283
- 284
for y in 1..<(h - 1) { - 285●
for x in 1..<(w - 1) { - 286●
let center = img.data[y * w + x].to_int() - 287
let mut lbp_value = 0 - 288
let neighbors = [ - 289●
img.data[(y - 1) * w + (x - 1)].to_int(), - 290●
img.data[(y - 1) * w + x].to_int(), - 291●
img.data[(y - 1) * w + (x + 1)].to_int(), - 292●
img.data[y * w + (x + 1)].to_int(), - 293●
img.data[(y + 1) * w + (x + 1)].to_int(), - 294●
img.data[(y + 1) * w + x].to_int(), - 295●
img.data[(y + 1) * w + (x - 1)].to_int(), - 296●
img.data[y * w + (x - 1)].to_int(), - 297
] - 298
for i in 0..<8 { - 299●
if neighbors[i] >= center { - 300●
lbp_value = lbp_value | (1 << i) - 301
} - 302
} - 303
histogram[lbp_value] += 1.0 - 304
} - 305
} - 306
- 307
// 归一化 - 308
let valid_pixels = (w - 2) * (h - 2) - 309
if valid_pixels > 0 { - 310●
for i in 0..<num_bins { - 311●
histogram[i] /= valid_pixels.to_double() - 312
} - 313
} - 314
- 315
CBIRImageFeature::{ - 316
feature_type: FeatureType::LBP, - 317
feature_vector: histogram, - 318
feature_length: num_bins, - 319
image_id: "", - 320
image_path: "", - 321
width: w, - 322
height: h, - 323
extraction_time_ms: 0.0, - 324
} - 325
} - 326
- 327
///| - 328
/// 提取 HOG 特征(简化版) - 329
pub fn extract_hog_feature( - 330
img : @types.Image, - 331
config : HOGConfig, - 332
) -> CBIRImageFeature { - 333●
let w = img.width - 334
let h = img.height - 335
let cell_size = config.cell_size - 336
let num_cells_x = w / cell_size - 337
let num_cells_y = h / cell_size - 338
let num_bins = config.num_bins - 339
let feature_length = num_cells_x * num_cells_y * num_bins - 340
let feature : Array[Double] = [] - 341
for _ in 0..<feature_length { - 342●
feature.push(0.0) - 343
} - 344
- 345
for cy in 0..<num_cells_y { - 346●
for cx in 0..<num_cells_x { - 347●
let cell_hist : Array[Double] = [] - 348
for _ in 0..<num_bins { - 349●
cell_hist.push(0.0) - 350
} - 351
for y in 0..<cell_size { - 352●
for x in 0..<cell_size { - 353●
let px = cx * cell_size + x - 354
let py = cy * cell_size + y - 355
if px > 0 && px < w - 1 && py > 0 && py < h - 1 { - 356●
let gx = img.data[py * w + (px + 1)].to_double() - - 357●
img.data[py * w + (px - 1)].to_double() - 358●
let gy = img.data[(py + 1) * w + px].to_double() - - 359●
img.data[(py - 1) * w + px].to_double() - 360●
let magnitude = (gx * gx + gy * gy).sqrt() - 361◐
let mut angle = if gx != 0.0 { gy / gx * 0.1 } else { 1.5708 } - 362
if angle < 0.0 { - 363●
angle += 3.14159 - 364
} - 365●
let bin = (angle / 3.14159 * num_bins.to_double()).to_int() % - 366
num_bins - 367
cell_hist[bin] += magnitude - 368
} - 369
} - 370
} - 371
let base_idx = (cy * num_cells_x + cx) * num_bins - 372
for b in 0..<num_bins { - 373●
feature[base_idx + b] = cell_hist[b] - 374
} - 375
} - 376
} - 377
- 378
CBIRImageFeature::{ - 379
feature_type: FeatureType::HOG, - 380
feature_vector: feature, - 381
feature_length, - 382
image_id: "", - 383
image_path: "", - 384
width: w, - 385
height: h, - 386
extraction_time_ms: 0.0, - 387
} - 388
} - 389
- 390
///| - 391
/// 计算余弦相似度 - 392
pub fn cosine_similarity_cbir( - 393
feat1 : Array[Double], - 394
feat2 : Array[Double], - 395
) -> Double { - 396●
let len = if feat1.length() < feat2.length() { - 397○
feat1.length() - 398
} else { - 399●
feat2.length() - 400
} - 401
let mut dot = 0.0 - 402
let mut norm1 = 0.0 - 403
let mut norm2 = 0.0 - 404
- 405
for i in 0..<len { - 406●
dot += feat1[i] * feat2[i] - 407
norm1 += feat1[i] * feat1[i] - 408
norm2 += feat2[i] * feat2[i] - 409
} - 410
- 411
if norm1 > 0.0 && norm2 > 0.0 { - 412●
dot / (norm1 * norm2).sqrt() - 413
} else { - 414●
0.0 - 415
} - 416
} - 417
- 418
///| - 419
/// 计算欧氏距离 - 420
pub fn euclidean_distance_cbir( - 421
feat1 : Array[Double], - 422
feat2 : Array[Double], - 423
) -> Double { - 424●
let len = if feat1.length() < feat2.length() { - 425○
feat1.length() - 426
} else { - 427●
feat2.length() - 428
} - 429
let mut sum = 0.0 - 430
- 431
for i in 0..<len { - 432●
let diff = feat1[i] - feat2[i] - 433
sum += diff * diff - 434
} - 435
- 436●
sum.sqrt() - 437
} - 438
- 439
///| - 440
/// 计算曼哈顿距离 - 441
pub fn manhattan_distance_cbir( - 442
feat1 : Array[Double], - 443
feat2 : Array[Double], - 444
) -> Double { - 445●
let len = if feat1.length() < feat2.length() { - 446○
feat1.length() - 447
} else { - 448●
feat2.length() - 449
} - 450
let mut sum = 0.0 - 451
- 452
for i in 0..<len { - 453●
sum += (feat1[i] - feat2[i]).abs() - 454
} - 455
- 456
sum - 457
} - 458
- 459
///| - 460
/// 计算直方图交集 - 461
pub fn histogram_intersection_cbir( - 462
feat1 : Array[Double], - 463
feat2 : Array[Double], - 464
) -> Double { - 465●
let len = if feat1.length() < feat2.length() { - 466○
feat1.length() - 467
} else { - 468●
feat2.length() - 469
} - 470
let mut intersection = 0.0 - 471
let mut sum1 = 0.0 - 472
- 473
for i in 0..<len { - 474●
intersection += if feat1[i] < feat2[i] { feat1[i] } else { feat2[i] } - 475
sum1 += feat1[i] - 476
} - 477
- 478
if sum1 > 0.0 { - 479●
intersection / sum1 - 480
} else { - 481○
0.0 - 482
} - 483
} - 484
- 485
///| - 486
/// 计算相似度(根据度量类型) - 487
pub fn calculate_similarity( - 488
feat1 : Array[Double], - 489
feat2 : Array[Double], - 490
metric : SimilarityMetric, - 491
) -> Double { - 492●
if metric == SimilarityMetric::Cosine { - 493●
cosine_similarity_cbir(feat1, feat2) - 494●
} else if metric == SimilarityMetric::Euclidean { - 495●
let dist = euclidean_distance_cbir(feat1, feat2) - 496
1.0 / (1.0 + dist) - 497●
} else if metric == SimilarityMetric::Manhattan { - 498●
let dist = manhattan_distance_cbir(feat1, feat2) - 499
1.0 / (1.0 + dist) - 500●
} else if metric == SimilarityMetric::Intersection { - 501●
histogram_intersection_cbir(feat1, feat2) - 502
} else { - 503●
cosine_similarity_cbir(feat1, feat2) - 504
} - 505
} - 506
- 507
///| - 508
/// 创建图像索引 - 509
pub fn create_image_index() -> CBIRImageIndex { - 510●
CBIRImageIndex::{ - 511
features: [], - 512
num_images: 0, - 513
index_type: "flat", - 514
built: false, - 515
build_time_ms: 0.0, - 516
} - 517
} - 518
- 519
///| - 520
/// 向索引添加图像特征 - 521
pub fn add_to_index( - 522
index : CBIRImageIndex, - 523
feature : CBIRImageFeature, - 524
) -> CBIRImageIndex { - 525●
let features = index.features - 526●
features.push(feature) - 527
CBIRImageIndex::{ - 528
features, - 529●
num_images: features.length(), - 530
index_type: index.index_type, - 531
built: true, - 532
build_time_ms: index.build_time_ms, - 533
} - 534
} - 535
- 536
///| - 537
/// 图像检索 - 538
pub fn retrieve_images( - 539
query_feature : CBIRImageFeature, - 540
index : CBIRImageIndex, - 541
num_results : Int32, - 542
metric : SimilarityMetric, - 543
) -> CBIRRetrievalResultList { - 544●
let similarities : Array[Double] = [] - 545
for i in 0..<index.num_images { - 546●
let sim = calculate_similarity( - 547
query_feature.feature_vector, - 548
index.features[i].feature_vector, - 549
metric, - 550
) - 551●
similarities.push(sim) - 552
} - 553
- 554
// 按相似度排序(冒泡排序,降序) - 555
let indices : Array[Int32] = [] - 556
for i in 0..<index.num_images { - 557●
indices.push(i) - 558
} - 559
for i in 0..<index.num_images { - 560●
for j in 0..<(index.num_images - i - 1) { - 561●
if similarities[indices[j]] < similarities[indices[j + 1]] { - 562●
let temp = indices[j] - 563
indices[j] = indices[j + 1] - 564
indices[j + 1] = temp - 565
} - 566
} - 567
} - 568
- 569
let results : Array[CBIRRetrievalResult] = [] - 570
let result_count = if num_results < index.num_images { - 571●
num_results - 572
} else { - 573●
index.num_images - 574
} - 575
for i in 0..<result_count { - 576●
let idx = indices[i] - 577
let feat = index.features[idx] - 578●
results.push(CBIRRetrievalResult::{ - 579
image_id: feat.image_id, - 580
image_path: feat.image_path, - 581
similarity: similarities[idx], - 582
distance: 1.0 - similarities[idx], - 583
rank: i + 1, - 584
width: feat.width, - 585
height: feat.height, - 586
}) - 587
} - 588
- 589
CBIRRetrievalResultList::{ - 590
results, - 591
num_results: result_count, - 592
query_image_id: query_feature.image_id, - 593
retrieval_time_ms: 0.0, - 594
total_images_in_index: index.num_images, - 595
} - 596
} - 597
- 598
///| - 599
/// 提取组合特征(颜色+纹理+形状) - 600
pub fn extract_combined_features(img : @types.Image) -> CBIRImageFeature { - 601●
let color_config = create_default_color_histogram_config() - 602●
let color_feat = extract_color_histogram(img, color_config) - 603●
let lbp_config = create_default_lbp_config() - 604●
let lbp_feat = extract_lbp_feature(img, lbp_config) - 605
- 606
// 组合特征 - 607
let combined : Array[Double] = [] - 608
for v in color_feat.feature_vector { - 609●
combined.push(v) - 610
} - 611
for v in lbp_feat.feature_vector { - 612●
combined.push(v) - 613
} - 614
- 615
CBIRImageFeature::{ - 616
feature_type: FeatureType::Combined, - 617
feature_vector: combined, - 618●
feature_length: combined.length(), - 619
image_id: "", - 620
image_path: "", - 621
width: img.width, - 622
height: img.height, - 623
extraction_time_ms: 0.0, - 624
} - 625
} - 626
- 627
///| - 628
/// 生成检索报告 - 629
pub fn retrieval_report_to_string( - 630
results : CBIRRetrievalResultList, - 631
query_feature : CBIRImageFeature, - 632
) -> String { - 633●
let mut report = "## 图像检索报告\n\n" - 634
report = report + "### 查询信息\n\n" - 635
report = report + "| 指标 | 值 |\n|------|------|\n" - 636
report = report + "| 查询图像ID | " + query_feature.image_id + " |\n" - 637
let feat_type_str = if query_feature.feature_type == - 638
FeatureType::ColorHistogram { - 639●
"颜色直方图" - 640●
} else if query_feature.feature_type == FeatureType::Texture { - 641●
"纹理" - 642●
} else if query_feature.feature_type == FeatureType::Shape { - 643●
"形状" - 644●
} else if query_feature.feature_type == FeatureType::SIFT { - 645●
"SIFT" - 646●
} else if query_feature.feature_type == FeatureType::HOG { - 647●
"HOG" - 648●
} else if query_feature.feature_type == FeatureType::LBP { - 649●
"LBP" - 650●
} else if query_feature.feature_type == FeatureType::Combined { - 651●
"组合特征" - 652●
} else if query_feature.feature_type == FeatureType::Unknown { - 653●
"未知" - 654
} else { - 655●
"其他" - 656
} - 657
report = report + "| 特征类型 | " + feat_type_str + " |\n" - 658
report = report + - 659
"| 特征维度 | " + - 660●
query_feature.feature_length.to_string() + - 661
" |\n" - 662
report = report + - 663
"| 索引图像数 | " + - 664●
results.total_images_in_index.to_string() + - 665
" |\n" - 666
report = report + - 667
"| 检索耗时 | " + - 668●
results.retrieval_time_ms.to_string() + - 669
"ms |\n\n" - 670
- 671
if results.num_results > 0 { - 672●
report = report + "### 检索结果\n\n" - 673
report = report + "| 排名 | 图像ID | 相似度 | 距离 | 尺寸 |\n" - 674
report = report + "|------|--------|--------|------|------|\n" - 675
for result in results.results { - 676●
report = report + - 677
"| " + - 678●
result.rank.to_string() + - 679
" | " + - 680
result.image_id + - 681
" | " + - 682●
(result.similarity * 100.0).to_string() + - 683
"% | " + - 684●
result.distance.to_string() + - 685
" | " + - 686●
result.width.to_string() + - 687
"x" + - 688●
result.height.to_string() + - 689
" |\n" - 690
} - 691
} else { - 692●
report = report + "### 检索结果\n\n未找到匹配图像。\n" - 693
} - 694
- 695
report - 696
}