python - 在 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。
我一直在考虑如何解决这个问题,但到目前为止还没有找到可行的解决方案。欢迎任何想法或见解!
解决方案
啊,解决了!感谢这个答案,它让我知道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)
现在它完美地工作了:)
推荐阅读
- android - Android-lock NxN矩阵可能组合的通用公式
- tensorflow - NotImplementedError:TPU 不支持类型为 AssignVariableOp (AssignVariableOp) 的操作进行推理
- javascript - div 元素只出现几秒钟
- bigcommerce - 如何使用模板框架在 Cornerstone 主题中创建新模板
- c# - Excel 表格和用户界面(Windows 应用程序)
- apache-spark - 使用 pyspark 的 Spark RDD 窗口化
- mysql - 如何借助 group by 子句在一个查询中获取两个不同表的不同行数
- python - 解析器txt文件python
- python - 从国民身份证中提取文本信息
- gcc - 虚假警告 gcc -Wuninitialized