我试图在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))
Run Code Online (Sandbox Code Playgroud)
OpenCV说
WARNING: Could not create empty movie file container.
Didn't successfully update movie file.
... [ 100 repetitions]
Run Code Online (Sandbox Code Playgroud)
我不确定下一步该尝试什么
Tod*_*ova 49
关于这个主题有许多过时和不正确的在线指南 - 我想我几乎尝试了每一个.在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)
Run Code Online (Sandbox Code Playgroud)
要编写图像框(请注意,imgFrame必须与上面的capSize大小相同,否则更新将失败):
self.vout.write(imgFrame)
Run Code Online (Sandbox Code Playgroud)
完成后一定要:
vout.release()
self.vout = None
Run Code Online (Sandbox Code Playgroud)
这适用于Mac OS X 10.8.5(Mountain Lion):不保证其他平台.我希望这个片段可以节省其他时间的实验!
我使用的是 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 not cap.isOpened():
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:
# 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()
Run Code Online (Sandbox Code Playgroud)