Как извлечь кадры из папки видео mp4 и перенести их в другую папку? - PullRequest
0 голосов
/ 02 марта 2019

У меня есть папка, полная клипов 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 и зацикливанием его, чтобы он прошел через все файлы в другой папке и отправил кадры, извлеченные в другую папку.

Ответы [ 2 ]

0 голосов
/ 02 марта 2019

Используйте 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)

Протестировано на двух видео.Вот что у меня есть:

enter image description here

0 голосов
/ 02 марта 2019

Вы можете использовать os.walk для извлечения всех имен mp4 и перебирать их.Есть и другие способы, подробно описанные в Найти все файлы в каталоге с расширением .txt в Python (заменить txt на mp4).

Создать несколько файлов для поиска:

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']
...