在不更改宽高比的情况下设置分辨率

问题描述 投票:0回答:2

我想缩放一些图像,我想将像素数设置为某些特定数字。例如,如果有一个带有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函数可以做到这一点,那就太好了。

python algorithm opencv computer-vision
2个回答
2
投票

列出比率列表,包括值(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]

1
投票

你可以使用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.
© www.soinside.com 2019 - 2024. All rights reserved.