In the previous blogs, we discussed the algorithm behind the
- nearest neighbor
- bilinear and
- bicubic interpolation methods using a 2×2 image.
Now, let’s do the same using OpenCV on a real image. First, let’s take an image, either you can load one or can make own image. Loading an image from the device looks like this
1 2 3 4 |
import cv2 import numpy as np img = cv2.imread('C:/New folder/apple.jpg') |
This is a 20×22 apple image that looks like this.
Now, let’s zoom it 10 times using each interpolation method. The OpenCV command for doing this is
1 |
dst = cv2.resize(src, dsize[, fx[, fy[, interpolation]]]]) |
where fx and fy are scale factors along x and y, dsize refers to the output image size and the interpolation flag refers to which method we are going to use. Either you specify (fx, fy) or dsize, OpenCV calculates the other automatically. Let’s see how to use this function
Nearest Neighbor Interpolation
In this we use cv2.INTER_NEAREST as the interpolation flag in the cv2.resize() function as shown below
1 |
near_img = cv2.resize(img,None, fx = 10, fy = 10, interpolation = cv2.INTER_NEAREST) |
Output:
Clearly, this produces a pixelated or blocky image. Also, it doesn’t introduce any new data.
Bilinear Interpolation
In this we use cv2.INTER_LINEAR flag as shown below
1 |
bilinear_img = cv2.resize(img,None, fx = 10, fy = 10, interpolation = cv2.INTER_LINEAR) |
Output:
This produces a smooth image than the nearest neighbor but the results for sharp transitions like edges are not ideal because the results are a weighted average of 2 surrounding pixels.
Bicubic Interpolation
In this we use cv2.INTER_CUBIC flag as shown below
1 |
bicubic_img = cv2.resize(img,None, fx = 10, fy = 10, interpolation = cv2.INTER_CUBIC) |
Output:
Clearly, this produces a sharper image than the above 2 methods. See the white patch on the left side of the apple. This method balances processing time and output quality fairly well.
Next time, when you are resizing an image using any software, wisely use the interpolation method as this can affect your result to a great extent. Hope you enjoy reading.
If you have any doubts/suggestions please feel free to ask and I will do my best to help or improve myself. Good-bye until next time.