In this article, we have explained the process to resize an image in Python using OpenCV library.
Table of contents:
- Basics of Resize Image
- Code to resize Image in Python using OpenCV
Basics of Resize Image
A image has 3 dimensions:
The channels for RGB images is set to 3. If we resize an image, the number of channels remain the same.
While resizing, the other two dimensions namely height and width are changed. We can reduce or increase the size.
Code to resize Image in Python using OpenCV
- Load relevant libraries
Only OpenCV library is used to resize the image. If you need to do some extra operations on the image, you can use Numpy.
import numpy as np import cv2
- Get the Image data
We can create an Numpy array with 3 dimensions that will work as an image.
image = np.random.rand(400, 400, 3) image = image.astype(np.uint8)
Alternatively, you can load a real image using OpenCV.
image = cv2.imread("image.jpeg", mode='RGB')
- Resize the image data
new_height = 500 new_width = 500 image = cv2.resize(image, dsize=(new_height, new_width), interpolation=cv2.INTER_CUBIC)
Interpolation is the way the extra pixels in the new image is calculated. If the original image is smaller, then a larger rescaled image has extra pixels which is not exactly the same as a nearby pixels.
The value of the extra pixel depends on the technique used. The different interpolation techniques used in OpenCV are:
- INTER_NEAREST: nearest neighbor interpolation technique
- INTER_LINEAR: bilinear interpolation (default)
- INTER_AREA: resampling using pixel area relation
- INTER_CUBIC: bicubic interpolation over 4 x 4 pixel neighborhood
- INTER_LANCZOS4: Lanczos interpolation over 8 x 8 pixel neighborhood
The best interpolation method will depend on the image. One needs to try by experimentation.
Complete Python code to resize an image:
import cv2 image = cv2.imread("image.jpeg", mode='RGB') new_height = 500 new_width = 500 image = cv2.resize(image, dsize=(new_height, new_width), interpolation=cv2.INTER_CUBIC)
With this article at OpenGenus, you must have the complete idea of how to resize an image in Python using OpenCV.