使用OpenCV Python调整图像大小的最佳方法

时间:2019-07-02 17:56:48

标签: python image opencv python-imaging-library image-resizing

我想根据百分比调整图像大小,并使其与原始图像保持接近,从而将噪声和失真降至最低。调整大小可能会变大或变小,因为我可以将大小调整为原始图像的5%或500%(或任何其他值作为示例)

这是我尝试过的方法,我需要在调整大小后的图像中进行绝对最小的更改,因为与其他图像相比,我将使用它

def resizing(main,percentage):
    main = cv2.imread(main)
    height = main.shape[ 0] * percentage
    width = crop.shape[ 1] * percentage
    dim = (width,height)
    final_im = cv2.resize(main, dim, interpolation = cv2.INTER_AREA)
    cv2.imwrite("C:\\Users\\me\\nature.jpg", final_im)

2 个答案:

答案 0 :(得分:1)

我认为您正在尝试调整尺寸和保持宽高比。这是一个根据百分比对图像进行放大或缩小的功能

原始图片示例

enter image description here

将图片大小调整为0.5(50%)

enter image description here

将图片调整为1.3(130%)

enter image description here

import cv2

# Resizes a image and maintains aspect ratio
def maintain_aspect_ratio_resize(image, width=None, height=None, inter=cv2.INTER_AREA):
    # Grab the image size and initialize dimensions
    dim = None
    (h, w) = image.shape[:2]

    # Return original image if no need to resize
    if width is None and height is None:
        return image

    # We are resizing height if width is none
    if width is None:
        # Calculate the ratio of the height and construct the dimensions
        r = height / float(h)
        dim = (int(w * r), height)
    # We are resizing width if height is none
    else:
        # Calculate the ratio of the width and construct the dimensions
        r = width / float(w)
        dim = (width, int(h * r))

    # Return the resized image
    return cv2.resize(image, dim, interpolation=inter)

if __name__ == '__main__':
    image = cv2.imread('1.png')
    cv2.imshow('image', image)
    resize_ratio = 1.2
    resized = maintain_aspect_ratio_resize(image, width=int(image.shape[1] * resize_ratio))
    cv2.imshow('resized', resized)
    cv2.imwrite('resized.png', resized)
    cv2.waitKey(0)

答案 1 :(得分:0)

您可以使用cv2.resize的以下语法:

  cv2.resize(image,None,fx=int or float,fy=int or float)

fx取决于宽度

fy取决于高度

您可以输入第二个参数None(0,0)

示例:

  img = cv2.resize(oriimg,None,fx=0.5,fy=0.5)

注意:

0.5表示要缩放图像的50%