首页 > 解决方案 > 在 Python 中估计扭曲的纵横比图像上最接近的逻辑纵横比

问题描述

好的,所以我编写了一个程序,它从在线资源加载随机图像,然后将它们一一加载到我在 Arch Linux 上的 Gnome 桌面。

现在,我想检查它们的纵横比,只显示与我的屏幕纵横比相同的图像。

我有以下函数来确定纵横比:

def highest_common_factor(width,height):
    """Support function to calculate the aspect ratio of a (width:height) input.
    Stolen fron online, sometimes also reffered to as the GCD value"""
    if(height==0): 
        return width 
    else: 
        return highest_common_factor(height,width%height) 

def get_current_resolution():
    """Get current screenresolution"""

    screen_resolutions = subprocess.Popen(["xrandr"], stdout=subprocess.PIPE)
    get_current_resolution = subprocess.Popen(["grep", '*'], stdin=screen_resolutions.stdout, stdout=subprocess.PIPE)
    current_resolution = get_current_resolution.communicate()[0].decode().split()[0]
    current_width = int(current_resolution.split("x")[0])
    current_height = int(current_resolution.split("x")[1])
    return current_width, current_height

def get_aspect_ratio(resolution):
    """Determine current aspect ratio"""

    width = resolution[0]
    height = resolution[1]
    gcd = highest_common_factor(width,height)
    aspect_width = width/gcd
    aspect_height = height/gcd
    return round(aspect_width), round(aspect_height)

问题是这个

如果图像具有完美的尺寸,例如1200:900,这些函数可以完美地工作,并且我将它们输入到get_aspect_ratio()函数中,我会得到完美的结果4:3。但是,如果图像不太完美并且分辨率为1200:901,我也会得到1200:901的纵横比。

从数学上讲这是正确的,但人类很容易看出这实际上是 4:3。

我一直在考虑如何解决这个问题,但到目前为止还没有找到可行的解决方案。欢迎任何想法或见解!

标签: pythonpython-3.ximageimage-processingaspect-ratio

解决方案


啊,解决了!感谢这个答案,它让我知道ndigits参数round也接受负值。

所以我可以简单地做:

def get_aspect_ratio(resolution):
    """Determine current aspect ratio"""

    width = resolution[0]
    height = resolution[1]
    gcd = highest_common_factor(round(width,-1),round(height,-1))
    aspect_width = width/gcd
    aspect_height = height/gcd
    return round(aspect_width), round(aspect_height)

现在它完美地工作了:)


推荐阅读