繁体   English   中英

如何使用 OpenCV 在单击或按键盘上的任意键时从网络摄像头捕获视频并保存

[英]How to capture video and save from webcam on click or pressing any key from keyboard using OpenCV

我想从我的网络摄像头捕获并保存视频,当我从键盘按下任何键( enterspace等)时,代码应该开始从当前帧保存视频,当我从键盘按下相同的键时,代码应该停止保存视频。 这是我目前的代码:

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() 

当我按下空格键时,我当前的代码只捕获一个(当前帧)。 我需要帮助来解决这个问题。

这是同样的问题,但它是针对图像的,它不能解决视频。

还有更好的方法来捕获和保存可以解决我的问题的视频吗?

问题是您编写的代码仅在您按空格键时调用 function out.write(frame)

这应该可以解决问题:

在代码的开头创建一些哨兵变量。 假设record = False

然后在您的循环中,进行以下更改:

if k%256 == 32:
    record = True

if record:
    out.write(frame)

所以这就是你的代码的样子:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM