python - 如何从 mp4 视频文件夹中提取帧并将它们传输到另一个文件夹?
问题描述
我有一个装满 mp4 剪辑的文件夹(超过 200 个)。我想获取所有这些剪辑,提取它们的帧并将它们发送到另一个文件夹以存储所有帧。这是我到目前为止所拥有的(部分代码)但它只有在我有一个 mp4 文件时才有效文件夹:
import cv2 # for capturing videos
import math # for mathematical operations
import matplotlib.pyplot as plt # for plotting the images
import pandas as pd
from keras.preprocessing import image # for preprocessing the images
import numpy as np # for mathematical operations
from keras.utils import np_utils
from skimage.transform import resize # for resizing images
count = 0
videoFile = "sample_vid.mp4"
cap = cv2.VideoCapture(videoFile) # capturing the video from the given path
frameRate = cap.get(5) #frame rate
x=1
while(cap.isOpened()):
frameId = cap.get(1) #current frame number
ret, frame = cap.read()
if (ret != True):
break
if (frameId % math.floor(frameRate) == 0):
filename ="frame%d.jpg" % count;count+=1
cv2.imwrite(filename, frame)
cap.release()
print ("Done!")
同样,我在处理 python 中的文件目录并循环它时遇到了一些麻烦,以便它遍历另一个文件夹中的所有文件并将提取的帧发送到另一个文件夹中。
解决方案
使用glob
lib 查找mp4
文件夹中的所有文件。然后video2frames
对所有视频运行方法。
import cv2
import math
import glob
def video2frames(video_file_path):
count = 0
cap = cv2.VideoCapture(video_file_path)
frame_rate = cap.get(5)
while cap.isOpened():
frame_id = cap.get(1)
ret, frame = cap.read()
if not ret:
break
if frame_id % math.floor(frame_rate) == 0:
filename = '{}_frame_{}.jpg'.format(video_file_path, count)
count += 1
cv2.imwrite(filename, frame)
cap.release()
videos = glob.glob('/home/adam/*.mp4')
for i, video in enumerate(videos):
print('{}/{} - {}'.format(i+1, len(videos), video))
video2frames(video)
测试了两个视频。这是我所拥有的:
推荐阅读
- c++ - Qt:窗口图标质量不好
- c# - 如何通过我的实体基类上的属性过滤从实体框架返回的所有内容
- ruby-on-rails - 没有 class_name 的 FactoryBot 命名空间模型
- r - 如果数据帧符合 R 中另一个数据帧的标准,则对数据帧中的行中的数据点求和
- java - 从 S3 Bucket 下载压缩的 .gz 文件中的文件
- javascript - 在页面重新加载时保留 .html() 响应数据
- jupyter-notebook - 在纸空间上启动 juptyer 笔记本?
- javascript - 对象字面量内的箭头函数
- elm - 如何在 Elm 中读取本地文件?
- python - 如何使用 re.sub 搜索和替换确切的字符和数字?