1. 程式人生 > 其它 >使用python對視訊檔案解析度進行分組

使用python對視訊檔案解析度進行分組

在平時的工作中,我們的目錄有很多的視訊檔案,如果你沒有一個好的視訊分類習慣,在找視訊素材的時候會很費時,通過對視訊的分辨路進行分類可以在需要的時候快速找到你想要的視訊解析度。當然人工去分類是一種比較費時費力的工作,通過軟體也好,程式也罷都是為了可以提高我們的工作效率。

程式碼分享

import os
import subprocess
import json
import shutil
import datetime


def get_files(file_dir):
    for root, dirs, files in os.walk(file_dir):
        if len(files) > 0:
            # 獲取圖片路徑
            for f in files:
                if f.endswith(".mp4"):
                    p = os.path.join(root, f)
                    h, w, t = get_video_info(p)

                    new_dir = os.path.realpath(
                        "{}\{}x{}".format(file_dir, h, w))
                    if not os.path.exists(new_dir):
                        os.makedirs(new_dir)
                    shutil.move(p, os.path.join(new_dir, "{}.mp4".format(t)))


def get_video_info(file_path):

    cmd = "ffprobe -v quiet -print_format json -show_streams -i {}".format(
        file_path)

    with open('output.json', 'w') as f:
        subprocess.call(cmd, stdout=f)

    with open('output.json', 'r') as f:
        streams = json.load(f)
        for i in streams["streams"]:
            if i['codec_type'] == "video":
                print(file_path)
                t2 = ""
                try:
                    t1 = datetime.datetime.strptime(
                        i['tags']['creation_time'], "%Y-%m-%dT%H:%M:%S.%f%z")
                    t2 = datetime.datetime.strftime(t1, '%Y%m%d%H%M%S')
                except KeyError:
                    t2 = datetime.datetime.now().strftime('%Y%m%d%H%M%S')
                return i['height'], i['width'], t2
            else:
                continue


if __name__ == "__main__":
    file_dir = input("dir:")
    get_files(file_dir)

程式碼使用了ffprobe獲取視訊資訊

原文:http://www.rencaixiu.cn/archives/811/