OSX下的opencv VideoWriter不产生输出

时间:2012-05-15 16:36:45

标签: python opencv

我正在尝试在OSX下为OpenCV的python包装器创建一个视频。我正在使用python 2.7.1,opencv 2.3.1a,以及来自该版本opencv的willowgarage的python包装器。我有:

import cv,cv2
w = cv2.VideoWriter('foo.avi', cv.FOURCC('M','J','P','G'), 25, (100,100))
for i in range(100):
    w.write(np.ones((100,100,3), np.uint8))

OpenCV说

WARNING: Could not create empty movie file container.
Didn't successfully update movie file.
... [ 100 repetitions]

我不确定接下来要尝试什么

10 个答案:

答案 0 :(得分:48)

关于这个主题,有许多过时且不正确的在线指南 - 我想我几乎每个人都尝试过。在Mac OSX上查看基于源代码QTKit的VideoWriter实现后,我终于能够使用以下代码让VideoWriter输出有效的视频文件:

fps = 15
capSize = (1028,720) # this is the size of my source video
fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v') # note the lower case
self.vout = cv2.VideoWriter()
success = self.vout.open('output.mov',fourcc,fps,capSize,True) 

要编写图像框(请注意,imgFrame必须与上面的capSize大小相同,否则更新将失败):

self.vout.write(imgFrame) 

完成后请务必:

vout.release() 
self.vout = None

这适用于Mac OS X 10.8.5(Mountain Lion):不保证其他平台。我希望这个片段可以节省其他时间的实验!

答案 1 :(得分:3)

我正在使用macOS High Sierra 10.13.4,Python 3.6.5,OpenCV 3.4.1。

以下代码(源:https://www.learnopencv.com/read-write-and-display-a-video-using-opencv-cpp-python/)打开相机,按“ q”键成功关闭窗口,并将视频保存为.avi格式。

请注意,您需要将其作为.py文件运行。如果您在Jupyter Notebook中运行它,则关闭时该窗口将挂起,您需要强制退出Python以关闭该窗口。

import cv2
import numpy as np

# Create a VideoCapture object
cap = cv2.VideoCapture(0)

# Check if camera opened successfully
if (cap.isOpened() == False): 
  print("Unable to read camera feed")

# Default resolutions of the frame are obtained.The default resolutions are system dependent.
# We convert the resolutions from float to integer.
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))

# Define the codec and create VideoWriter object.The output is stored in 'outpy.avi' file.
out = cv2.VideoWriter('outpy.avi',cv2.VideoWriter_fourcc('M','J','P','G'), 10, (frame_width,frame_height))

while(True):
  ret, frame = cap.read()

  if ret == True: 

    # Write the frame into the file 'output.avi'
    out.write(frame)

    # Display the resulting frame    
    cv2.imshow('frame',frame)

    # Press Q on keyboard to stop recording
    if cv2.waitKey(1) & 0xFF == ord('q'):
      break

  # Break the loop
  else:
    break 

# When everything done, release the video capture and video write objects
cap.release()
out.release()

# Closes all the frames
cv2.destroyAllWindows() 

答案 2 :(得分:2)

在尝试了各种选项后,我发现我使用的frame.size不符合VideoWriter中指定的大小:因此将其设置为myMac 1280x720的默认设置使得一切正常工作!

import numpy as np
import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
out = cv2.VideoWriter()
succes = out.open('output.mp4v',fourcc, 15.0, (1280,720),True)
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()

答案 3 :(得分:2)

这是“大小”问题。

import cv2
import time

filename = time.strftime("%m-%d-%H-%M-%S") + '.avi'
fps = 16

cap = cv2.VideoCapture(0)

#in this way it always works, because your get the right "size"
size = (int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_WIDTH)),
        int(cap.get(cv2.cv.CV_CAP_PROP_FRAME_HEIGHT)))
fourcc = cv2.cv.FOURCC('8', 'B', 'P', 'S')     #works, large
out = cv2.VideoWriter(filename, fourcc, fps, size, True)

#in this way, you must set the "size" to your size, 
#because you don't know the default "size" is right or not
#cap.set(3, 640)
#cap.set(4, 480)
#out = cv2.VideoWriter(filename, fourcc, fps, (640, 480), True)

while(cap.isOpened()):
    ret, frame = cap.read()
    if ret == True:
        out.write(frame)
        cv2.imshow('frame', frame)

    if cv2.waitKey(1) & 0xFF == ord('q'):
        break;

else:
    print 'Error...'
    break;

cap.release()
out.release()
cv2.destroyAllWindows()

答案 4 :(得分:1)

这不是个好主意

您必须创建VideoWriter结构并使用方法WriteFrame

import cv
cv.NamedWindow('cap', 1)
w = cv.CreateVideoWriter('test.avi',cv.CV_FOURCC('X','V','I','D'),25,(640,480))
cap = cv.CaptureFromCAM(0)
while(1):
    img = cv.QueryFrame(cap)
    cv.ShowImage('cap', img)
    cv.WriteFrame(w, img)
    if cv.WaitKey(1) == 27:
        break
cv.DestroyWindow('cap')

答案 5 :(得分:1)

您的ffmpeg版本可能已过期。我遇到了与ffmpeg 0.8类似的问题,在我升级到ffmpeg 0.11之后它运行良好。

答案 6 :(得分:1)

这是@ ToddStellanova的答案的变体,对我有用:

def write_video(image_dir):
  '''
  Writes a video from a set of images in `image_dir`
  '''
  target = join('data/labelled-videos',
                basename(image_dir) + '.mp4v')
  codec = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')
  size = (256, 256)
  v = cv2.VideoWriter(target, codec, 16, size)
  for image_name in listdir(image_dir):
    image_filename = join(image_dir, image_name)
    arr = np.asarray(Image.open(image_filename))
    assert arr.shape[:2] == size
    v.write(arr)

答案 7 :(得分:1)

这是一个适用于以下版本的版本:

  • Python 3.6.3
  • OpenCV 3.3.1
  • macOS 10.13.1

使用brew install opencv安装。

#!/usr/bin/env python3

import cv2

def main():
    vc = cv2.VideoCapture()
    if not vc.open('input.mp4'):
        print('failed to open video capture')
        return

    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    # Match source video features.
    fps = vc.get(cv2.CAP_PROP_FPS)
    size = (
        int(vc.get(cv2.CAP_PROP_FRAME_WIDTH)),
        int(vc.get(cv2.CAP_PROP_FRAME_HEIGHT)),
    )

    vw = cv2.VideoWriter()
    if not vw.open('output.mp4', fourcc, fps, size):
        print('failed to open video writer')
        return

    while True:
        ok, frame = vc.read()
        if not ok:
            break

        # Flip upside down.
        frame = cv2.flip(frame, 0)

        # Write processed frame.
        vw.write(frame)

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

    vc.release()
    vw.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    main()

答案 8 :(得分:0)

感谢@TeddStellanova

这里是XCode C ++版本:

int fWidth = capture.get(CV_CAP_PROP_FRAME_WIDTH);
int fHeight = capture.get(CV_CAP_PROP_FRAME_HEIGHT);
string vid_path = path + "frames.mov";
VideoWriter vid(vid_path,CV_FOURCC('m','p','4','v'),30,Size(fWidth,fHeight),true);

答案 9 :(得分:0)

我的问题是 frame_width frame_height 。请尝试以下操作:

import cv2

cap = cv2.VideoCapture(0)

# Define the codec and create VideoWriter object
fourcc = cv2.VideoWriter_fourcc(*'MJPG')
frame_width = int(cap.get(3))
frame_height = int(cap.get(4))
size = (frame_width, frame_height)
fps = 10
out = cv2.VideoWriter("output.avi", fourcc, fps, size)

while(cap.isOpened()):
    ret, frame = cap.read()

    if ret:
        out.write(frame)  # write the frame
        cv2.imshow('frame', frame)
    else:
        break
    if cv2.waitKey(1) == 27:  # Esc
        break

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