[英]Extract images using opencv and python or moviepy
我有一個大約有 8000 幀的視頻 (.mp4)。 我有一個 csv,它告訴我需要在視頻中抓取每一幀的時間,以及要抓取的幀數。 number_of_frames in video = 8000
times 是一個數組,如[0.004, 0.005, ... 732s]
給出的數據中最后一次是在 732s。 因此FPS = 8000 / 732 = ~10
我希望能夠在那些特定時間從視頻中提取圖像幀。 然后將這些圖像路徑寫入 a.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],
})
但是,這種方法也不起作用,出於某種原因,我捕獲了視頻中的最后一幀數百次。
此代碼可以在不同時間提取幀:
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
變量的內容是什么?
嘗試這個
from PIL import Image
from moviepy.editor import *
clip = VideoFileClip("video.mp4")
img = Image.fromarray(clip.get_frame(1))
img.show()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.