因此,我试图使我的网络摄像头捕捉运动,我如何注册运动是好的,但所有这些嵌套的时间循环,我的保存文件被拖到30分钟长,而不是10秒的预期。我不知道我做错了什么。
我的意思是拖出,我记录了10秒,但当我进入我的文件,审查镜头,这是30分钟,只是一些帧。
这样做的目的是让它注册运动,然后记录10秒,并将记录保存为.avi文件。
import cv2
from datetime import datetime
import time
vid_capture = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
ret, cur_frame = vid_capture.read()
prev_frame = cur_frame
capture_duration = 10
motion = False
while True:
frame_diff = cv2.absdiff(cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY), cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY))
if frame_diff.max() > 150:
motion = True
if motion:
start_time = time.time()
name = str(datetime.now().date()) + "_" + str(datetime.now().time().hour) + "-" + str(datetime.now().time().minute) + "-" + str(datetime.now().time().second) + ".avi"
out = cv2.VideoWriter(name, fourcc, 20.0, (640,480))
ret, cur_frame = vid_capture.read()
while time.time() - start_time < capture_duration:
if ret:
out.write(cur_frame)
cv2.imshow('Input', cur_frame)
else:
break
out.release()
cv2.destroyAllWindows()
motion = False
prev_frame = cur_frame.copy()
ret, cur_frame = vid_capture.read()
if cv2.waitKey(1) == 27:
break
vid_capture.release()发布于 2022-03-08 21:43:01
您的代码可能运行得非常快,它可能会创建ie。每秒钟100帧。
但是20.0 in VideoWriter并不会以每秒20帧的速度编写视频,但它只会告诉玩家他们必须每秒显示20帧。但是,如果您每秒创建100个帧,那么最后它将需要5秒而不是1秒来显示它(100frames/20FPS = 5seconds)。
您必须放慢速度来创建每个50ms - (1000ms/20FPS)的新帧,您可以尝试waitKey(50)。
编辑:
因为代码可能需要一些时间来创建框架,所以在waitKey (即48 )中可能需要更小的处理量,或者您可以尝试测量循环中的时间并使用
waitKey( 50 - (loop_end-loop_start) )运行内部while-loop,它一直在编写相同的帧--您应该在这个while-loop中使用ret, cur_frame = vid_capture.read()。
较短:
name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.avi")motion = (frame_diff.max() > 150) 我看到了一个可能的问题:当窗口关闭时,cv2.waitKey无法工作--因为系统只将键/鼠标事件发送到活动窗口,而当窗口关闭时,cv2可能无法获得键/鼠标事件。
from datetime import datetime
import time
import cv2
vid_capture = cv2.VideoCapture(0)
fourcc = cv2.VideoWriter_fourcc(*'XVID')
ret, cur_frame = vid_capture.read()
prev_frame = cur_frame
capture_duration = 10
while True:
frame_diff = cv2.absdiff(cv2.cvtColor(cur_frame, cv2.COLOR_BGR2GRAY), cv2.cvtColor(prev_frame, cv2.COLOR_BGR2GRAY))
motion = (frame_diff.max() > 150)
if motion:
name = datetime.now().strftime("%Y-%m-%d_%H-%M-%S.avi")
print(name)
out = cv2.VideoWriter(name, fourcc, 20.0, (640,480))
start_time = time.time()
while time.time() - start_time <= capture_duration:
ret, cur_frame = vid_capture.read()
if ret:
out.write(cur_frame)
cv2.imshow(name, cur_frame)
if cv2.waitKey(50) == 27:
break
else:
break
out.release()
cv2.destroyAllWindows()
prev_frame = cur_frame.copy()
ret, cur_frame = vid_capture.read()
if cv2.waitKey(1) == 27:
break
vid_capture.release()https://stackoverflow.com/questions/71400924
复制相似问题