使用OpenCvSharp實現目標跟蹤:
首先需要有兩張圖像. 一張為目標物體的圖像(object) 別一張是含有這個目標物體的圖像(Image). 使用Cv.MatchTemplate()方法在圖像中去尋找目標物體 . 得到"一張圖" 是一張結果圖.這個圖並不是簡單意義上的圖像. 而是尋找的結果. 如果圖像的大小為W & H 目標圖像的大小為w & h 那個這張結果圖的大小為 (W - w + 1) & (H - h + 1).
最后. 我們使用CV.MinMaxLoc() 方法 . 得到這個結果的左上角的CvPoint與右下角的CvPoint . 這樣,我們就可以用這兩個數據來做一些有意思的事情

1 using System;
2 using OpenCvSharp;
3
4 class Program
5 {
6 static void Main()
7 {
8 using (CvCapture cap = CvCapture.FromCamera(0))
9 using (CvWindow win = new CvWindow("CVS231"))
10 {
11 while (Cv.WaitKey(10) < 0) {
12 using (IplImage src = cap.QueryFrame()) // 源圖像
13 {
14 src.Flip(src,FlipMode.Y);
15
16 using (IplImage tpl = IplImage.FromFile("speedlimit55.jpg",LoadMode.Color)) // 目標圖像
17 using (IplImage res = new IplImage(new CvSize(src.Width - tpl.Width + 1, // 結果"圖像"
18 src.Height - tpl.Height + 1),
19 BitDepth.F32,1))
20 {
21 CvPoint minloc , maxloc;
22 // 使用這個方法 得到查找的結果圖
23 Cv.MatchTemplate(src,tpl,res,MatchTemplateMethod.CCoeff);
24 // 得到結果中的左上角與右下角
25 Cv.MinMaxLoc(res,out minloc,out maxloc);
26 // 我們 主要 使用的是結果的左上角. 然后使用這個左上角 + 目標圖像的大小
27 Cv.Rectangle(src,minloc,new CvPoint(minloc.X + tpl.Width,minloc.Y + tpl.Height),new CvColor(0,255,0),2);
28
29 win.Image = src;
30 }
31 }
32 }
33 }
34 }
35 }
運行結果: