Image resizing

From Lofaro Lab Wiki
Jump to: navigation, search

Now we are going to explore a very important method needed for image processing. Resizing is the techniques through which we can resize an image according to our need. We can resize an image by its height or width. The function for resizing our image is cv2.resize. we need to keep in mind about the aspect ratio of the image before we use the resize function. This concept can be better explained through some codes


import cv2
import numpy as np
image = cv2.imread('hubo.jpg',0)
cv2.imshow("Original", image)
r = 200.0 / image.shape[1]
dim = (200, int(image.shape[0] * r))
# Resizing the image by his width
resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Resized (Width)", resized)
r = 50.0 / image.shape[0]
dim = (int(image.shape[1] * r), 50)
# Resizing the image by its height
resized = cv2.resize(image, dim, interpolation = cv2.INTER_AREA)
cv2.imshow("Resized (Height)", resized)
cv2.waitKey(0)
cv2.destroyAllWindows()


The first few lines of codes imported our packages, loaded the image and showed it so that we can compare it with resized images.

When we resize an image we need to be careful about the aspect ratio, otherwise it will not look correct. We want to resize out image width to 200 pixel. So we need to convert our height according to that so that aspect ratio of the image remains same.

First we find out the aspect ratio of the image by dividing 200 by the image width (obtained by using image.shape[1] function) and put the ratio in r. This r will help us to convert the height according to the width. Then we defined our transformation matrix dim.

The actual resize takes place in the third line where we used the cv2.resize function. The function takes three arguments. First one is the image we want to resize, second one is the dimension of the image in which we want to resize. The last one is the interpolation method, which works behind the scene and determine how the image is resized. cv2.INTER_AREA is generally used for resizing. There are other methods too, you can see in the opencv library to get an idea how the methods differ from each other.

We did the height resizing using the same techniques in the later code. For that we resized the height to 100 pixels and changed the width according to that to keep the aspect ratio same. See the images below, which will help you to better understand the resizing things.


Resize.jpg