【问题标题】:accurate image aspect ratio in pythonpython中准确的图像纵横比
【发布时间】:2014-07-09 22:16:44
【问题描述】:

我有以下代码来获取图像的纵横比

img0 = color.rgb2gray(io.imread("C:\\work\\TRAIN\\SET1\\bus.jpg"))
img0 = resize(img0, (40, 116))
ar = 1.0 * (img0.shape[1]/img0.shape[0])
print "aspect ratio: " 
print ar

输出为2.0。但事实并非如此。 对于宽度为 116、高度为 40 的图像,纵横比应为 116/40 = 2.9

我的计算哪里出错了?

【问题讨论】:

  • 116/40 将在 Python 2.7 上执行 floor division(向下舍入到下一个整数)。使用 float(img0.shape[1]) / img0.shape[0] 之类的东西来获得浮点除法。
  • 成功了!如果您将其添加为答案,我会选择它。

标签: python image-processing floating-accuracy aspect-ratio


【解决方案1】:

116/40 将在 Python 2.x 上执行 floor division(向下舍入到下一个整数)。

使用 float(img0.shape[1]) / img0.shape[0] 之类的东西来获得浮点除法(这是 Python 3.x 上 / 运算符的默认行为)。

最好的选择可能是使用from __future__ import division(作为脚本中的第一个导入)——这将确保你的脚本在 Python 2.x 和 Python 3 上都使用浮点除法.x.

【讨论】:

    【解决方案2】:

    你的问题是 img0.shape[1] 和 img0.shape[0] 都是整数。您已执行整数除法,然后将其转换为浮点数。你可以试试:

    float(img0.shape[1]) / img0.shape[0]
    

    1.0 * img0.shape[1] / img0.shape[0]
    

    或者,我推荐的方法是在此导入的文件中添加为第一行代码

    from __future__ import division
    

    这将使“/”总是执行浮点计算,以避免这种情况。如果要专门使用整数除法,请使用“//”,如 10 // 3

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2019-04-02
      • 1970-01-01
      • 2011-07-16
      • 2020-12-13
      • 2011-09-24
      • 1970-01-01
      相关资源
      最近更新 更多