image.process\feature\template_match.mbt

80% · 84 / 105 points · 354 lines

Background color reports the state of each line. Underlined characters mark exact instrumented byte offsets; hover them to inspect the visit count.

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