Ask Your Question

Opencv4android mask for matchTemplate()

asked 2016-12-30 13:18:38 -0500

Ftahir192 gravatar image


I'm trying to speed up matchTemplate() for Android. I have already downsampled the image and template to half the original size, but the matching is still somewhat (understandably) slow on some older devices.

I acknowledged that I can pass in a mask to the matchTemplate() method. I'm trying to utilize this in the following way:

1) I know the location of the object from the previous frame, lets say its (180, 30). 2) I want to search only around some specified distance around this point, rather than the whole frame. 3) I create a region of interest based on this distance.

My question is, how can I utilize this roi such that I can take the current image being searched, and set everything outside the ROI to 0? I can then pass this in as a mask, and thus matchTemplate() would only search the image where pixel values are not 0 (so everything in the ROI)?

I have something such as the following:

cameraFrameROI = new Rect(topLeftX, topLeftY, width, height);
Mat mask = new Mat(mCameraMatResized);
// mask = 0 if not part of ROI, otherwise keep original value
Imgproc.matchTemplate(new Mat(mCameraMatResized, cameraFrameROI), mTemplateMatResized, mResult, mMatchMethod);

But I now need to utilize the ROI to create the actual mask.

Would this speed up template matching, and if so, I'm hoping if anyone can provide pointers.


edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2016-12-31 06:20:33 -0500

LBerger gravatar image

updated 2016-12-31 09:08:02 -0500

MatchTemplate use fourier transform. Only way to speed this algorithm is to reduce size as you have already done.

If you want to use previous location and you are sure that object (size(wx,wy)) move less than (dx,dy) per image you can extract a new image around previous location (x,y)

  Mat imgnew=img(Rect(x-dx-wx,y-dy-wy,wx+2*dx,wy+2*dy);

then you can try matchTemplate with this new image and hope size is less than previous image

image description

edit flag offensive delete link more


Hi. Thank you for the reply. I'm wondering if you can explain the numbers you used to calculate the rectangles parameters? Thanks.

Ftahir192 gravatar imageFtahir192 ( 2016-12-31 08:08:42 -0500 )edit

Thanks for the edit, that is perfect! When I call minMaxLoc, the coordinates of the object will be in terms of the new, shrinked image. How can I make it such that these coordinates map to the full sized image? I am drawing a rectangle over the frame to show the location of the object being matched.

Ftahir192 gravatar imageFtahir192 ( 2016-12-31 10:31:48 -0500 )edit

just add topleft corner (x-dv-wx/2,y-dv-wy/2) to matchtemplate result

LBerger gravatar imageLBerger ( 2017-01-01 03:09:52 -0500 )edit
Login/Signup to Answer

Question Tools

1 follower


Asked: 2016-12-30 13:18:38 -0500

Seen: 273 times

Last updated: Dec 31 '16