我在一个名为jupyter的文件夹中有一些jpg格式的图,我想把它们放在一起制作一个视频,但当我运行代码时,它不会保存和显示视频。
import cv2
import os
from os.path import isfile, join
def convert_pictures_to_video(pathIn, pathOut, fps, time):
frame_array=[]
files= [f for f in os.listdir(pathIn) if isfile(join(pathIn,f))]
for i in range (len(files)):
filename=pathIn+files[i]
img=cv2.imread(filename)
height, width, layers=img.shape
size=(width,height)
for k in range (time):
frame_array.append(img)
out=cv2.VideoWriter(pathOut, cv2.VideoWriter_fourcc(*'mp4v'),fps,size)
for i in range(len(frame_array)):
out.write(frame_array[i])
cv2.destroyAllWindows()
out.release()
pathIn='/Users/jupyter/'
pathOut='/Users/jupyter/video.avi'
fps=1
time=20
convert_pictures_to_video(pathIn, pathOut, fps, time
-
- 您想要从图像创建一个
.avi
文件。因此,应该将fourcc
初始化为MJPG
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
-
当您想要创建
.mp4
文件时,应该使用mp4v
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
- 您想要从图像创建一个
-
-
所有图像的大小和
VideoWriter
的大小必须相同。例如:我所有的图片都是大小(300167(。因此:
out = cv2.VideoWriter('video.avi', fourcc, 25, (300, 167), isColor=True)
-
由于我要创建彩色图像,我将
isColor
变量设置为真正的
-
-
-
我更喜欢
glob
来收集所有图像:for img in sorted(glob.glob("ball_tracking/*.png")): img = cv2.imread(img) img = cv2.resize(img, (300, 167)) out.write(img)
-
代码:
import cv2
import glob
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
out = cv2.VideoWriter('video.avi', fourcc, 25, (300, 167), isColor=True)
for img in sorted(glob.glob("ball_tracking/*.png")):
img = cv2.imread(img)
img = cv2.resize(img, (300, 167))
out.write(img)
out.release()
更新
如果质量真的很差,你可以做两件事。为了降低视频的速度,可以降低帧速率。
- 将
.avi
更改为.mp4
fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v')
- 将
- 您可以更改
image size
。例如,如果你们所有的图像都是相同的大小。然后获取第一个图像的高度和宽度,并将其设置为视频的大小
(h, w) = cv2.imread(glob("<your-path-here>*.png")[0]).shape[:2]
如果你的图像不一样,你仍然可以使用上面的代码,但质量可能不会提高。
- 您可以更改
- 对于较慢的视频,可以降低帧速率。例如:25比2
out = cv2.VideoWriter('video.avi', fourcc, 2, (w, h), isColor=True)
更新代码:
import cv2
import glob
fourcc = cv2.VideoWriter_fourcc('M', 'P', '4', 'V')
(h, w) = cv2.imread(glob("<your-path-here>*.png")[0]).shape[:2]
out = cv2.VideoWriter('video.mp4', fourcc, 2, (w, h), isColor=True)
for img in sorted(glob.glob("<your-path-here>*.png")):
img = cv2.imread(img)
img = cv2.resize(img, (w, h))
out.write(img)
out.release()