简体   繁体   中英

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. 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.

This should solve the issue:

create some sentinel variable at the beginning of your code. let's say 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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