Resize image in Python

As the title says, resizing images in Python sounds interesting right? We have already been fascinated by the title itself, it will be fun implementing it.

We are going to learn about various functions that resize the dimension and modify the quality of the image and many more.

For this, we need to have basic knowledge about-

  1. Pillow
  2. cv2

About Pillow and CV2

Pillow is a module under PIL(Python Image Library) which is helpful for the various image processing techniques. We will implement various functions under this library to accomplish our task.

CV2 is again a library that solves computer-vision problems and is also proven to be helpful in the modification of images.

Resizing image in CV2 – Python

We will now try to resize an image in Python. We will implement pillow to import the image and to resize it, we will use cv2. We will open the image and then try to resize it using resize() function.

resize() function works as image.resize(height,width)

We will display the size of the original and resize it and check for its output.

Implementation-

from PIL import Image
image = Image.open(r"Image Location")
print(image.size)
resize=image.resize((600,600))
print(resize.size)

Output-

(537, 322)
(600, 600)

As you can see, the flow of the program is to first import the Image module from the PIL library and then open the image, thereafter printing the size of the image which results out to be (537,322). Then we will use resize with the height of 600 and width of 600 and print its size.

Modifying the quality of an image using cv2 (OpenCV) in Python

Whenever we need to change the quality or we can say we need to blur the image, we can do this easily by cv2 and see the image as output.

Snippet part-

import cv2
image=cv2.imread(r'Image Location')
blur=cv2.blur(image,(15,15))
cv2.imshow('',blur)
cv2.waitKey(0)

Output-

The image will be displayed as an output. The image will be blurred.

Here’s my output image-

Resize image in Python

The flow of the program first imports cv2 and then reads the image from its location in read mode. After that blur() function takes the image you can alter the value in place of 15. We will then show the image.

This is how we can easily resize and blur an image in Python. I hope you find this tutorial helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *