使用OpenCV和Python或MoviePy提取图像

7
我有一个含有8000帧的视频(.mp4)和一个csv文件,告诉我需要在视频中获取每个帧的时间和帧数。 视频中的帧数 = 8000 时间是一个数组,如[0.004, 0.005, ... 732秒] 给定数据中的最后时间为732秒。因此FPS = 8000 / 732 = ~10 我想能够在指定的时间从视频中提取图像帧,然后将这些图像路径写入.csv文件。
我尝试了多种方法: 第一种方法(openCV):
with open('./data/driving.csv', 'w') as csvfile:
fieldnames = ['image_path', 'time', 'speed']
writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
writer.writeheader()
vidcap = cv2.VideoCapture('./data/drive.mp4')
for idx, item in enumerate(ground_truth):
    # set video capture to specific time frame
    # multiply time by 1000 to convert to milliseconds
    vidcap.set(cv2.CAP_PROP_POS_MSEC, item[0] * 1000)
    # read in the image
    success, image = vidcap.read()
    if success:
        image_path = os.path.join('./data/IMG/', str(item[0]) + 
     '.jpg')
        # save image to IMG folder
        cv2.imwrite(image_path, image)
        # write row to driving.csv
        writer.writerow({'image_path': image_path, 
                 'time':item[0],
                 'speed':item[1],
                })

然而,这种方法并没有给我想要的总帧数。它只给出了与 FPS = 25 的视频对应的帧数。我认为我的 FPS = 8000 / 732s = 10.928s。

然后,我尝试使用 moviepy 以类似的方式捕获每个图像:

from moviepy.editor import VideoFileClip
clip1 = VideoFileClip('./data/drive.mp4')
with open('./data/driving.csv', 'w') as csvfile:
    fieldnames = ['image_path', 'time', 'speed']
    writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
    writer.writeheader()

    # Path to raw image folder
    abs_path_to_IMG = os.path.join('./data/IMG/')
    for idx, item in enumerate(ground_truth):
      image_path = os.path.join('./data/IMG/', str(item[0]) + '.jpg')
      clip1.save_frame(image_path, t = item[0])
      # write row to driving.csv
      writer.writerow({'image_path': image_path, 
             'time':item[0],
             'speed':item[1],
            })

然而,这种方法也不起作用,出于某种原因,我会捕获视频中的最后一帧数百次。
2个回答

12

这段代码可以在不同的时间提取帧:

import os
from moviepy.editor import *

def extract_frames(movie, times, imgdir):
    clip = VideoFileClip(movie)
    for t in times:
        imgpath = os.path.join(imgdir, '{}.png'.format(t))
        clip.save_frame(imgpath, t)

movie = 'movie.mp4'
imgdir = 'frames'
times = 0.1, 0.63, 0.947, 1.2, 3.8, 6.7

extract_frames(movie, times, imgdir)

你的ground_truth变量包含什么内容?

3

试试这个

from PIL import Image
from moviepy.editor import *

clip = VideoFileClip("video.mp4")

img = Image.fromarray(clip.get_frame(1))
img.show()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接