我想在python中使用opencv从图像创建视频。但不幸的是,我发现该视频并未包含所有图片。然后我检查尺寸,发现所有图像尺寸不一样。所以我在将所有图像写入视频文件之前调整了大小。然后我在打开显示"无法解复用流"的视频文件时出错。我在这里错过了什么? 请纠正我。
这是我的代码:
import cv2
import numpy as np
import os
image_list=os.listdir(os.getcwd())
img=[]
i=0
for filename in image_list:
if(filename.endswith(".jpg")):
img.append(filename)
i+=1
frame=cv2.imread(img[0])
height,width,layers=frame.shape
fourcc = cv2.VideoWriter_fourcc(*'mp4v')
video=cv2.VideoWriter('video.avi',fourcc,1,(width,height))
for file in img:
image=cv2.imread(file)
resized=cv2.resize(image,(960,720)) #for my image list lowest size.
print(file,resized.shape)
video.write(resized)
video.release()
cv2.destroyAllWindows()
答案 0 :(得分:0)
问题是您要设置与第一张图像匹配的视频帧大小,然后保存的图像大小可能与第一张图像的大小不匹配。以下解决方案应该有效:
import os
import cv2
dir_path = os.getcwd()
ext = '.jpg'
output = 'video.avi'
shape = 960, 720
fps = 1
images = [f for f in os.listdir(dir_path) if f.endswith(ext)]
fourcc = cv2.VideoWriter_fourcc(*'DIVX')
video = cv2.VideoWriter(output, fourcc, fps, shape)
for image in images:
image_path = os.path.join(dir_path, image)
image = cv2.imread(image_path)
resized=cv2.resize(image,shape)
video.write(resized)
video.release()