[英]How do I extract the frames from a folder of mp4 videos and transfer them to another folder?
我有一個裝滿 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)
測試了兩個視頻。 這是我所擁有的:
您可以使用os.walk
獲取所有 mp4 名稱並對其進行迭代。 在 Python中查找擴展名為 .txt 的目錄中的所有文件(用 mp4 替換 txt)中詳細介紹了其他方法。
創建一些文件以查找:
import os
with open("tata.mp4","w") as f: f.write(" ")
with open("tata1.mp4","w") as f: f.write(" ")
with open("tata2.mp4","w") as f: f.write(" ")
os.makedirs("./1/2/3")
with open("./1/subtata.mp4","w") as f: f.write(" ")
with open("./1/2/subtata1.mp4","w") as f: f.write(" ")
with open("./1/2/3/subtata2.mp4","w") as f: f.write(" ")
查找文件:
startdir = "./"
all_files = []
for root,dirs,files in os.walk(startdir):
for file in files:
if file.endswith(".mp4"):
all_files.append(os.path.join(root,file))
print(all_files)
for f in all_files:
# do your thing
輸出:
['./tata2.mp4', './tata1.mp4', './tata.mp4',
'./1/subtata.mp4',
'./1/2/subtata1.mp4',
'./1/2/3/subtata2.mp4']
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.