Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Found a solution using the following code:

function(){
    var method  =   cv.TM_CCORR_NORMED;

    var source      =   cv.imread('source', 1);
    var template    =   cv.imread('template',  1);
    var mask        =   cv.imread('mask',  1);

    let result_cols =   source.cols - template.cols + 1;
    let result_rows =   source.rows - template.rows + 1;

    var result      =   new cv.Mat(result_rows, result_rows, cv.CV_32FC1);

    cv.matchTemplate(source, template, result, method, mask);

    cv.normalize(result, result, 0, 1, cv.NORM_MINMAX, -1, new cv.Mat() );

    let minMaxLoc   =   cv.minMaxLoc(result);

    let matchLoc;

    if(method == cv.TM_SQDIFF || method == cv.TM_SQDIFF_NORMED){
        matchLoc    =   minMaxLoc.minLoc;
    }else{
        matchLoc    =   minMaxLoc.maxLoc;
    }

    let canvas  =   document.createElement("canvas");

    var output  =   new cv.Mat();
    source.copyTo(output);

    let point1 = new cv.Point(matchLoc.x, matchLoc.y);
    let point2 = new cv.Point(matchLoc.x + template.cols, matchLoc.y + template.rows);

    let rectangleColor = new cv.Scalar(255, 0, 0);
    cv.rectangle(output, point1, point2, rectangleColor, 2, cv.LINE_AA, 0);

    cv.imshow(canvas, output);
    document.body.appendChild(canvas);
}

CV.TM_SQDIFF is still causing issues, but this seems to work well enough.