在 Python 中估计失真纵横比图像上最接近的逻辑纵横比

Estimate nearest logical aspect ratio on distorted aspect images in 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。

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

啊,解决了!感谢 this 的回答让我了解到 roundndigits 参数也接受负值。

所以我可以简单地做:

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)

现在它完美运行:)