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

2024-03-28 17:33:37 发布

您现在位置:Python中文网/ 问答频道 /正文

我想根据一个百分比调整图像的大小,并使其尽可能接近原始图像,同时尽量减少噪声和失真。大小可以上下调整,因为我可以缩放到原始图像大小的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)

Tags: 图像maindefwidthcv2噪声例子final
2条回答

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

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

fx取决于宽度

fy取决于高度

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

示例:

^{pr2}$

注:

0.5表示要缩放图像的50%

我想你是想调整和保持纵横比。这里有一个函数可以根据百分比来放大或缩小图像

原始图像示例

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)

相关问题 更多 >