Finding distance between two contours in video [closed]
Hello, Im trying to meassure the distance between two objects using Python. I have managed to do it in a still picture but now Im trying to do it in a video. The program measure the distance D in the first frame of the video, but not continiously as the objects move. Im quite new to Python and openCV, so any help is much appreciated. Here is the code:
import numpy as np
import cv2
import matplotlib.pyplot as plt
cap = cv2.VideoCapture('new4.avi')
centers=[]
while(True):
ret, frame = cap.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
_, thresh = cv2.threshold(gray, 127,255,0)
im2, contours, hierarchy = cv2.findContours(thresh,cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
for c in contours:
if cv2.contourArea(c)<100:
continue
elif cv2.contourArea(c)>2000:
continue
cv2.drawContours(frame, [c], -1, (0,255,0), 3)
M = cv2.moments(c)
cX = int(M['m10'] /M['m00'])
cY = int(M['m01'] /M['m00'])
centers.append([cX,cY])
if len(centers) >=2:
dx= centers[0][0] - centers[1][0]
dy = centers[0][1] - centers[1][1]
D = np.sqrt(dx*dx+dy*dy)
print(D)
cv2.imshow('frame', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
How can I get the value of D to change continiously as the two objects move in the video? *Edit: added the entire code.
Where is the grab loop in your code ? Are you applying
findcontour
each new frame ?Edited to include the entire code. The contour follows the objects for the enitre video, but cant seem to get the values from the contours.
Not familiar with python language, but could this always be verifying as true and thus leaving the while cycle?
if cv2.waitKey(1) & 0xFF == ord('q'): break
You have move
centers=[]
inside the grab loop or keep centers index and calculate D using current idx !It works now that I moved the
centers=[]
inside the while loop. Thanks for the response :)