Python和OpenCV - 无法编写可读的avi视频文件

时间:2016-04-15 09:19:41

标签: python opencv ffmpeg windows-10 avi

我有这样的代码:

import numpy as np
import cv2


cap = cv2.VideoCapture('C:/Users/Hilman/haatsu/drive_recorder/sample/3.mov')

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret==True:
        frame = cv2.flip(frame,0)

        # write the flipped frame
        out.write(frame)

        cv2.imshow('frame',frame)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break
    else:
        break

# Release everything if job is finished
cap.release()
out.release()
cv2.destroyAllWindows()

output.avi无法播放。

尝试也将out = cv2.VideoWriter('output.avi', fourcc, 20.0, (640,480))更改为此类内容(如某些人所建议的)out = cv2.VideoWriter('output.avi', -1, 20.0, (640,480))。但是当我这样做时,我收到了这条消息

OpenCV: FFMPEG: tag 0xffffffff/'    ' is not found (format 'avi / AVI (Audio Video Interleaved)')'

可能是什么问题?我顺便使用Windows 10。

2 个答案:

答案 0 :(得分:1)

我无法在Windows 10计算机上运行该代码。

所以这就是我所做的:

  1. 我跟着these instructions并在机器上安装了最新的ffmpeg版本:
    1. 下载latest static build for Windows,然后解压缩文件。您可能需要7zip来提取。
    2. 在C:\中创建一个名为ffmpeg
    3. 的文件夹
    4. 将解压缩文件的内容复制到C:\ ffmpeg
    5. 编辑PATH环境变量以在末尾附加以下条目: C:\ffmpeg\bin;
    6. 通过打开cmd提示确认一切正常,并输入以下内容(注意您可能需要以管理员身份运行cmd): ffmpeg -version
  2. 修改了您的代码,如下所示:
  3. _

    import numpy as np
    import cv2
    import os
    
    base_path = 'C:\\Users\\Hilman\\haatsu\\drive_recorder\\sample\\'
    cap = cv2.VideoCapture('%s3.mov' % base_path)
    
    i = 0
    while(cap.isOpened()):
        ret, frame = cap.read()
        if ret==True:
            frame = cv2.flip(frame,0)
            cv2.imwrite(os.path.join(base_path, str(i) + '.png'), frame)
            i = i + 1
        else:
            break
    
    # Release everything if job is finished
    cap.release()  
    
    1. C:\Users\Hilman\haatsu\drive_recorder\sample打开命令提示符并运行以下命令:ffmpeg -framerate 29 -i %d.png -c:v libx264 -r 30 -pix_fmt yuv420p out.mp4
    2. 您的视频应保存为out.mp4

答案 1 :(得分:0)

我在Ubuntu 14.04上使用OpenCV 2.4.9,以下代码对我来说很合适:

import cv2
import cv
cap = cv2.VideoCapture(0)
ret,img=cap.read()
height , width , layers =  img.shape     
fps=20
video = cv2.VideoWriter("rec_out.avi", cv.CV_FOURCC(*'DIVX'), fps, (img.shape[1], img.shape[0]))
while True: 

    ret,img=cap.read()
    height , width , layers =  img.shape
        video.write(img)
    cv2.imshow('Video', img)
    #video.write(img)
    if(cv2.waitKey(10) & 0xFF == ord('b')):
            break



cv2.destroyAllWindows()
video.release()