首页 > 解决方案 > Python-将文件夹中的.png图像转换为视频

问题描述

我想用python构建一个屏幕录像机。所以,我使用了 pyautogui 库的 Screenshot() 函数。当我运行程序时,我会在这样的文件夹中获得单独的 PNG 图像-----

C:\rec\1.png
C:\rec\2.png
C:\rec\3.png
C:\rec\4.png
C:\rec\5.png

等等。现在我想将这些 PNG 图片转换成 MP4 或 AVI 格式的视频。我应该如何进行?

标签: pythonpython-3.xmp4avi

解决方案


我找到了这个

他们使用opencv库:

pip install opencv-python

然后:

import cv2
import numpy as np
import glob
 
img_array = []
for filename in glob.glob('C:/rec/*.png'): # (The only change I have made is here to the filepath.)
    img = cv2.imread(filename)
    height, width, layers = img.shape
    size = (width,height)
    img_array.append(img)
 
 
out = cv2.VideoWriter('project.avi',cv2.VideoWriter_fourcc(*'DIVX'), 15, size)
 
for i in range(len(img_array)):
    out.write(img_array[i])
out.release()

推荐阅读