I am trying to track objects with opencv in python from recorded video. I want to give a unique object nr to each visible object when it appears. For example, one object enters the screen and gets nr1, then a second joins the first and gets nr2, then the first object leaves the screen but the second is still visible and still gets object nr2 and not 1 (being the only object). I can't find any information on how to do this online. Any help (including code) is appreciated.
The code I have written so far for getting the contours and drawing object numbers:
cap = cv2.VideoCapture("video.mov")
while True:
flag, frame = cap.read()
cv2.drawContours(frame, contours, -1, (255,0,0) ,1)
for i in range(len(contours)):
cnt = contours[i]
cnt_nr = i+1
x,y,w,h = cv2.boundingRect(cnt)
cv2.putText(frame, str(cnt_nr), ((x+w)/2,(y+h)/2), cv2.FONT_HERSHEY_PLAIN, 1.8, (0,0,0))
cv2.imshow("Tracked frame",frame)
k = cv2.waitKey(0)
if k == 27:
cv2.destroyAllWindows()
break