public MatchInfo GetMatchPos(string Src, string Template) { MatchInfo myMatchInfo = new MatchInfo(); Image<Bgr, byte> a = new Image<Bgr, byte>(Src); Image<Bgr, byte> b = new Image<Bgr, byte>(Template); Image<Bgr, byte> aa = new Image<Bgr, byte>(Src); Image<Gray, float> c = new Image<Gray, float>(a.Width, a.Height); c = a.MatchTemplate(b, TemplateMatchingType.CcorrNormed); double min = 0, max = 0; Point maxp = new Point(0, 0); Point minp = new Point(0, 0); CvInvoke.MinMaxLoc(c, ref min, ref max, ref minp, ref maxp); //for (int i =0;i< c.; i++) {
//} Console.WriteLine(max + "-" + maxp.X + "," + maxp.Y); Console.WriteLine(min + "-"+minp.X + "," + minp.Y); CvInvoke.Rectangle(aa, new Rectangle(maxp, new Size(b.Width, b.Height)), new MCvScalar(0, 0, 255), 3); CvInvoke.Rectangle(aa, new Rectangle(minp, new Size(b.Width+13, b.Height+13)), new MCvScalar(0, 255, 255), 3); Image<Gray, float> c1 = c; int getcnt = 0; Lab1: c1 = getNextMinLoc(c1, maxp, (int)max, b.Width, b.Height); CvInvoke.MinMaxLoc(c1, ref min, ref max, ref minp, ref maxp); if (max < 0.95) { goto Lab2; } getcnt++; if (getcnt > 10) { goto Lab2; } Console.WriteLine(max + "-" + maxp.X + "," + maxp.Y); CvInvoke.Rectangle(aa, new Rectangle(maxp, new Size(b.Width, b.Height)), new MCvScalar(0, 255, 0), 3); goto Lab1; Lab2: myMatchInfo.matchMax = max; myMatchInfo.matchMin = min; myMatchInfo.matchPicture = aa; myMatchInfo.matchRectangle = new Rectangle(maxp, new Size(b.Width, b.Height)); myMatchInfo.matchMaxLoc = maxp; myMatchInfo.matchMinLoc = minp; return myMatchInfo; } Image<Gray, float> getNextMinLoc(Image<Gray, float> result, Point maxLoc, int maxVaule, int templatW, int templatH) {
// 先将第一个最大值点附近模板宽度和高度的都设置为最大值防止产生干扰 int startX = maxLoc.X- (templatW>>2);// int startY = maxLoc.Y- (templatH >> 2);// int endX = maxLoc.X+ (templatW >> 2);// int endY = maxLoc.Y+ (templatH >> 2);// if (startX < 0 || startY < 0) { startX = 0; startY = 0; } if (endX > result.Width - 1 || endY > result.Height - 1) { endX = result.Width - 1; endY = result.Height - 1; } int y, x; for (y = startY; y < endY; y++) { for (x = startX; x < endX; x++) { CvInvoke.cvSetReal2D(result, y, x, maxVaule); } }
return result;
}
|
请发表评论