image.process\feature\template_match.mbt
80% · 84 / 105 points · 354 linesBackground color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.
- 1
///| - 2
/// # 模板匹配 template match - 3
/// - 4
/// 图像处理算法模块 - 5
/// 图像处理算法模块 Image processing algorithm module - 6
// 模板匹配(纯 MoonBit) - 7
// 在图像中滑动模板,计算每个位置的匹配分数 - 8
// 参考: https://docs.opencv.org/4.x/df/dfb/group__imgproc__object.html - 9
- 10
///| - 11
/// 模板匹配方法 - 12
pub(all) enum TemplateMatchMethod { - 13
SqDiff // 平方差:Σ(I-T)²,越小越好 - 14
CCorr // 互相关:Σ(I*T),越大越好 - 15
CCoeff // 相关系数:Σ(I-Ī)(T-T̄),越大越好 - 16
SqDiffNormed // 归一化平方差:[0,1],越小越好 - 17
CCorrNormed // 归一化互相关:[0,1],越大越好 - 18
CCoeffNormed // 归一化相关系数:[-1,1],越大越好 - 19
} - 20
- 21
///| - 22
/// 模板匹配结果 - 23
pub(all) struct TemplateMatchResult { - 24
x : Int32 // 匹配位置 x - 25
y : Int32 // 匹配位置 y - 26
score : Float // 匹配分数(语义依方法而定) - 27
} - 28
- 29
///| - 30
/// 模板匹配。 - 31
/// 在 img 中滑动 template,计算每个位置的匹配分数。 - 32
/// 返回所有位置的匹配结果(未排序)。 - 33
/// 对于 SqDiff/SqDiffNormed,score 越小越好;其余方法 score 越大越好。 - 34
pub fn template_match( - 35
img : @types.Image, - 36
template : @types.Image, - 37
match_method~ : TemplateMatchMethod = TemplateMatchMethod::CCoeffNormed, - 38
) -> Array[TemplateMatchResult] raise @types.LoadError { - 39
// 输入验证 - 40●
if img.width <= 0 || img.height <= 0 { - 41●
raise @types.LoadError::DecodeFailed( - 42
"template_match: 图像尺寸必须大于0", - 43
) - 44
} - 45
if img.channels < 1 || img.channels > 4 { - 46○
raise @types.LoadError::DecodeFailed( - 47
"template_match: 图像通道数必须在1-4之间", - 48
) - 49
} - 50
let expected_size = img.width * img.height * img.channels - 51●
if img.data.length() != expected_size { - 52○
raise @types.LoadError::DecodeFailed( - 53
"template_match: 图像数据大小不匹配,期望 " + - 54○
expected_size.to_string() + - 55
",实际 " + - 56○
img.data.length().to_string(), - 57
) - 58
} - 59
if template.width <= 0 || template.height <= 0 { - 60●
raise @types.LoadError::DecodeFailed( - 61
"template_match: 模板尺寸必须大于0", - 62
) - 63
} - 64
let tpl_expected_size = template.width * template.height * template.channels - 65●
if template.data.length() != tpl_expected_size { - 66○
raise @types.LoadError::DecodeFailed( - 67
"template_match: 模板数据大小不匹配,期望 " + - 68○
tpl_expected_size.to_string() + - 69
",实际 " + - 70○
template.data.length().to_string(), - 71
) - 72
} - 73
if img.channels != template.channels { - 74●
raise @types.LoadError::DecodeFailed( - 75
"template_match: 模板与图像通道数必须一致", - 76
) - 77
} - 78
if template.width > img.width || template.height > img.height { - 79●
raise @types.LoadError::DecodeFailed( - 80
"template_match: 模板不能大于图像", - 81
) - 82
} - 83
let w = img.width - 84
let tw = template.width - 85
let th = template.height - 86
// 转灰度以加速(多通道时按亮度公式合并) - 87●
let (gray_img, _) = to_gray_tm(img) - 88●
let (gray_tpl, _) = to_gray_tm(template) - 89
// 预计算模板统计量 - 90●
let tpl_sum = array_sum(gray_tpl) - 91●
let tpl_sq_sum = array_sq_sum(gray_tpl) - 92
let tpl_n = tw * th - 93●
let tpl_mean = Float::from_int(tpl_sum) / Float::from_int(tpl_n) - 94
let tpl_var_sum = tpl_sq_sum - - 95●
2.0F * tpl_mean * Float::from_int(tpl_sum) + - 96●
Float::from_int(tpl_n) * tpl_mean * tpl_mean - 97
let results : Array[TemplateMatchResult] = [] - 98
let sw = w - tw + 1 // 搜索宽度 - 99
let sh = img.height - th + 1 // 搜索高度 - 100
for y in 0..<sh { - 101●
for x in 0..<sw { - 102●
let score = match match_method { - 103●
SqDiff => compute_sqdiff(gray_img, w, gray_tpl, tw, th, x, y) - 104●
CCorr => compute_ccorr(gray_img, w, gray_tpl, tw, th, x, y) - 105○
CCoeff => compute_ccoeff(gray_img, w, gray_tpl, tw, th, x, y, tpl_mean) - 106
SqDiffNormed => - 107●
compute_sqdiff_normed(gray_img, w, gray_tpl, tw, th, x, y, tpl_sq_sum) - 108
CCorrNormed => - 109●
compute_ccorr_normed(gray_img, w, gray_tpl, tw, th, x, y, tpl_sq_sum) - 110
CCoeffNormed => - 111●
compute_ccoeff_normed( - 112
gray_img, w, gray_tpl, tw, th, x, y, tpl_mean, tpl_var_sum, - 113
) - 114
} - 115●
results.push(TemplateMatchResult::{ x, y, score, }) - 116
} - 117
} - 118
results - 119
} - 120
- 121
///| - 122
/// 找到最佳匹配位置 - 123
pub fn template_match_best( - 124
img : @types.Image, - 125
template : @types.Image, - 126
match_method~ : TemplateMatchMethod = TemplateMatchMethod::CCoeffNormed, - 127
) -> TemplateMatchResult? raise @types.LoadError { - 128●
let results = template_match(img, template, match_method~) - 129●
if results.length() == 0 { - 130○
return None - 131
} - 132
// SqDiff 系列越小越好,其余越大越好 - 133●
let want_min = match match_method { - 134●
SqDiff => true - 135○
SqDiffNormed => true - 136●
_ => false - 137
} - 138
let mut best = results[0] - 139●
for i in 1..<results.length() { - 140●
let r = results[i] - 141
if want_min { - 142●
if r.score < best.score { - 143●
best = r - 144
} - 145●
} else if r.score > best.score { - 146●
best = r - 147
} - 148
} - 149
Some(best) - 150
} - 151
- 152
// ==================== 匹配分数计算 ==================== - 153
- 154
///| - 155
fn compute_sqdiff( - 156
img : Array[Int32], - 157
w : Int32, - 158
tpl : Array[Int32], - 159
tw : Int32, - 160
th : Int32, - 161
ox : Int32, - 162
oy : Int32, - 163
) -> Float { - 164●
let mut sum = 0.0F - 165
for ty in 0..<th { - 166●
for tx in 0..<tw { - 167●
let diff = Float::from_int( - 168
img[(oy + ty) * w + (ox + tx)] - tpl[ty * tw + tx], - 169
) - 170
sum += diff * diff - 171
} - 172
} - 173
sum - 174
} - 175
- 176
///| - 177
fn compute_ccorr( - 178
img : Array[Int32], - 179
w : Int32, - 180
tpl : Array[Int32], - 181
tw : Int32, - 182
th : Int32, - 183
ox : Int32, - 184
oy : Int32, - 185
) -> Float { - 186●
let mut sum = 0.0F - 187
for ty in 0..<th { - 188●
for tx in 0..<tw { - 189●
sum += Float::from_int(img[(oy + ty) * w + (ox + tx)] * tpl[ty * tw + tx]) - 190
} - 191
} - 192
sum - 193
} - 194
- 195
///| - 196
fn compute_ccoeff( - 197
img : Array[Int32], - 198
w : Int32, - 199
tpl : Array[Int32], - 200
tw : Int32, - 201
th : Int32, - 202
ox : Int32, - 203
oy : Int32, - 204
tpl_mean : Float, - 205
) -> Float { - 206○
let n = tw * th - 207
let mut img_sum = 0 - 208
let mut cross = 0.0F - 209
for ty in 0..<th { - 210○
for tx in 0..<tw { - 211○
let iv = img[(oy + ty) * w + (ox + tx)] - 212
let tv = tpl[ty * tw + tx] - 213
img_sum += iv - 214○
cross += Float::from_int(iv) * Float::from_int(tv) - 215
} - 216
} - 217○
let img_mean = Float::from_int(img_sum) / Float::from_int(n) - 218○
cross - Float::from_int(n) * img_mean * tpl_mean - 219
} - 220
- 221
///| - 222
fn compute_sqdiff_normed( - 223
img : Array[Int32], - 224
w : Int32, - 225
tpl : Array[Int32], - 226
tw : Int32, - 227
th : Int32, - 228
ox : Int32, - 229
oy : Int32, - 230
tpl_sq_sum : Float, - 231
) -> Float { - 232●
let mut sq_diff = 0.0F - 233
let mut img_sq_sum = 0.0F - 234
for ty in 0..<th { - 235●
for tx in 0..<tw { - 236●
let iv = Float::from_int(img[(oy + ty) * w + (ox + tx)]) - 237●
let tv = Float::from_int(tpl[ty * tw + tx]) - 238
let diff = iv - tv - 239
sq_diff += diff * diff - 240
img_sq_sum += iv * iv - 241
} - 242
} - 243●
let denom = (img_sq_sum * tpl_sq_sum).sqrt() - 244
if denom < 0.000001F { - 245●
return 1.0F - 246
} - 247
sq_diff / denom - 248
} - 249
- 250
///| - 251
fn compute_ccorr_normed( - 252
img : Array[Int32], - 253
w : Int32, - 254
tpl : Array[Int32], - 255
tw : Int32, - 256
th : Int32, - 257
ox : Int32, - 258
oy : Int32, - 259
tpl_sq_sum : Float, - 260
) -> Float { - 261●
let mut cross = 0.0F - 262
let mut img_sq_sum = 0.0F - 263
for ty in 0..<th { - 264●
for tx in 0..<tw { - 265●
let iv = Float::from_int(img[(oy + ty) * w + (ox + tx)]) - 266●
let tv = Float::from_int(tpl[ty * tw + tx]) - 267
cross += iv * tv - 268
img_sq_sum += iv * iv - 269
} - 270
} - 271●
let denom = (img_sq_sum * tpl_sq_sum).sqrt() - 272
if denom < 0.000001F { - 273○
return 0.0F - 274
} - 275
cross / denom - 276
} - 277
- 278
///| - 279
fn compute_ccoeff_normed( - 280
img : Array[Int32], - 281
w : Int32, - 282
tpl : Array[Int32], - 283
tw : Int32, - 284
th : Int32, - 285
ox : Int32, - 286
oy : Int32, - 287
tpl_mean : Float, - 288
tpl_var_sum : Float, - 289
) -> Float { - 290●
let n = tw * th - 291
let mut img_sum = 0 - 292
let mut cross = 0.0F - 293
let mut img_sq_sum = 0.0F - 294
for ty in 0..<th { - 295●
for tx in 0..<tw { - 296●
let iv = img[(oy + ty) * w + (ox + tx)] - 297
let tv = tpl[ty * tw + tx] - 298
img_sum += iv - 299●
cross += Float::from_int(iv) * Float::from_int(tv) - 300●
img_sq_sum += Float::from_int(iv * iv) - 301
} - 302
} - 303●
let img_mean = Float::from_int(img_sum) / Float::from_int(n) - 304
let img_var_sum = img_sq_sum - - 305●
2.0F * img_mean * Float::from_int(img_sum) + - 306●
Float::from_int(n) * img_mean * img_mean - 307●
let numerator = cross - Float::from_int(n) * img_mean * tpl_mean - 308●
let denom = (img_var_sum * tpl_var_sum).sqrt() - 309
if denom < 0.000001F { - 310●
return 0.0F - 311
} - 312
numerator / denom - 313
} - 314
- 315
// ==================== 辅助函数 ==================== - 316
- 317
///| - 318
fn to_gray_tm(img : @types.Image) -> (Array[Int32], Int32) { - 319●
let w = img.width - 320
let h = img.height - 321
let ch = img.channels - 322
let n = w * h - 323●
let gray : Array[Int32] = Array::make(n, 0) - 324
for i in 0..<n { - 325●
if ch >= 3 { - 326●
let r = img.data[i * ch].to_int() - 327●
let g = img.data[i * ch + 1].to_int() - 328●
let b = img.data[i * ch + 2].to_int() - 329
gray[i] = (r * 299 + g * 587 + b * 114) / 1000 - 330
} else { - 331●
gray[i] = img.data[i * ch].to_int() - 332
} - 333
} - 334
(gray, n) - 335
} - 336
- 337
///| - 338
fn array_sum(arr : Array[Int32]) -> Int32 { - 339●
let mut s = 0 - 340
for v in arr { - 341●
s += v - 342
} - 343
s - 344
} - 345
- 346
///| - 347
fn array_sq_sum(arr : Array[Int32]) -> Float { - 348●
let mut s = 0.0F - 349
for v in arr { - 350●
let f = Float::from_int(v) - 351
s += f * f - 352
} - 353
s - 354
}