Apply Image Filters Using Python

  • Share this:

Code introduction


This function accepts an image path and a filter name, then applies the specified filter to the image and saves the processed image.


Technology Stack : Pillow

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageFilter, ImageOps

def apply_filter_to_image(image_path, filter_name):
    # Load the image
    with Image.open(image_path) as img:
        # Apply the selected filter
        if filter_name == "BLUR":
            filtered_img = img.filter(ImageFilter.BLUR)
        elif filter_name == "CONTOUR":
            filtered_img = img.filter(ImageFilter.CONTOUR)
        elif filter_name == "EMBOSS":
            filtered_img = img.filter(ImageFilter.EMBOSS)
        elif filter_name == "FIND_EDGES":
            filtered_img = img.filter(ImageFilter.FIND_EDGES)
        elif filter_name == "SMOOTH":
            filtered_img = img.filter(ImageFilter.SMOOTH)
        elif filter_name == "SMOOTH_MORE":
            filtered_img = img.filter(ImageFilter.SMOOTH_MORE)
        else:
            raise ValueError("Unsupported filter name")

        # Save the filtered image
        filtered_img.save("filtered_" + image_path)

        return "Filtered image saved as 'filtered_" + image_path + "'"                
              
Tags: