James
James

Reputation: 77

Optimal way to resize an image with OpenCV Python

I want to resize an image based on a percentage and keep it as close to the original with minimal noise and distortion. The resize could be up or down as in I could scale to 5% the size of the original image or 500% (or any other value these are given as example)

This is what i tried and i'd need absolute minimal changes in the resized image since i'll be using it in comparison with other images

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)

Upvotes: 5

Views: 12483

Answers (2)

nathancy
nathancy

Reputation: 46600

I think you're trying to resize and maintain aspect ratio. Here's a function to upscale or downscale an image based on percentage

Original image example

enter image description here

Resized image to 0.5 (50%)

enter image description here

Resized image to 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)

Upvotes: 1

aseem bhartiya
aseem bhartiya

Reputation: 104

You can use this syntax of cv2.resize:

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

fx depends on width

fy depends on height

You can put the second argument None or (0,0)

Example:

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

Note:

0.5 means 50% of image to be scaling

Upvotes: 4

Related Questions