【问题标题】:Measuring distance between two contours in video? OpenCV Python测量视频中两个轮廓之间的距离? OpenCV Python
【发布时间】:2017-06-09 11:46:57
【问题描述】:

我正在尝试使用 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?

【问题讨论】:

  • 你有什么问题?第一个之后的帧中 D 的值是多少?
  • D值为295,即第一帧中的像素距离,但是当物体移动时,即使物体移近了,D值也只是保持在295。
  • 我从未使用过视频,所以我不知道 cap.read() 是如何工作的,但我假设每次 while 循环时,都会读取下一帧?你检查了吗?例如,通过在循环内移动 imshow(frame)
  • 不,我想我找到了错误!我会发布答案

标签: python opencv video distance opencv-contour


【解决方案1】:

你应该不关心

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 决定给你。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2015-05-03
    相关资源
    最近更新 更多