使用OpenCV和C ++在模板匹配中重复匹配

时间:2017-01-04 17:41:01

标签: python c++ opencv

我在OpenCv中基于OpenCV youtube Python教程实现了一个C ++代码:

此代码是关于将模板与图像匹配并在图像上出现它。 屏蔽步骤输出与预期相同的区域,但输出显示预期区域和一组重复值。我有两个疑惑

a)为什么会有重复?

b)我不得不用一个值来偏移对象周围的矩形。哪个错误导致了此偏移?我不得不向唯一方向偏移,让我相信代码中存在错误,而不是它是一个预期的功能。图像底部的一些区域也被错误地标记为正面。

C ++代码:

int main(){
    Mat img,gray,temp,res,graytemp;
    img=imread("/home/robo123/Downloads/opencv-template-matching-python-tutorial.jpg",1);
    temp=imread("/home/robo123/Downloads/opencv-template-for-matching.jpg",1);
    cvtColor(img,gray, COLOR_BGR2GRAY);
    cvtColor(temp,graytemp,COLOR_BGR2GRAY);
    matchTemplate(gray,graytemp,res,TM_CCOEFF_NORMED);
    double thresh = 0.78;
    threshold(res, res, thresh, 1., THRESH_BINARY);
    Mat rescolor;
    res.convertTo(rescolor, CV_8U, 255);
    int w,h,width,height;
    w=temp.rows;
    h=temp.cols;
    width=rescolor.rows;
    height=rescolor.cols;
    imshow("rescolor",rescolor);
    waitKey(0);


    for(int i=0;i<width;i++)
        for(int j=0;j<height;j++){
            Vec3b intensity = rescolor.at<cv::Vec3b>(j, i);
            uchar blue = intensity.val[0];
            uchar green = intensity.val[1];
            uchar red = intensity.val[2];
            if(blue!=0 || green!=0 || red!= 0){
                rectangle(img,Point(i+1.25*w,j),Point(i+2.25*w,j+h),Scalar(255,255,255),2,LINE_AA);
            }
        }
    imshow("IMage",img);
    waitKey(0);
    return 0;
}

来自在线的Python代码[我尝试用C ++编写的代码]:

import numpy as np
import cv2

img_bgr=cv2.imread('opencv-template-matching-python-tutorial.jpg')
img_gray=cv2.cvtColor(img_bgr,cv2.COLOR_BGR2GRAY)

template= cv2.imread('opencv-template-for-matching.jpg',0)
w, h=template.shape[::-1]

res= cv2.matchTemplate(img_gray, template, cv2.TM_CCOEFF_NORMED)
threshold= 0.78
loc= np.where(res>= threshold)

for pt in zip(*loc[::-1]):
    cv2.rectangle(img_bgr, pt, (pt[0]+w,pt[1]+h), (0,255,255) ,2)

cv2.imshow('detected', img_bgr)
cv2.waitKey(0)
cv2.destroyAllWindows()

Mask Matches of the template

0 个答案:

没有答案