How to export video as .mp4 using openCV?

匿名 (未验证) 提交于 2019-12-03 10:10:24

问题:

I am trying to export video as .mp4 with openCV. I have tried several codecs but for now I had no success.

This is a function that constructs a video from frames:

def create_movie(self, out_directory, fps, total_frames):     img1 = cv2.imread("temp/scr0.png")     height, width, layers =  img1.shape     codec = cv2.cv.CV_FOURCC('X','V','I','D')     video = cv2.VideoWriter(out_directory, codec, fps, (width, height))      for i in range(total_frames):         img_name = "temp/scr" + str(i) + ".png"         img = cv2.imread(img_name)         video.write(img)      video.release()     cv2.destroyAllWindows() 

I usually get next error message, using different codecs:

Tag XVID/0x44495658 incompatible with output codec id '13' 

Is is possible to do this and how?

回答1:

There is a non-direct solution. You export as .avi and then convert to .mp4 using python's call which calls terminal command.

from subprocess import call  dir = out_directory.strip(".avi") command = "avconv -i %s.avi -c:v libx264 -c:a copy %s.mp4" % (dir, dir) call(command.split()) 


回答2:

May be a little bit late to answer this, but if you want to write an .MP4 file with OpenCV try this:

import cv2 #your previous code here  fourcc = cv2.VideoWriter_fourcc(*'a\0\0\0') out = cv2.VideoWriter('out.mp4', fourcc, fps, res)  #the character '\0' is the Null-Terminator or simply 0x00 in the ASCII-Table #tag: *'a\0\0\0' corresponds to 0x00000061  #your following code here 


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