Getting video dimension / resolution / width x height from ffmpeg

前端 未结 8 1576
粉色の甜心
粉色の甜心 2020-11-27 05:33

How would I get the height and width of a video from ffmpeg\'s information output. For example, with the following output:

$ ffmpeg -i video.mp4         


        
8条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 05:46

    In this blog post theres a rough solution in python:

    import subprocess, re
    pattern = re.compile(r'Stream.*Video.*([0-9]{3,})x([0-9]{3,})')
    
    def get_size(pathtovideo):
        p = subprocess.Popen(['ffmpeg', '-i', pathtovideo],
                             stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE)
        stdout, stderr = p.communicate()
        match = pattern.search(stderr)
        if match:
            x, y = map(int, match.groups()[0:2])
        else:
            x = y = 0
        return x, y
    

    This however assumes it's 3 digits x 3 digits (i.e. 854x480), you'll need to loop through the possible dimension lengths, such as (1280x720):

    possible_patterns = [re.compile(r'Stream.*Video.*([0-9]{4,})x([0-9]{4,})'), \
                re.compile(r'Stream.*Video.*([0-9]{4,})x([0-9]{3,})'), \
    re.compile(r'Stream.*Video.*([0-9]{3,})x([0-9]{3,})')]
    

    and check if match returns None on each step:

    for pattern in possible_patterns:
        match = pattern.search(stderr)
        if match!=None:
            x, y = map(int, match.groups()[0:2])
            break
    
    if match == None:
        print "COULD NOT GET VIDEO DIMENSIONS"
        x = y = 0
    
    return '%sx%s' % (x, y)
    

    Could be prettier, but works.

提交回复
热议问题