How do you properly track contours?

asked 2019-11-12 21:54:23 -0500

jlok gravatar image

updated 2019-11-12 22:07:20 -0500

I have code to find contours in the live camera preview and I want to track each contour with an ID. I'm using this code for each contour to create the tracker.

 Rect rect = Imgproc.boundingRect(contour);
 Rect2d rect2d = new Rect2d(rect.x, rect.y, rect.width, rect.height);
 multiTracker.add(TrackerMOSSE.create(), ingray, rect2d);

Since this is happening every frame obviously it is creating a new tracker every single frame and just keeps adding even if the contour is actually of the same object between frames. Is there a way to check if the contour/object is already tracked?

edit retag flag offensive close merge delete


  • please look at the samples , e.g. the csrt one

  • don't use multitracker, unless you have to

  • create a single tracker instance ONCE, call init(), and later, update() per frame.

berak gravatar imageberak ( 2019-11-13 01:35:50 -0500 )edit

Thanks, berak, the samples helped but I think I didn't adequately explain the concept I am having trouble with. I understand I use the update() method to track the object after it is detected once. But then when the detection runs again I have to figure out which contour belongs to which tracked object. Does opencv have a method to do this or is it something I have to write? I'm guessing a match by centroid location and area may work but may not be that simple if objects are erratic, fast moving, or fps is low.

Any algorithms or key terms you can point me to would be much appreciated. Thanks!

jlok gravatar imagejlok ( 2019-11-14 03:24:58 -0500 )edit

kalman filter, hungarian algorithm, kuhn-munkres

berak gravatar imageberak ( 2019-11-14 04:00:49 -0500 )edit

i have a c++ code i worked on it long time ago. i may share it if you can use it

sturkmen gravatar imagesturkmen ( 2019-11-14 14:09:47 -0500 )edit

That would be really helpful sturkmen! Are there PMs on here? If not you can email me at Thanks!

jlok gravatar imagejlok ( 2019-11-14 16:07:41 -0500 )edit

see thiscrude code using kalman filter, hungarian algorithm, kuhn-munkres ( based on early code of the repo to test it you need vtest.avi and haarcascade_fullbody.xml in the working directory and press SPACE when the first frame showed..... ask for more

sturkmen gravatar imagesturkmen ( 2019-11-14 17:24:36 -0500 )edit