使用cv2.VideoWriter将图像列表转换为视频幻灯片

2024-03-29 05:15:23 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了follow函数

import cv2
import numpy as np

FPS = 10

def write_video(file_name, images, slide_time=5):
    fourcc = cv2.VideoWriter.fourcc(*'X264')
    out = cv2.VideoWriter(file_name, fourcc, FPS, (870, 580))

    for image in images:
        cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
        for _ in range(slide_time * FPS):
            out.write(cv_img)

    out.release()

它曾经工作过,但我把它弄坏了,不知道怎么了

当我尝试使用MPV打开时,我得到:

[ffmpeg/demuxer] avi: Could not find codec parameters for stream 0 (Video: h264 (X264 / 0x34363258), none, 870x580): unspecified pixel format
[ffmpeg/demuxer] Consider increasing the value for the 'analyzeduration' and 'probesize' options
 (+) Video --vid=1 (h264 870x580 10.000fps)


Exiting... (Errors when loading file)

以下是一个最小可复制示例:

import requests
from PIL import Image
from io import BytesIO
import cv2
import numpy as np



FPS = 10

res = requests.get('https://external-content.duckduckgo.com/iu/?u=https%3A%2F%2Ftse1.mm.bing.net%2Fth%3Fid%3DOIP.bNvIoWPYwYWXe-gpRKsalQHaE9%26pid%3DApi&f=1')

image = Image.open(BytesIO(res.content))
image = np.array(image)
image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

fourcc = cv2.VideoWriter.fourcc(*'MJPG')
video = cv2.VideoWriter('output.avi', fourcc, FPS, (870, 580))


for _ in range(13 * FPS):
    video.write(image)

video.release()

Tags: inimageimportnumpyforasvideonp
1条回答
网友
1楼 · 发布于 2024-03-29 05:15:23

我想用你的代码来解决这些问题

  • 问题1:

  • 错误显示:

    Could not find codec parameters for stream 0 (Video: h264"

    • 表示x264编解码器在当前环境中不可用

    • 您可以安装opencv-python

    • 将编解码器初始化为MJPG(运动JPEG)。原因是MJPG适用于.avi文件

    • fourcc = cv2.VideoWriter.fourcc(*'MJPG')
      
  • 问题2:


  • 您正在从RGB转换为BGR

  • 我建议您阅读图像,这样您就不必转换为BGR

  • cv2.imreadBGR格式读取图像

  • 还要确保每个图像的大小与定义的VideoCapture大小相同

    • for image in images:
          cv_img = cv2.imread(image)
          cv_img = cv2.resize(cv_img, (870, 580))
      

根据最小可再现误差更新代码:


import cv2
from glob import glob

FPS = 10


def write_video(file_name, images, slide_time=5):
    fourcc = cv2.VideoWriter.fourcc(*'MJPG')
    out = cv2.VideoWriter(file_name, fourcc, FPS, (870, 580))

    for image in images:
        cv_img = cv2.cvtColor(np.array(image), cv2.COLOR_RGB2BGR)
        for _ in range(slide_time * FPS):
            cv_img = cv2.resize(image, (870, 580))
            out.write(cv_img)

    out.release()


if __name__ == '__main__':
    write_video(file_name='result.avi', images=glob("b/*.jpg"))

相关问题 更多 >