基於opencv 的灰度模板匹配,其原裝函數只能匹配一個目標,本人通過對其進行簡單的封裝,以實現一次匹配多個目標:
先上效果:
模板圖片:
效果:經過本人的實際測試,效果還是穩定的。opencv 的灰度模板極容易出現錯誤匹配,需要根據實際應用條件來進行進一步處理,這個因項目實際而異,有興趣我們可以私下討論。(下面為本人項目用圖,匹配的穩定已經根據實際進行再次處理。當然,需要圖片也可以傳給你幾張!)
對於類似簡單的工業應用,opencv sharp基本都可以勝任哦.
好了,時間有限。上代碼,多目標匹配關鍵代碼:

1 /// <summary> 2 /// 用同一個模板來匹配多個相似目標,函數返回為多個目標對應的分數。 3 /// </summary> 4 /// <param name="srcimg">輸入圖片</param> 5 /// <param name="templateimg">輸入模板</param> 6 /// <param name="Target_Point_list">輸出多個目標的中心點位置</param> 7 /// <param name="findtarget_count">需要匹配的目標數量,默認是1</param> 8 /// <returns></returns> 9 public static List<double> MatcheAndFindMultiTarget(Mat srcimg, Mat templateimg, out List<Point> Target_Point_list, int findtarget_count=1) 10 { 11 12 List<double> allscore = new List<double>(); 13 Target_Point_list = new List<Point>(); 14 double minvalue = 0; 15 double maxvalue = 0; 16 17 Mat matchresult2 = new Mat(); 18 Cv2.MatchTemplate(srcimg, templateimg, matchresult2, TemplateMatchModes.CCorrNormed); 19 Point minLoc; 20 //尋找最幾個最值的位置 21 Mat mask = new Mat(matchresult2.Height, matchresult2.Width, MatType.CV_8UC1, Scalar.White); 22 Mat mask_sub = new Mat(matchresult2.Height, matchresult2.Width, MatType.CV_8UC1, Scalar.Black); 23 var Target_Point = new Point(0, 0); 24 for (int i=0;i<findtarget_count;i++) 25 { 26 Target_Point = default; 27 28 Cv2.MinMaxLoc(matchresult2, out minvalue, out maxvalue, out minLoc, out Target_Point, mask); 29 Rect maskrect = new Rect(Target_Point.X-templateimg.Width/2, Target_Point.Y-templateimg.Height/2, templateimg.Width, templateimg.Height); 30 mask_sub.Rectangle(maskrect, Scalar.White,-1); 31 mask = mask - mask_sub; 32 // mask.Set<float>(Target_Point.Y, Target_Point.X, 0.0f); 33 //轉中心 34 Target_Point = Target_Point + new Point(templateimg.Width / 2, templateimg.Height / 2); 35 //位置 36 Target_Point_list.Add(Target_Point); 37 //分數 38 allscore.Add(100 * maxvalue); 39 } 40 41 42 //輸出最大分數 43 matchresult2.Dispose(); 44 mask.Dispose(); 45 mask_sub.Dispose(); 46 return allscore; 47 }
有問題可以聯系我,相互討論學習,進步。