【问题标题】:Set the resolution without changing the aspect ratio在不改变纵横比的情况下设置分辨率
【发布时间】:2018-09-13 10:59:48
【问题描述】:

我想缩放一些图像,并且我想将像素数设置为某个特定的数字。例如,如果有一个带有width=400px height=100 的图像,我可以将其缩放 0.5 以将分辨率设置为 10000px 但是下面的代码可能会产生一些 new_width*new_height 值,例如 9999 或 10001 一些其他宽度和高度值。总像素数必须为 10000。

import os
import cv2

TOTAL_PIXEL_NUMBER = 10000

path = 'path/to/images/folder'
for img in os.listdir(path):
    try:
        img_array = cv2.imread(os.path.join(path,img), cv2.IMREAD_GRAYSCALE)
        height, width = img_array.shape
        aspect_ratio = width/height
        new_height = np.sqrt(TOTAL_PIXEL_NUMBER/aspect_ratio)
        new_width = new_height * aspect_ratio
        new_array = cv2.resize(img_array, (new_width,new_height))
        data.append(new_array)
    except Exceptinon as e:
        print(e)

我想保持比例不变,以免图像失真。但是,保持“完全”不变并不是强制性的。例如,如果原始比率为 0.35,则在调整大小的图像中可以为 0.36 或 0.34,以使总像素数为 10000。但是我如何选择最佳比率以使分辨率恒定?或者如果有一些 opencv 函数可以做到这一点,那就太好了。

【问题讨论】:

  • 您是否意识到面积为 10000 像素的矩形可能只有很少的尺寸和相应的方面(100x100、125x80、200x50、250x40、400x25 等),而不是任意方面?
  • @MBo 是的,我知道。因此我说保持比例完全相同并不是强制性的。它可能会有所改变。但在本例中,分辨率必须为 10000。

标签: python algorithm opencv computer-vision


【解决方案1】:

制作比率列表,包括值(10000/1, 5000/2, etc)

[10000, 2500, 625, 400, 156.25, 100, 39.065, 25, 16, 6.25, 4, 1.5625, 1...0.0001]

或准备使用具有比率、宽度和高度的元组:

[(10000, 10000, 1), (2500, 5000, 2), (625, 2500, 4) ...]

以及此列表第一部分的倒数。

对于给定的 w/h 比率,从列表中找到最接近的值,并使用相应的宽度和高度来制作结果矩形。

例如,您有300x200 图像,比例为1.5。最佳值为1.5625,因此结果矩形为125x80,比例系数为125/30080/200

l = []
for i in range(1, 10001):
    if (10000 % i == 0):
        w = i
        h = 10000 // i
        r = w / h
        l.append((r, w, h))

ww, hh = 1920, 1080
rr = ww / hh
mn = 100000
for i in range(len(l)):
    cmn = max(rr / l[i][0], l[i][0] / rr)
    if (cmn < mn):
        bestidx = i
        mn = cmn

new_width = l[bestidx][1]
new_height = l[bestidx][2]

【讨论】:

    【解决方案2】:

    您可以使用 fx 和 fy 参数进行设置。

    #creating ratio
    rate=1/np.sqrt(height*width/10000)
    new_array = cv2.resize(img_array, (0,0), fx=rate, fy=rate)
    #this will resize the image to 10000 pixels in 3 channels.
    

    【讨论】:

    • 谢谢,但是你不能用它设置特定的分辨率(高*宽)。
    • 不错的举动,但如果 input size = (300, 226) 速率将是 0.3840476863212842 并且输出是 (115, 87) 分辨率是 (115x87) = 10005
    猜你喜欢
    • 2021-04-23
    • 2013-01-19
    • 2017-07-17
    • 1970-01-01
    • 2014-07-28
    • 2012-10-06
    • 1970-01-01
    • 2018-04-22
    • 2011-10-27
    相关资源
    最近更新 更多