218

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?

Glains
  • 2,773
  • 3
  • 16
  • 30
Bastian
  • 9,505
  • 6
  • 19
  • 8

5 Answers5

430

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.

Fabian N.
  • 3,807
  • 2
  • 23
  • 46
emem
  • 5,588
  • 1
  • 24
  • 30
  • 1
    does not the resize() function make the picture loosing information about itself ? –  Apr 22 '15 at 16:32
  • 16
    Yes, you can't reduce the size of the image without losing information. – Rafael_Espericueta Jun 18 '15 at 15:33
  • 1
    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. – gizzmole May 12 '17 at 23:26
  • @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? – emem May 15 '17 at 12:06
  • 1
    Thaks for pointing out that resize function take (W * H) whereas cv2 print as (H * W) – Shivam Kotwalia Feb 13 '18 at 08:19
  • how to resize by dpi? – yozawiratama May 23 '18 at 07:28
  • @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. – emem Sep 17 '18 at 14:30
  • does `cv2.resize` automatically uses padding? what is the size of the window that is created using desired output as `(100, 50)`? – seralouk May 28 '19 at 18:13
  • In reply to https://stackoverflow.com/questions/4195453/how-to-resize-an-image-with-opencv2-0-and-python2-6#comment47735184_18767569 , in many cases, information would be lost unless the image is something like a trivial blank image or two squares or some SVG rendering. – Prasad Raghavendra Apr 23 '20 at 16:48
  • @emem i'm really in need of help with this question, can you help me, please? https://stackoverflow.com/questions/61216402/how-to-improve-image-segmentation-using-the-watershed – Carlos Diego Apr 28 '20 at 17:01
81

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()
T.Etti
  • 23
  • 6
João Cartucho
  • 3,688
  • 32
  • 39
9

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

jlengrand
  • 12,152
  • 14
  • 57
  • 87
8

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

nathancy
  • 42,661
  • 14
  • 115
  • 137
7
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)
mathandy
  • 1,892
  • 25
  • 32
  • does `cv2.resize` automatically uses padding? what is the size of the window that is created using `(w, target_height)` arguments? – seralouk May 28 '19 at 18:11