2

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);
Yanai Ankri
  • 439
  • 4
  • 11
  • Not an answer, but template matching is almost always a bad solution to locating/tracking objects. – Sam Aug 01 '12 at 07:26
  • @vasile, I know, I just wanted to code something fast and simple... eventually I spent ~4 hours on this – Yanai Ankri Aug 01 '12 at 12:02
  • @YanaiAnkri can you please provide some suggestions on [this question](http://stackoverflow.com/questions/29072000/opencv4android-template-matching-using-camera) ? – Mehul Joisar Mar 16 '15 at 08:02

1 Answers1

2

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);
Régis B.
  • 10,092
  • 6
  • 54
  • 90