Smoothing by averaging with the box blur kernel

The following code block shows how to use the PIL ImageFilter.Kernel() function and box blur kernels (mean filters) of a size of 3 x 3 and 5 x 5 to smooth a noisy image:

im = Image.open('../images/mandrill_spnoise_0.1.jpg')pylab.figure(figsize=(20,7))pylab.subplot(1,3,1), pylab.imshow(im), pylab.title('Original Image', size=30), pylab.axis('off')for n in [3,5]:    box_blur_kernel = np.reshape(np.ones(n*n),(n,n)) / (n*n)    im1 = im.filter(ImageFilter.Kernel((n,n), box_blur_kernel.flatten()))    pylab.subplot(1,3,(2 if n==3 else 3))    plot_image(im1, 'Blurred with kernel size = ' + str(n) + 'x' + str(n))pylab.suptitle('PIL Mean Filter (Box Blur) with different Kernel size',size=30)pylab.show()

The following ...

Get Hands-On Image Processing with Python now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.