Finding distance between two contours in video [closed]

asked 2017-01-24 05:15:08 -0500

agroms gravatar image

updated 2017-01-24 06:09:51 -0500

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.

edit retag flag offensive reopen merge delete

Closed for the following reason the question is answered, right answer was accepted by pklab
close date 2017-01-25 02:12:04.183815

Comments

Where is the grab loop in your code ? Are you applying findcontour each new frame ?

pklab gravatar imagepklab ( 2017-01-24 05:59:07 -0500 )edit

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.

agroms gravatar imageagroms ( 2017-01-24 06:15:28 -0500 )edit

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

Pedro Batista gravatar imagePedro Batista ( 2017-01-24 10:21:33 -0500 )edit
1

You have move centers=[] inside the grab loop or keep centers index and calculate D using current idx !

pklab gravatar imagepklab ( 2017-01-24 10:25:32 -0500 )edit

It works now that I moved the

centers=[]

inside the while loop. Thanks for the response :)

agroms gravatar imageagroms ( 2017-01-24 13:59:27 -0500 )edit