gpt4 book ai didi

python - 在 Python 中使用 OpenCV 检测从 mp4 视频中检测到的对象位置的时间戳

转载 作者:太空宇宙 更新时间:2023-11-03 21:32:47 25 4
gpt4 key购买 nike

我正在尝试在 Python 中使用 OpenCV 从 mp4 视频文件中检测对象。我能够检测到视频中的对象。

我想获取视频文件中检测到对象的位置的时间戳,并将其写入文本文件。

到目前为止,这是我的代码:

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
toys= my_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in toys:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
#Logic to write time stamp to file goes here
return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

我尝试使用 VideoCapture 的方法 get() 使用属性标识符,如下所示:

 video_capture.get(CV_CAP_PROP_POS_MSEC)

但出现错误name 'CV_CAP_PROP_POS_MSEC' is not defined

似乎 cv2 没有实现此方法或属性标识符。

cv2 中还有其他方法可以实现我想要的吗?

请帮忙。


已解决

每次在视频中检测到对象时,这将打印对象位置的时间戳。这是工作代码:

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
toys= my_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in toys:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
print("Toy Detected at: "+str(video_capture.get(cv2.CAP_PROP_POS_MSEC)))
return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

最佳答案

cv2 确实实现了属性,但需要使用全名。

这应该可行

import cv2

my_cascade = cv2.CascadeClassifier('toy.xml')

def detect(gray, frame):
toys= my_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in toys:
cv2.rectangle(frame, (x, y), (x+w, y+h), (255, 0, 0), 2)
#Logic to write time stamp to file goes here
return frame

video_capture = cv2.VideoCapture('home.mp4')
cv2.startWindowThread()
while True:
_, frame = video_capture.read()
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
canvas = detect(gray, frame)
print (video_capture.get(cv2.CAP_PROP_POS_MSEC))
cv2.imshow('Video', canvas)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
video_capture.release()
cv2.destroyAllWindows()

即您需要实例 video_capture 的属性,而不是通用类 VideoCapture 并且属性名称以类 cv2. 为前缀。属性名称是 CAP_PROP_POS_MSECCV_CAP_PROP_MSEC - 取决于 OpenCV 版本(参见 Can't get VideoCapture property as the property identifier are not defined)。

关于python - 在 Python 中使用 OpenCV 检测从 mp4 视频中检测到的对象位置的时间戳,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47678708/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com