Python:如何从视频中获取显示纵横比?

2024-04-28 22:08:01 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个视频,其中ffmpeg告诉我存储纵横比(SAR)为4:3,但显示纵横比DAR为16:9。分辨率为1440x1080。 有没有机会在Python OpenCV或其他包中找到16:9的DAR?在


Tags: 视频分辨率opencvffmpeg机会sardar
2条回答

存储纵横比是以像素为单位的图像宽高比,可以很容易地从视频文件中计算出来。在

显示纵横比是在屏幕上显示时图像的宽高比(以厘米或英寸为单位),根据像素纵横比和存储纵横比的组合计算。在

SAR×PAR= DAR。在

例如,一个640×480的VGA图像的SAR为640/480=4:3,如果在4:3显示(DAR=4:3)显示为正方形像素,则为1:1的PAR。相比之下,720×576d-1pal图像的SAR为720/576=5:4,但显示在4:3显示器上(DAR=4:3)。在

Source

因此,使用OpenCV可以得到SAR(像素尺寸的比率),但我怀疑您能否从中获得一个常量显示纵横比(因为它与显示相关)。在

你可以做的是当displaying图像时,你可以得到window property,它有一个标志WND_PROP_ASPECT_RATIO。在

我相信这适用于大多数视频(需要ffprobe,它与ffmpeg一起提供)

import subprocess
import json
def get_aspect_ratios(video_file):
    cmd = 'ffprobe -i "{}" -v quiet -print_format json -show_format -show_streams'.format(video_file)
#     jsonstr = subprocess.getoutput(cmd)
    jsonstr = subprocess.check_output(cmd, shell=True, encoding='utf-8')
    r = json.loads(jsonstr)
    # look for "codec_type": "video". take the 1st one if there are mulitple
    video_stream_info = [x for x in r['streams'] if x['codec_type']=='video'][0]
    if 'display_aspect_ratio' in video_stream_info and video_stream_info['display_aspect_ratio']!="0:1":
        a,b = video_stream_info['display_aspect_ratio'].split(':')
        dar = int(a)/int(b)
    else:
        # some video do not have the info of 'display_aspect_ratio'
        w,h = video_stream_info['width'], video_stream_info['height']
        dar = int(w)/int(h)
        ## not sure if we should use this
        #cw,ch = video_stream_info['coded_width'], video_stream_info['coded_height']
        #sar = int(cw)/int(ch)
    if 'sample_aspect_ratio' in video_stream_info and video_stream_info['sample_aspect_ratio']!="0:1":
        # some video do not have the info of 'sample_aspect_ratio'
        a,b = video_stream_info['sample_aspect_ratio'].split(':')
        sar = int(a)/int(b)
    else:
        sar = dar
    par = dar/sar
    return dar, sar, par

-旧答案

^{pr2}$

相关问题 更多 >