繁体   English   中英

测量视频中两个轮廓之间的距离? OpenCV Python

[英]Measuring distance between two contours in video? OpenCV Python

我试图使用Python和openCV来测量视频中两个对象之间的距离(以像素值为单位)。 到目前为止,我所拥有的代码找到了两个对象并测量了第一帧中两个对象之间的距离,但是当对象在视频中移动时并不是连续的。 我对OpenCV和Python都很陌生,所以非常感谢任何帮助。

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()

当视频中的物体移动时,如何连续获得距离D.

你应该delcare

center=[]

在while循环中,否则你的行

centers.append([cX,cY])

继续追加前一帧的中心和

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

总是从第一帧中取出从未被替换过的中心。

整个

if len(centers) >=2:

事情并不是那么好,你应该根据你的申请检查确切的平等,因为如果你有超过2个轮廓,你没有理由只想要前2个findContours决定给你。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM