【发布时间】: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