using opencv2 write streaming video in python

本小妞迷上赌 提交于 2019-12-09 07:01:50

问题


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:


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.




回答2:


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




回答3:


If you really want to use the codec provided for your pc to compress the frames.

  1. You should set the 2nd parameter of cv2.VideoWriter([filename, fourcc, fps, frameSize[, isColor]]) with the flag value = -1. This will allow you to see a list of codec compress utilized in your pc.
  2. In my case, the codec provided by Intel is named IYUV or I420. I don't know for another manufacturers. fourcc webpage.
  3. Set this information as follow

    fourcc = cv2.cv.CV_FOURCC('I','Y','U','V')
    # or
    fourcc = cv2.cv.CV_FOURCC('I','4','2','0')
    # settting all the information
    out = cv2.VideoWriter('output1.avi',fourcc, 20, (640,480))
    
  4. Remember two small parameters which gave me a big headache:
    • Don't forget the cv2.cv prefix
    • Introduce the correct frame Size

For everything else, you can use the code provided by Ekalic



来源:https://stackoverflow.com/questions/16045654/using-opencv2-write-streaming-video-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!