在 Mac 上使用 opencv 在 Python 中使用图像制作视频

Making a video with images in Python using opencv on Mac

我在名为 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
    1. 您想从图像创建一个 .avi 文件。因此你应该将 fourcc 初始化为 MJPG.
    • fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G') 
      
    • 当你想创建一个 .mp4 文件时你应该​​使用 mp4v

      • fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 
        
    1. 所有图片的尺寸和 VideoWriter 尺寸必须相同。

      例如:我所有的图片都是大小为(300, 167)。因此:

      • out = cv2.VideoWriter('video.avi', fourcc, 25, (300, 167), isColor=True)
        
      • 因为我要创建彩色图像,所以我将 isColor 变量设置为 true

    1. 我更喜欢 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()

更新


  • 如果质量真的很差,可以two-things。要放慢视频速度,您可以降低 frame-rate.

      1. .avi 更改为 .mp4
      • fourcc = cv2.VideoWriter_fourcc('m', 'p', '4', 'v') 
        
      1. 您可以更改 image size。例如,如果你们所有的图像大小都相同。然后获取第一张图片的高度和宽度,并将其设置为视频的大小。
      •  (h, w) = cv2.imread(glob("<your-path-here>*.png")[0]).shape[:2]
        
      • 如果你的图片不一样你仍然可以使用上面的代码,但质量可能不会提高。

      1. 您可以降低 frame-rate 以获得较慢的视频。例如: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()