Kernel() method in Python PIL

In this tutorial, we are learning kernel() method of PIL in Python.

  •  Python Imaging Library(PIL) is a free library in Python programming language which is used for image editing.
  • ImageFilter module provides various filters to apply to an image.
  • PIL.ImageFiIter.Kernel is a class that creates a convolution kernel.

 

How To Apply Kernal method of PIL in Python

Since ImageFilter module contains the kernel( )method, so we will import the module from PIL.

#for opening the image we are using
from PIL import Image, ImageFilter

im1 = Image.open("img1.jpeg")
im1.show()

OUTPUT:

Kernel() method in Python PIL

 

So, now through some examples, we are gonna see how this kernel method works.

First Example :

# Importing Image and ImageFilter module from PIL package  
from PIL import Image, ImageFilter  

im1 = Image.open("img1.jpeg")  
  
# applying the Kernel filter 
im2 = im1.filter(ImageFilter.Kernel((3, 3), 
      (-1, -1, -1, -1, 9, -1, -1, -1, -1), 1, 0)) 
  
im2 = im2.show()

Output:

Kernel() method in PIL

 

Second Example:

# Importing Image and ImageFilter module from PIL package  
from PIL import Image, ImageFilter  
    
im1 = Image.open("img1.jpeg")  
  
# applying the Kernel filter 
im2 = im1.filter(ImageFilter.Kernel((3, 3), 
          (-1, -1, -1, -1, 11, -2, -2, -2, -2), 1, 0)) 
  
im2 = im2.show()

Output:

PIL

 

Third Example:

# Importing Image and ImageFilter module from PIL package  
from PIL import Image, ImageFilter  
  
im1 = Image.open("img1.jpeg")  
  
# applying the Kernel filter 
im2 = im1.filter(ImageFilter.Kernel((3, 3), 
          (-1, 0, 0, 0,1, 0, 0, 0, 1), 5, 0)) 
  
im2 = im2.show()

Output:

kernel

 

Finally, we have seen some examples above showing the use of the kernel( ) method. So, I hope this helps you!

Leave a Reply

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