How to resize an image with OpenCV2.0 and Python2.6

568,885

Solution 1

If you wish to use CV2, you need to use the resize function.

For example, this will resize both axes by half:

small = cv2.resize(image, (0,0), fx=0.5, fy=0.5) 

and this will resize the image to have 100 cols (width) and 50 rows (height):

resized_image = cv2.resize(image, (100, 50)) 

Another option is to use scipy module, by using:

small = scipy.misc.imresize(image, 0.5)

There are obviously more options you can read in the documentation of those functions (cv2.resize, scipy.misc.imresize).


Update:
According to the SciPy documentation:

imresize is deprecated in SciPy 1.0.0, and will be removed in 1.2.0.
Use skimage.transform.resize instead.

Note that if you're looking to resize by a factor, you may actually want skimage.transform.rescale.

Solution 2

Example doubling the image size

There are two ways to resize an image. The new size can be specified:

  1. Manually;

    height, width = src.shape[:2]

    dst = cv2.resize(src, (2*width, 2*height), interpolation = cv2.INTER_CUBIC)

  2. By a scaling factor.

    dst = cv2.resize(src, None, fx = 2, fy = 2, interpolation = cv2.INTER_CUBIC), where fx is the scaling factor along the horizontal axis and fy along the vertical axis.

To shrink an image, it will generally look best with INTER_AREA interpolation, whereas to enlarge an image, it will generally look best with INTER_CUBIC (slow) or INTER_LINEAR (faster but still looks OK).

Example shrink image to fit a max height/width (keeping aspect ratio)

import cv2

img = cv2.imread('YOUR_PATH_TO_IMG')

height, width = img.shape[:2]
max_height = 300
max_width = 300

# only shrink if img is bigger than required
if max_height < height or max_width < width:
    # get scaling factor
    scaling_factor = max_height / float(height)
    if max_width/float(width) < scaling_factor:
        scaling_factor = max_width / float(width)
    # resize image
    img = cv2.resize(img, None, fx=scaling_factor, fy=scaling_factor, interpolation=cv2.INTER_AREA)

cv2.imshow("Shrinked image", img)
key = cv2.waitKey()

Using your code with cv2

import cv2 as cv

im = cv.imread(path)

height, width = im.shape[:2]

thumbnail = cv.resize(im, (round(width / 10), round(height / 10)), interpolation=cv.INTER_AREA)

cv.imshow('exampleshq', thumbnail)
cv.waitKey(0)
cv.destroyAllWindows()

Solution 3

You could use the GetSize function to get those information, cv.GetSize(im) would return a tuple with the width and height of the image. You can also use im.depth and img.nChan to get some more information.

And to resize an image, I would use a slightly different process, with another image instead of a matrix. It is better to try to work with the same type of data:

size = cv.GetSize(im)
thumbnail = cv.CreateImage( ( size[0] / 10, size[1] / 10), im.depth, im.nChannels)
cv.Resize(im, thumbnail)

Hope this helps ;)

Julien

Solution 4

Here's a function to upscale or downscale an image by desired width or height while maintaining aspect ratio

# 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)

Usage

import cv2

image = cv2.imread('1.png')
cv2.imshow('width_100', maintain_aspect_ratio_resize(image, width=100))
cv2.imshow('width_300', maintain_aspect_ratio_resize(image, width=300))
cv2.waitKey()

Using this example image

enter image description here

Simply downscale to width=100 (left) or upscale to width=300 (right)

enter image description here enter image description here

Solution 5

def rescale_by_height(image, target_height, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_height` (preserving aspect ratio)."""
    w = int(round(target_height * image.shape[1] / image.shape[0]))
    return cv2.resize(image, (w, target_height), interpolation=method)

def rescale_by_width(image, target_width, method=cv2.INTER_LANCZOS4):
    """Rescale `image` to `target_width` (preserving aspect ratio)."""
    h = int(round(target_width * image.shape[0] / image.shape[1]))
    return cv2.resize(image, (target_width, h), interpolation=method)
Share:
568,885

Related videos on Youtube

Bastian
Author by

Bastian

Updated on September 17, 2020

Comments

  • Bastian
    Bastian almost 4 years

    I want to use OpenCV2.0 and Python2.6 to show resized images. I used and adopted this example but unfortunately, this code is for OpenCV2.1 and does not seem to be working on 2.0. Here my code:

    import os, glob
    import cv
    
    ulpath = "exampleshq/"
    
    for infile in glob.glob( os.path.join(ulpath, "*.jpg") ):
        im = cv.LoadImage(infile)
        thumbnail = cv.CreateMat(im.rows/10, im.cols/10, cv.CV_8UC3)
        cv.Resize(im, thumbnail)
        cv.NamedWindow(infile)
        cv.ShowImage(infile, thumbnail)
        cv.WaitKey(0)
        cv.DestroyWindow(name)
    

    Since I cannot use

    cv.LoadImageM
    

    I used

    cv.LoadImage
    

    instead, which was no problem in other applications. Nevertheless, cv.iplimage has no attribute rows, cols or size. Can anyone give me a hint, how to solve this problem?

    • Michał
      Michał about 7 years
      If any of answers was correct, please mark it as it will help others.
  • Admin
    Admin about 9 years
    does not the resize() function make the picture loosing information about itself ?
  • Rafael_Espericueta
    Rafael_Espericueta about 9 years
    Yes, you can't reduce the size of the image without losing information.
  • gizzmole
    gizzmole about 7 years
    The opencv (0.05ms per image) implementation seems to be much faster than the scipy (0.33ms image) implementation. I resized 210x160x1 to 84x84x1 images with bilinear interpolation.
  • emem
    emem about 7 years
    @gizzmole Interesting insight. I did not test the efficiency of the implementations, nor compared the results - so the end result may also differ slightly. Did you test to see the resized images match bitwise?
  • Shivam Kotwalia
    Shivam Kotwalia over 6 years
    Thaks for pointing out that resize function take (W * H) whereas cv2 print as (H * W)
  • yozawiratama
    yozawiratama about 6 years
    how to resize by dpi?
  • emem
    emem almost 6 years
    @yozawiratama I don't think I understand your question, or why it is related to the original question - dpi is defined by the size of the image as it is displayed (or printed) in the real world, and by the number of information dots (usually pixels) it has.
  • BenP
    BenP over 5 years
    your solution using the scaling factors returns an error on cv2.resize() saying 'src is not a numpy array, neither a scalar.' please advise?
  • João Cartucho
    João Cartucho over 5 years
    did you do: src = cv2.imread('YOUR_PATH_TO_IMG') and edited the 'YOUR_PATH_TO_IMG' to the path of your own image?
  • seralouk
    seralouk about 5 years
    does cv2.resize automatically uses padding? what is the size of the window that is created using (w, target_height) arguments?
  • seralouk
    seralouk about 5 years
    does cv2.resize automatically uses padding? what is the size of the window that is created using desired output as (100, 50)?
  • seralouk
    seralouk about 5 years
    does cv2.resize automatically uses padding? what is the size of the window that is created using desired output size as (width/10, height/10)?
  • João Cartucho
    João Cartucho about 5 years
    @makaros you get an image that is 10x smaller both in width and height
  • seralouk
    seralouk about 5 years
    @JoãoCartucho yes I understand this. But when nearest_neighbors is used then a window should applied behind the scenes. This is what I am asking..
  • João Cartucho
    João Cartucho about 5 years
    what nearest_neighbors?
  • Prasad Raghavendra
    Prasad Raghavendra about 4 years
    In reply to stackoverflow.com/questions/4195453/… , in many cases, information would be lost unless the image is something like a trivial blank image or two squares or some SVG rendering.
  • Carlos Diego
    Carlos Diego about 4 years
    @emem i'm really in need of help with this question, can you help me, please? stackoverflow.com/questions/61216402/…