Image Filter and Flip Application

  • Share this:

Code introduction


This function accepts an image path, a filter type, and a flip method, then applies the specified filter and flip effect to the image, and finally saves the processed image as 'output.png'.


Technology Stack : Pillow library's Image, ImageFilter, ImageOps modules

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageFilter, ImageOps

def apply_filter_and_flip(image_path, filter_type, flip_method):
    # Open the image file
    with Image.open(image_path) as img:
        # Apply the specified filter
        if filter_type == 'BLUR':
            filtered_img = img.filter(ImageFilter.BLUR)
        elif filter_type == 'CONTOUR':
            filtered_img = img.filter(ImageFilter.CONTOUR)
        elif filter_type == 'EMBOSS':
            filtered_img = img.filter(ImageFilter.EMBOSS)
        else:
            raise ValueError("Unsupported filter type. Choose from 'BLUR', 'CONTOUR', 'EMBOSS'")
        
        # Flip the image based on the specified method
        if flip_method == 'VERTICAL':
            flipped_img = ImageOps.mirror(filtered_img)
        elif flip_method == 'HORIZONTAL':
            flipped_img = ImageOps.flip(filtered_img)
        else:
            raise ValueError("Unsupported flip method. Choose from 'VERTICAL', 'HORIZONTAL'")
        
        # Save the final image
        flipped_img.save("output.png")