0

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?

Erric
  • 123
  • 1
  • 10

1 Answers1

2

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()
Wazaki
  • 899
  • 1
  • 8
  • 22
  • Thats make sense... Would you help me to write a piece of code as you suggested? Because still I'm confused about it. Thanks – Erric May 21 '20 at 03:56
  • `if k & 0xFF == 32 : record ^= True` will allow to start AND STOP (or pause) recording when space key is pressed. – lenik May 21 '20 at 04:28