测量视频中两个轮廓之间的距离? 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?
你应该删除
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 决定给你。
我正在尝试使用 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?
你应该删除
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 决定给你。