我正在尝试使用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'未定义
似乎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()
答案 0 :(得分:2)
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_MSEC
或CV_CAP_PROP_MSEC
- 取决于OpenCV版本(请参阅Can't get VideoCapture property as the property identifier are not defined)。