Take the 2-minute tour ×

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);
share|improve this question
Not an answer, but template matching is almost always a bad solution to locating/tracking objects. –  sammy Aug 1 '12 at 7:26
@vasile, I know, I just wanted to code something fast and simple... eventually I spent ~4 hours on this –  Yanai Ankri Aug 1 '12 at 12:02

1 Answer 1

up vote 2 down vote accepted

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);
share|improve this answer
This work! Thanks!! –  Yanai Ankri Aug 3 '12 at 13:03

Your Answer


