使用OpenCV Python调整图像尺寸的最佳方法

5
我希望基于百分比调整图像大小,并使其尽可能接近原始图像以保持最小的噪点和失真。调整大小可以是增大或缩小,例如我可以将图像缩放到原始图像的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个回答

3

您可以使用以下 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%


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)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接