飞道的博客

《自拍教程72》Python批量重命名视频文件,AV专家必备!

361人阅读  评论(0)

案例故事: 任何一款终端产品只要涉及视频播放,就肯定涉及视频的解码播放测试,
作为一名专业的多媒体测试人员,我们需要一堆的规范的标准视频测试文件
但是发现视频资源名字命名的很随意比如:big_buck_bunny_720p_h264.mp4,
以上命名不能看出视频文件的具体编码规格,
测试经理要求我进行批量重命名工作,模板如下,
视频流信息 + 音频流信息 + 容器.容器
视频编码格式_规格_分辨率_帧率_视频比特率_音频编码格式_采样率_声道数_音频比特率_容器.容器
H.264_BPL3.2_1280x720_30fps_1024kbps_aac_44.1KHz_stereo_128Kbps_mp4.mp4

视频编解码相关参数


其中视频流,主要是通过批量压缩每一帧的图片来实现视频编码(压缩),
其主要涉及以下关键技术参数:

视频技术参数 参数释义 举例
视频编码格式
(压缩技术)
即将图片数据压缩的一类技术,
不同的编码格式,
其压缩率与压缩效果不一样。
H.265/H.264/H.263
Mpeg1/Mpeg2/Mpeg4,
WMV,Real,VP8,VP9
视频分辨率
(单位:Pixel)
视频里的每一张图片的分辨率
(图片长像素点数量*图片宽像素点数量)
4096×2160(4K), 1920x1080,
1280x720,720×480,
640x480, 320x480等
视频帧率
(单位:fps)
每秒钟的图片数量,图片就是帧,一帧代表一张图片 12fps,24fps,30fps,60fps
视频比特率
(单位:Kbps)
每秒钟的视频流所含的数据量,
大概等于 = 编码格式压缩比帧率分辨率
1Mbps,5Mbps, 10Mbps, 512Kbps等等。
视频容器 文件后缀,将视频流+音频流封装的一种文件格式 .mp4; .3gp; .mkv; .mov;
.wmv; .avi; .webm;
.rmvb; .rm; .ts;

准备阶段
  1. 确保mediainfo.exe 命令行工具已经加入环境变量,查看其具体功能方法
  2. 以下是某个视频文件的mediainfo信息, 都是文本,Python处理起来肯定很简单的。
  3. 如果要进行批量重命名视频,我们还是用输入输出文件架构,如下:

	+---Input_Video   #批量放入待命名的视频
	|       1.mp4
	|       2.3gp
	|       
	+---Output_Video   #批量输出已命名的视频
	|     H.264_BPL3.2_1280x720_30fps_1024kbps_aac_44.1KHz_stereo_128Kbps_mp4.mp4
	|     Mpeg4_SPL1_640x480_12fps_512kbps_AAC_24KHz_stereo_56Kbps_3gp.3gp
	|
	\video_info.py  # 视频流解析模块
	\audio_info.py  # 音频流解析模块
	\rename_video.py  #Python重命名视频的批处理脚本,双击运行即可


定义video_info.py模块

由于涉及较复杂的代码,建议直接用面向对象类的编程方式实现:

# coding=utf-8

import os
import re
import subprocess


class VideoinfoGetter():
    def __init__(self, video_file):
        '''判断文件是否存在,如果存在获取其mediainfo信息'''
        if os.path.exists(video_file):
            self.video_file = video_file
            p_obj = subprocess.Popen('mediainfo "%s"' % self.video_file, shell=True, stdout=subprocess.PIPE,
                                     stderr=subprocess.PIPE)
            self.info = p_obj.stdout.read().decode("utf-8")  # 解决非英文字符的编码问题
        else:
            raise FileNotFoundError("Not this File!")  # 如果多媒体文件路径不存在,必须中断

    def get_video_codec(self):
        '''获取视频的编码格式,比如H.264, Mpeg4, H.263等'''
        try:
            video_codec = re.findall(r"Codec ID\s+:\s(.*)", self.info)
            if (len(video_codec) >= 3):
                video_codec = video_codec[1].strip()
            elif (len(video_codec) == 2):
                video_codec = video_codec[0].strip()
            elif (len(video_codec) == 1):
                video_codec = video_codec[0].strip()
            else:
                video_codec = "undef"
        except:
            video_codec = "undef"
        return self.__format_video_codec(video_codec)

    def get_video_profile(self):
        '''获取视频编码格式的规格,比如Main Profile Level 3.2'''
        try:
            v_profile = re.findall(r"Format profile\s+:\s(.*)", self.info)
            # print vprofile
            if (len(v_profile) == 3):
                video_profile = v_profile[1].strip()
            elif (len(v_profile) == 2):
                video_profile = v_profile[0].strip()
            elif (len(v_profile) == 1):
                video_profile = v_profile[0].strip()
            else:
                video_profile = "undef"
        except:
            video_profile = "undef"
        return self.__format_video_profile(video_profile)

    def get_video_fps(self):
        '''获取视频的帧率,比如60fps,30fps'''
        try:
            video_fps = re.findall(r'Frame rate\s+:\s(.*)', self.info)[0].strip()
            return self.__format_fps(video_fps)
        except:
            return "undef"

    def get_video_height(self):
        '''获取视频图像的高度(宽方向上的像素点)'''
        try:
            video_height = re.findall(r"Height\s+:\s(.*) pixels", self.info)[0].strip()
            return video_height
        except:
            return "undef"

    def get_video_weight(self):
        '''获取视频图像的宽度(长方向上的像素点)'''
        try:
            video_weight = re.findall(r"Width\s+:\s(.*) pixels", self.info)[0].strip()
            return video_weight
        except:
            return "undef"

    def get_video_bitrate(self):
        '''获取视频比特率,比如560kbps'''
        try:
            # print findall(r"Bit rate\s+:\s(.*)", self.info)
            video_bitrate = re.findall(r"Bit rate\s+:\s(.*)", self.info)[0].strip()
            return self.__format_bitrate(video_bitrate)
        except:
            return "undef"

    def get_video_container(self):
        '''获取视频容器,即文件后缀名,比如.mp4 ,.3gp'''
        _, video_container = os.path.splitext(self.video_file)
        if not video_container:
            raise NameError("This file no extension")
        audio_container = video_container.replace(".", "")
        return audio_container

    def __format_video_profile(self, info):
        '''格式化视频的规格参数,比如,MPL3.2'''
        v_profile_level = None
        v_profile = None
        v_level = None
        if (re.match(r'(.*)@(.*)', info)):
            m = re.match(r'(.*)@(.*)', info)
            m1 = m.group(1)
            m2 = m.group(2)
            if (m1 == "Simple"):
                v_profile = "SP"
            elif (m1 == "BaseLine"):
                v_profile = "BP"
            elif (m1 == "Baseline"):
                v_profile = "BP"
            elif (m1 == "Advanced Simple"):
                v_profile = "ASP"
            elif (m1 == "AdvancedSimple"):
                v_profile = "ASP"
            elif (m1 == "Main"):
                v_profile = "MP"
            elif (m1 == "High"):
                v_profile = "HP"
            elif (m1 == "Advanced Profile"):
                v_profile = "AP"
            elif (m1 == "Simple Profile Low"):
                v_profile = "SPL"
            elif (m1 == "Simple Profile Main"):
                v_profile = "SPM"
            elif (m1 == "Main Profile Main"):
                v_profile = "MPM"
            else:
                v_profile = m1
            if (m2 == "0.0"):
                v_level = "L0.0"
            else:
                v_level = m2
            v_profile_level = v_profile + v_level

        elif (re.match(r"(.*)\s(.*)", info)):
            v_profile_level = re.sub(r"\s", "", info)
        else:
            v_profile_level = info
        return v_profile_level

    def __format_video_codec(self, info):
        '''格式化输出视频编码格式'''
        v_codec = None
        if (info == "avc1"):
            v_codec = "H.264"
        elif (info == "AVC"):
            v_codec = "H.264"
        elif (info == "27"):
            v_codec = "H.264"
        elif (info == "s263"):
            v_codec = "H.263"
        elif (info == "20"):
            v_codec = "Mpeg4"
        elif (info == "DIVX"):
            v_codec = "DIVX4"
        elif (info == "DX50"):
            v_codec = "DIVX5"
        elif (info == "XVID"):
            v_codec = "XVID"
        elif (info == "WVC1"):
            v_codec = "VC1"
        elif (info == "WMV1"):
            v_codec = "WMV7"
        elif (info == "WMV2"):
            v_codec = "WMV8"
        elif (info == "WMV3"):
            v_codec = "WMV9"
        elif (info == "V_VP8"):
            v_codec = "VP8"
        elif (info == "2"):
            v_codec = "SorensonSpark"
        elif (info == "RV40"):
            v_codec = "Realvideo"
        else:
            v_codec = "undef"
        return v_codec

    def __format_fps(self, info):
        '''格式化输出帧率'''
        if (re.match(r'(.*) fps', info)):
            m = re.match(r'(.*) fps', info)
            try:
                info = str(int(int(float(m.group(1)) + 0.5))) + "fps"
            except:
                info = "Nofps"
        else:
            info = "Nofps"
        return info

    def __format_bitrate(self, info):
        '''格式化输出比特率'''
        if (re.match(r'(.*) Kbps', info)):
            info = re.sub(r'\s', "", info)
            m = re.match(r'(.*)Kbps', info)
            try:
                info = str(int(float(m.group(1)))) + "Kbps"
            except Exception as e:
                # print(e)
                info = "NoBit"
        else:
            info = "NoBit"
        return info

定义audio_info.py模块

请参考文章《Python mediainfo批量重命名音频文件》里的audio_info.py

调用video_info.py, audio_info.py模块

实现批量重命名视频文件

# coding=utf-8

import os
import shutil
import video_info
import audio_info

curdir = os.getcwd()

input_video_path = curdir + "\\Input_Video\\"
filelist = os.listdir(input_video_path)
output_video_path = curdir + "\\Output_Video\\"

if (len(filelist) != 0):
    for i in filelist:
        video_file = os.path.join(input_video_path, i)

        # 先解析视频流
        v_obj = video_info.VideoinfoGetter(video_file)
        vcodec = v_obj.get_video_codec()
        vprofile = v_obj.get_video_profile()
        vresoultion = v_obj.get_video_weight() + "x" + v_obj.get_video_height()
        vfps = v_obj.get_video_fps()
        vbitrate = v_obj.get_video_bitrate()
        vcontainer = v_obj.get_video_container()

        # 再解析音频流
        a_obj = audio_info.AudioInfoGetter(video_file)
        acodec = a_obj.get_audio_codec()
        asample_rate = a_obj.get_audio_sample_rate()
        achannel = a_obj.get_audio_channel()
        abitrate = a_obj.get_audio_bitrate()

        # 重命名
        new_video_name = vcodec + "_" + vprofile + "_" + vresoultion + "_" + vfps + \
        "_" + vbitrate + "_" + acodec + "_" + asample_rate + "_" + achannel + "_" + abitrate + "_" + vcontainer + "." + vcontainer
        print(new_video_name)
        new_video_file = os.path.join(output_video_path, new_video_name)

        # 复制到新的路径
        shutil.copyfile(video_file, new_video_file)  # 复制文件
else:
    print("It's a Empty folder, please input the audio files which need to be renamed firstly!!!")
os.system("pause")

本案例练手素材下载

包含:mediainfo.exe(更建议丢到某个环境变量里去),
各种编码格式的视频文件,video_info.py模块,audio_info.py模块,rename_video.py批处理脚本
跳转到自拍教程官网下载
运行效果如下:


小提示: 比如Android手机,Google推出了CDD(Compatibiltiy Definition Document兼容性定义文档)
其第5部分,涉及了很多视频编解码格式的规定,比如H.264的规定:

这就是Android最主要的视频编解码测试需求。


更多更好的原创文章,请访问官方网站:www.zipython.com
自拍教程(自动化测试Python教程,武散人编著)
原文链接:https://www.zipython.com/#/detail?id=ed62bec121074a25a402d9a0bd250271
也可关注“武散人”微信订阅号,随时接受文章推送。


转载:https://blog.csdn.net/qq_45572661/article/details/106861086
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场