首页 > 解决方案 > OpenCV 不写入文件

问题描述

我一直在尝试从文件夹中的所有静止图像创建视频。写入的文件大小为 0KB。我已经检查并且所有文件都被 glob.glob 部分正确检索(这就是注释的 print(filename) 行的内容)。我尝试了多个fourcc 选项,但没有一个有效。有没有人看到会导致这种情况的问题?这也在 Jupyter Notebook 中的 python 3 上运行。

fold_file = fold +'/*jpg' #fold is just the path to folder containing the images
img_array=[]
for filename in glob.glob(fold_file):
    #print(filename)
    img=cv2.imread(filename)
    height, width, layer = img.shape
    size = (width,height)
    img_array.append(img)

out = cv2.VideoWriter('pleasework.avi',cv2.VideoWriter.fourcc('X','V','I','D') ,15,size)

for image in range(len(img_array)):
    out.write(image)


cv2.destroyAllWindows()
out.release()

标签: pythonopencv

解决方案


这行代码可能是您的问题:

for image in range(len(img_array)):
    out.write(image)

len()函数计算序列中的项目数。让我们假设,为了论证,您在img_array. 然后len()会返回5。然后我们将该长度值输入到range()函数中以生成从0to的数字序列4(即最多但不包括 5)。

然后,我们使用for循环解析该范围,并将数字放入方法0中,而不是放入图像中。4out.write()

你可能想要的是这样的:

for image in img_array:
    out.write(image)

img_array是一个 Python list,因此可以通过for循环本地解析,而无需使用任何类型的长度计算等。


推荐阅读