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.

FatihAkici
  • 4,679
  • 2
  • 31
  • 48
  • 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: https://stackoverflow.com/questions/43176029/videocapture-always-returns-false-in-python-opencv-linux?noredirect=1&lq=1 – Dinesh Feb 24 '18 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 – Muhammad Ammar Malik Feb 24 '18 at 17:32
  • @MUHAMMADAMWARMALIK Change `cv2.waitKey(0)` to `cv2.waitKey(1)` – eyllanesc Feb 24 '18 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. – FatihAkici Feb 24 '18 at 17:35
  • Now it is working. – Muhammad Ammar Malik Feb 24 '18 at 17:37
  • can you tell me what is the difference between cv2.waitKey(0) and cv2.waitKey(1) – Muhammad Ammar Malik Feb 24 '18 at 17:38
  • @MUHAMMADAMWARMALIK see my answer. – eyllanesc Feb 24 '18 at 17:55

1 Answers1

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.

eyllanesc
  • 235,170
  • 19
  • 170
  • 241