Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Measuring distance between two contours in video? OpenCV Python

Im trying to measure the distance between two objects in a video (in pixels value), using Python and openCV. The code I have so far finds the two objects and measure the distance between the two objects in the first frame, but not continiously as the objects move in the video. Im quite new to both OpenCV and Python, so any help is much appreciated.

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 contours are too small or large, ignore them:
        if cv2.contourArea(c)<100:
            continue
        elif cv2.contourArea(c)>2000:
            continue
        cv2.drawContours(frame, [c], -1, (0,255,0), 3)

        # Find center point of contours:
        M = cv2.moments(c)
        cX = int(M['m10'] /M['m00'])
        cY = int(M['m01'] /M['m00'])
        centers.append([cX,cY])

        # Find the distance D between the two contours:
    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 distance D continiously as the objects move in the video?

like image 896
agrom Avatar asked Mar 20 '26 20:03

agrom


1 Answers

You should delcare

center=[]

in the while loop, otherwise your line

centers.append([cX,cY])

keeps on appending to centers from the previous frame and

dx= centers[0][0] - centers[1][0]
dy = centers[0][1] - centers[1][1]

always take the centers from the first frame which have never been replaced.

This whole

if len(centers) >=2:

thing is not that great, you should check for exact equality anyway, given your application, because if you have more than 2 contours, there's not reason you would want only the first 2 findContours decided to give you.

like image 178
Soltius Avatar answered Mar 23 '26 08:03

Soltius



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!