Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using opencv2 write streaming video in python

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?

like image 952
mridul Avatar asked Feb 05 '26 20:02

mridul


2 Answers

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.

like image 114
Ekalic Avatar answered Feb 08 '26 17:02

Ekalic


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

like image 20
mridul Avatar answered Feb 08 '26 16:02

mridul