Question

I'm trying to grab one image in my Android phone camera, define a template using ROI from this image, and then when successive images are grabbed, do template matching to find the new location of the template.

The problem is that it seems the template matching is not running: all the time the maxVal value is around 0.99, and the maxLoc is exactly the original location of the template (X, Y below).

What am I doing wrong?

This is the code when grabbing frames:

protected Bitmap processFrame(VideoCapture capture) {  
    capture.retrieve(mRgba, Highgui.CV_CAP_ANDROID_COLOR_FRAME_RGBA);  
    Imgproc.cvtColor(mRgba, mGray, Imgproc.COLOR_BGRA2GRAY);  
    Mat corrMap = new Mat();  
    Imgproc.matchTemplate(mGray, template, corrMap, Imgproc.TM_CCOEFF_NORMED);  
    MinMaxLocResult locRes = Core.minMaxLoc(corrMap);  
    double maxVal = locRes.maxVal;  
    Point maxLoc = locRes.maxLoc;  
    Scalar c = new Scalar(255, 0, 0, 255);  
    Core.putText(mRgba, Double.toString(maxVal), new Point(100,100), 3, 1, c, 2);  
    Core.putText(mRgba, Double.toString(maxLoc.x), new Point(100,130), 3, 1, c, 2);  
    Core.putText(mRgba, Double.toString(maxLoc.y), new Point(100,160), 3, 1, c, 2);  
}

And this is the code to generate the template:

X = 100;  
Y = 100;  
H = 150;  
W = 200;  
template = mGray.submat(Y-H/2, Y+H/2, X-W/2, X+W/2);
Was it helpful?

Solution

I might be far off here, but I believe the submat method returns a pointer to the submatrix of mGray. So your template changes from frame to frame since mRgba is always copied to mGray, but mGray is never reallocated. In this case, the solution would be to make a copy of the mGray submatrix. In C++, that would be something like:

mGray.submat(Y-H/2, Y+H/2, X-W/2, X+W/2).copyTo(template);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top