我尝试使用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?
答案 0 :(得分:1)
你应该delcare
ref.observe(.value, with: { snapshot in
var newItems: [Contacts] = []
for item in snapshot.children {
let contact = Contacts(snapshot: item as! FIRDataSnapshot)
newItems.append(contact)
}
// filter the data here
let userID = FIRAuth.auth()?.currentUser?.email
let itemsMatching = self.items.filter {
$0.addedByUser == userID
}
self.items = newItems
let sortedNames = itemsMatching.sorted { $0.lastName < $1.lastName }
self.tableView.reloadData()
})
在while循环中,否则你的行
center=[]
继续追加前一帧的中心和
centers.append([cX,cY])
始终从第一帧中取出从未被替换的中心。
这整个
dx= centers[0][0] - centers[1][0]
dy = centers[0][1] - centers[1][1]
事情并不是那么好,你应该根据你的申请检查确切的平等,因为如果你有超过2个轮廓,那么你没有理由只想要前2个findContours决定给你。