我创建了关注函数。
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()
答案 0 :(得分:1)
我想解决您的代码问题。
错误提示:
找不到流0的编解码器参数(视频:h264“
意味着x264
编解码器在当前环境中不可用。
您可以安装opencv-python
或
将编解码器初始化为MJPG
(Motion-JPEG)。原因是MJPG
适用于.avi
文件。
fourcc = cv2.VideoWriter.fourcc(*'MJPG')
问题#2:
您正在从RGB
转换为BGR
我建议您阅读图片,因此您不必转换为BGR
。
cv2.imread
以BGR
格式读取图像
还要确保每个图像的大小与定义的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"))