如何从提取的帧制作视频?

2024-04-26 12:46:02 发布

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

我将视频帧提取到一个名为“images”的文件夹中。在获得保存在我的文件夹中的图像后,我使用以下代码再次创建视频。我得到了视频,但是帧是随机排列的,我怎样才能按顺序排列呢?谢谢你的来信

import cv2
import os


image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for image in images:
    video.write(cv2.imread(os.path.join(image_folder, image)))

cv2.destroyAllWindows()
video.release()

请告知,我如何修复此问题?我希望视频与原始视频的速率相同,帧的顺序也一样


Tags: nameinimageimport文件夹imgfor视频
3条回答

如果您的需求需要您存储帧,请尝试此方法

import cv2
import os


image_folder = 'images'
video_name = 'video.avi'

images = [img for img in os.listdir(image_folder) if img.endswith(".jpg")]
frame = cv2.imread(os.path.join(image_folder, images[0]))
height, width, layers = frame.shape

video = cv2.VideoWriter(video_name, 0, 1, (width,height))

for i in range(len(images)):
    video.write(cv2.imread(os.path.join(image_folder, 'a'+str(i)+'.jpg')))

cv2.destroyAllWindows()
video.release()
  1. 打印images列表并查看图像的顺序?它们分类了吗
  2. 你的图片的文件名是什么?选择像00001.jpg00002.jpg这样的递增数字而不是1.jpg2.jpg是很有帮助的,这会搞乱排序

    1. 从os.listdir('.')读取后对图像进行排序: 这是pathlib库的一个示例
for filename in sorted([e for e in path.iterdir() if e.is_file() and str(e).endswith(".png")]):
    print(filename)
    img = cv2.imread(str(filename))
    img_array.append(img)

或者仅仅使用: for filename in sorted(os.listdir(path))

也许您可以尝试不保存图像并再次加载它们,而是从源视频捕获视频并将其传递给out object(在本例中为demo_output.avi)…类似以下内容:

import cv2

cap = cv2.VideoCapture('path to video/video.mp4')

fourcc = cv2.VideoWriter_fourcc(*'XVID')
ret, frame = cap.read()
fps_video=cap.get(cv2.CAP_PROP_FPS)
height,width = frame.shape[:2]
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values




while ret:
    frame = cv2.resize(frame, None, fx=1.0, fy=1.0, interpolation=cv2.INTER_AREA)

    out.write(frame)
    ret, frame = cap.read()

cap.release()
out.release()
cv2.destroyAllWindows()      

更新:

如果需要图像,然后保存视频文件:

import cv2
import os
import numpy as np

vidcap = cv2.VideoCapture('path to video/video.mp4')
success,image = vidcap.read()
fps_video = vidcap.get(cv2.CAP_PROP_FPS)
height,width = image.shape[:2]
count = 0
while success:

    cv2.imwrite("frame%d.jpg" % count, image)     # save frame as JPEG file      
    success,image = vidcap.read()
    print('Read a new frame: ', success)
    count += 1

vidcap.release()
lista = [[x[5:-4],x] for x in os.listdir() if x.endswith('jpg')]

result=[]
for x in lista:
    t1,t2 = np.int(x[0]),x[1]
    result.append([t1,t2])

result.sort()

#recording video back
fourcc = cv2.VideoWriter_fourcc(*'XVID')
out = cv2.VideoWriter('demo_output.avi',fourcc, fps_video, (width,height)) ##can be set with your width,height values

for img in result:
    frame = cv2.imread(img[1])
    out.write(frame)
out.release()

相关问题 更多 >