- Practical Computer Vision
- Abhinav Dadhich
- 265字
- 2021-06-30 18:54:49
Box filters
This filter averages out the pixel value as the kernel matrix is denoted as follows:
Applying this filter results in blurring the image. The results are as shown as follows:

In frequency domain analysis of the image, this filter is a low pass filter. The frequency domain analysis is done using Fourier transformation of the image, which is beyond the scope of this introduction. We can see on changing the kernel size, the image gets more and more blurred:

As we increase the size of the kernel, we can observe that resulting image gets more blurred. This is due to averaging out of peak values in the small neighborhood where the kernel is applied. The result for applying kernel of size 20 x 20 can be seen in the following image:

However, if we use a very small filter of size (3, 3) there is negligible effect on the output, due to the fact that the kernel size is quite small compared to the photo size. In most applications, kernel size is heuristically set according to image size:

The complete code to generate box filtered photos is as follows:
def plot_cv_img(input_image, output_image):
"""
Converts an image from BGR to RGB and plots
"""
fig, ax = plt.subplots(nrows=1, ncols=2)
ax[0].imshow(cv2.cvtColor(input_image, cv2.COLOR_BGR2RGB))
ax[0].set_title('Input Image')
ax[0].axis('off')
ax[1].imshow(cv2.cvtColor(output_image, cv2.COLOR_BGR2RGB))
ax[1].set_title('Box Filter (5,5)')
ax[1].axis('off')
plt.show()
def main():
# read an image
img = cv2.imread('../figures/flower.png')
# To try different kernel, change size here.
kernel_size = (5,5)
# opencv has implementation for kernel based box blurring
blur = cv2.blur(img,kernel_size)
# Do plot
plot_cv_img(img, blur)
if __name__ == '__main__':
main()