为什么我的OpenCV视频拒绝写入磁盘



所以我开始对openCV库将视频写入磁盘的能力感到非常困惑,因为即使是openCV文档也不是非常清楚在这种情况下视频实际上是如何写入的。我下面的代码似乎收集数据很好,但它试图写的视频文件中没有数据。我所要做的就是取一个我知道我可以的视频,将其中的数据改变为0到255之间的斜率,然后将数据写回磁盘。然而,由于我不明白的原因,最后的I/O步骤不配合。有人能帮忙吗?查找下面的代码:

import numpy as np
import cv2
import cv2.cv as cv

cap = cv2.VideoCapture("/Users/Steve/Documents/TestVideo.avi")  #The video
height = cap.get(cv.CV_CAP_PROP_FRAME_HEIGHT)  #We get some properties of the video
width = cap.get(cv.CV_CAP_PROP_FRAME_WIDTH)
fps = cap.get(cv.CV_CAP_PROP_FPS)
fourcc = cv2.cv.CV_FOURCC(*'PDVC')  #This is essential for testing
out = cv2.VideoWriter('output.avi',fourcc, int(fps), (int(width),int(height)))
xaxis = np.arange(width,dtype='int')
yaxis = np.arange(height,dtype='int')
xx,yy = np.meshgrid(xaxis,yaxis)
ramp=256*xx/int(width)   #This is a horizontal ramp image that scales from 0-255 across the width of the image

i=0
while(cap.isOpened()):
if i%100==0: print i
i+=1
ret, frame = cap.read()  #Grab a frame
if ret==True:
    # Change the frame data to the ramp instead of the original video                                                                                                                                                                                                                                             
    frame[:,:,0]=ramp   #The camera is B/W so the image is in B/W
    frame[:,:,1]=ramp
    frame[:,:,2]=ramp
    out.write(frame)  #Write to disk?
    cv2.imshow('frame',frame)  # I see the ramp as an imshow
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break
else:
    break
cap.release()   #Clear windows
out.release()
cv2.destroyAllWindows()

您的代码通常是正确的,但可能会在某个步骤中无声地失败。

尝试添加一些调试行:

out = cv2.VideoWriter('output2.avi',fourcc, int(fps), (int(width),int(height)))

else:
    print "frame %d is false" % i
    break

当我在本地测试你的代码时,我发现对于我读的大多数.avi文件,fps设置为0。手动将其设置为15或30有效。

我也没能在我的机器(osx)上运行你的fourcc,但是这个运行得很好。

fourcc = cv2.cv.CV_FOURCC('m', 'p', '4', 'v')

最新更新