<p>我相信这适用于大多数视频(需要ffprobe,它与ffmpeg一起提供)</p>
<pre><code>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
</code></pre>
<p>-旧答案</p>
^{pr2}$