using opencv2 write streaming video in python


Question

In my project i want to save streaming video.

import cv2;
if __name__ == "__main__":
     camera =  cv2.VideoCapture(0);
     while True:
          f,img = camera.read();
          cv2.imshow("webcam",img);
          if (cv2.waitKey (5) != -1):
                break;

` using above code it is possible to stream video from the web cam. How to write this streaming video to a file?

1
3
4/16/2013 7:39:51 PM

Accepted Answer

You can simply save the grabbed frames into images:

camera = cv2.VideoCapture(0)
i = 0
while True:
   f,img = camera.read()
   cv2.imshow("webcam",img)
   if (cv2.waitKey(5) != -1):
       break
   cv2.imwrite('{0:05d}.jpg'.format(i),img)
   i += 1

or to a video like this:

camera = cv2.VideoCapture(0)
video  = cv2.VideoWriter('video.avi', -1, 25, (640, 480));
while True:
   f,img = camera.read()
   video.write(img)
   cv2.imshow("webcam",img)
   if (cv2.waitKey(5) != -1):
       break
video.release()    

When creating VideoWriter object, you need to provide several parameters that you can extract from the input stream. A tutorial can be found here.

9
4/17/2013 5:12:26 AM

In ubuntu create video from given pictures using following code

os.system('ffmpeg -f image2 -r 8 -i %05d.bmp -vcodec mpeg4 -y movie3.mp4')

where name of picture is 00000.bmp,00001.bmp,00002.bmp etc..


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon