Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

Finding distance between two contours in video

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:

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)

How can I get the value of D to change continiously as the two objects move in the video?

Finding distance between two contours in video

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.