Multiple template matching only detects one match

后端 未结 1 1441
别那么骄傲
别那么骄傲 2021-01-14 23:10

I\'m trying to match this image

in this image

However, I can\'t find more than one boss enemy. What do I need to do to find the others?

相关标签:
1条回答
  • 2021-01-14 23:42

    I didn't debug your code, but since it doesn't work (probably floodfill is messing up your result matrix), this is a simple working sample.

    I iterate over the maximum points in the result matrix finding the blobs where values are over a threshold, and finding the highest value within each blob (used as a mask to retrieve actual values in the result matrix).

    #include <opencv2\opencv.hpp>
    #include <vector>
    using namespace std;
    using namespace cv;
    
    int main()
    {
        Mat3b img = imread("path_to_image");
        Mat3b templ = imread("path_to_template");
    
        Mat1b img_gray;
        Mat1b templ_gray;
        cvtColor(img, img_gray, COLOR_BGR2GRAY);
        cvtColor(templ, templ_gray, COLOR_BGR2GRAY);
    
        Mat1f result;
        matchTemplate(img, templ, result, TM_CCOEFF_NORMED);
    
        double thresh = 0.7;
        threshold(result, result, thresh, 1., THRESH_BINARY);
    
        Mat1b resb;
        result.convertTo(resb, CV_8U, 255);
    
        vector<vector<Point>> contours;
        findContours(resb, contours, RETR_LIST, CHAIN_APPROX_SIMPLE);
    
        for (int i=0; i<contours.size(); ++i)
        {
            Mat1b mask(result.rows, result.cols, uchar(0));
            drawContours(mask, contours, i, Scalar(255), CV_FILLED);
    
            Point max_point;
            double max_val;
            minMaxLoc(result, NULL, &max_val, NULL, &max_point, mask);
    
            rectangle(img, Rect(max_point.x, max_point.y, templ.cols, templ.rows), Scalar(0,255,0), 2);
        }
        return 0;
    }
    

    Result:

    0 讨论(0)
提交回复
热议问题