[英]How to capture video and save from webcam on click or pressing any key from keyboard using OpenCV
I want to capture and save a video from my webcam in a way that when I press any key ( enter
, space
etc) from keyboard then code should start save the video from current frame and when I press same key from keyboard then code should stop to save the video.我想从我的网络摄像头捕获并保存视频,当我从键盘按下任何键( enter
、 space
等)时,代码应该开始从当前帧保存视频,当我从键盘按下相同的键时,代码应该停止保存视频。 This is my code currently:这是我目前的代码:
import cv2
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
while(True):
ret, frame = cap.read()
k = cv2.waitKey(1)
if ret == True:
cv2.imshow('frame',frame)
# press space key to start recording
if k%256 == 32:
out.write(frame)
# press q key to close the program
elif k & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
My current code is capturing only one (current frame) when I press space key.当我按下空格键时,我当前的代码只捕获一个(当前帧)。 I need help to solve this problem.我需要帮助来解决这个问题。
Here is the same question but it is for images, it can't solve for videos. 这是同样的问题,但它是针对图像的,它不能解决视频。
Also is there a better way to capture and save video which can solve my problem?还有更好的方法来捕获和保存可以解决我的问题的视频吗?
The problem is that the code you wrote only calls the function out.write(frame)
when you press the space key.问题是您编写的代码仅在您按空格键时调用 function out.write(frame)
。
This should solve the issue:这应该可以解决问题:
create some sentinel variable at the beginning of your code.在代码的开头创建一些哨兵变量。 let's say record = False
假设record = False
And then inside your loop, make this change:然后在您的循环中,进行以下更改:
if k%256 == 32:
record = True
if record:
out.write(frame)
So this is how your code will look like:所以这就是你的代码的样子:
import cv2
record = False
cap = cv2.VideoCapture(0)
if (cap.isOpened() == False):
print("Unable to read camera feed")
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
out = cv2.VideoWriter('output.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))
while(True):
ret, frame = cap.read()
k = cv2.waitKey(1)
if ret == True:
cv2.imshow('frame',frame)
# press space key to start recording
if k%256 == 32:
record = True
if record:
out.write(frame)
# press q key to close the program
if k & 0xFF == ord('q'):
break
else:
break
cap.release()
out.release()
cv2.destroyAllWindows()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.