Ask Your Question

How to keep tracking one object forever?

asked 2015-07-25 01:24:14 -0500

mmt gravatar image


I am trying to track ants, it is really hard because ants change its form and I am using grayscale image. It means, mosse and camshit didnt work on my project.

I have to track 1 special one(not a random), because I need to take its position and make some analysis. So I need a way to select one ant and track it forever, I tried everything, but nothing worked.

Well, I can set the the ant position manually, or by mouse, it is not a problem, the problem is how to keep tracking the same ant after know its first position.

I am using knn filter on my code to make it easier, because I will have all my ants white, and the background in black.

It is my code:

import numpy as np
import cv2

class ColourTracker:
    def __init__(self):

        self.capture = cv2.VideoCapture('video.avi')
        self.knn = cv2.createBackgroundSubtractorKNN()

    def run(self):
        while True:
            f, orig_img =

            if( not f ):

            fore = self.knn.apply( orig_img )
            back = self.knn.getBackgroundImage()
            kernel = np.ones((5,5),np.uint8)
            fore = cv2.erode( fore, kernel )
            fore = cv2.dilate( fore, kernel )
           # fore = fore[r:r+h, c:c+w]
            image, contours, hiearchy = cv2.findContours( fore, cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE )

            maximumArea = 0
            bestContour = None
            for contour in contours:
                currentArea = cv2.contourArea(contour)
                if currentArea > maximumArea:
                    bestContour = contour
                    maximumArea = currentArea

                    x,y,w,h = cv2.boundingRect(bestContour)
                    cv2.rectangle(orig_img, (x,y),(x+w,y+h), (0,0,255), 3)        

            cv2.imshow( "Background", back )
            cv2.imshow( "Frame", orig_img )

            k = cv2.waitKey(24) & 0xff 
            print k
            if k == 27:
if __name__ == "__main__":
    colour_tracker = ColourTracker()
edit retag flag offensive close merge delete

1 answer

Sort by ยป oldest newest most voted

answered 2015-10-08 09:52:18 -0500

RVQ gravatar image

I know it's a late answer but maybe it's still helpfull.

You could try it with the object tracking algorithm provied by DLIB

Checkout this Blogpost

edit flag offensive delete link more

Question Tools



Asked: 2015-07-25 01:24:14 -0500

Seen: 416 times

Last updated: Oct 08 '15