对于我正在处理的项目,我需要创建一个函数,该函数接受高度和宽度的输入,并输出具有16:9比率的最接近的高度和宽度
这是我到目前为止所得到的
def image_to_ratio(h, w):
if width % 16 < height % 9:
h -= (h % 9)
else:
w -= (w% 9)
return h, w
输入: 1920,1200
我的函数的输出: 1920,1197
发布于 2018-12-28 13:48:49
您可以尝试执行以下操作:
from __future__ import division # needed in Python2 only
def image_to_ratio(w, h):
if (w / h) < (16 / 9):
w = (w // 16) * 16
h = (w // 16) * 9
else:
h = (h // 9) * 9
w = (h // 9) * 16
return w, h
>>> image_to_ratio(1920, 1200)
(1920, 1080)
同样的逻辑可以被压缩为:
def image_to_ratio(w, h):
base = w//16 if w/h < 16/9 else h//9
return base * 16, base * 9
发布于 2018-12-28 14:01:23
@schwobaseggl答案的第二短版本:
def image_to_ratio(h, w):
if (w/h) < (16/9):h,w=16*(h//16),9*(h//16)
else:h,w=16*(h//9),9*(h//9)
return h,w
现在:
print(image_to_ratio(1920, 1200))
是:
(1920, 1080)
https://stackoverflow.com/questions/53954028
复制相似问题