1

I want to save my webcam video using opencv.

I wrote this code.

import numpy as np
import cv2

cap=cv2.VideoCapture(0)
#Define the codec
#FourCC code is passed as cv2.VideoWriter_fourcc('M','J','P','G')
#or cv2.VideoWriter_fourcc(*'MJPG') for MJPG.
fourcc = cv2.VideoWriter_fourcc(*'XVID')

#Define VideWrite object
#cv2.VideoWrite('arg1',arg2,arg3,(width,heigh))
#arg1:output file name
#arg2:Specify Fourcc code
#arg3: frames per seconds
#FourCC is a 4-byte code used to specify video codec
out=cv2.VideoWriter('SaveAVideo.avi',fourcc,20.0, (640,480))


while(cap.isOpened()):      

   ret,frame = cap.read()
   print('frame =',frame)
   print('ret = ',ret)
   if ret==True:
          frame =cv2.flip(frame,0)
          #Write the flipped frame
          out.write(frame)
          cv2.imshow('frame',frame)
          if cv2.waitKey(0) & 0xFF== ord('q'):
               break
   else:
          break
   print('after while loop')
# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

The problem I am facing is that it is recording only black screen, although I have checked my webcam.

7
  • Do you get outputs of print statements you have inside while loop? OpenCV needs to be compiled against specific version of ffmpeg. i.e. check if cap.isOpened() is true or false. Default installation of opencv has problems with ffmpeg library. Read the unaccepted last answer in: stackoverflow.com/questions/43176029/… Commented Feb 24, 2018 at 17:29
  • when i run the program it work i.e. its open a window (black window i.e. empty) and when i press 'q' it also save the video with the specified name but the problem is that the video which is saved is empty i.e black window but the duration of the videos is same Commented Feb 24, 2018 at 17:32
  • @MUHAMMADAMWARMALIK Change cv2.waitKey(0) to cv2.waitKey(1) Commented Feb 24, 2018 at 17:33
  • In line with @edit's comment, I would include some print statements after the cv2.imshow and cv2.waitkey lines, and see if they actually print as desired. Commented Feb 24, 2018 at 17:35
  • Now it is working. Commented Feb 24, 2018 at 17:37

1 Answer 1

1

As I said in my comment, the solution is to change:

cv2.waitKey(0) 

to:

cv2.waitKey(another_value)

by example 1.

According to the docs the parameter that receives cv2.waitKey() indicates the delay that is given:

enter image description here

In your case it is necessary since saving the image in the video, also is always convenient since an image is given at 60Hz so Overcoming that frequency is unnecessary.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.