Random Image Filter and Grayscale Conversion

  • Share this:

Code introduction


This function loads an image from a specified path, applies a random image filter from the Pillow library's ImageFilter module, converts the image to grayscale, and saves the processed image to the output path.


Technology Stack : Pillow library, ImageFilter module, ImageOps module

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageFilter, ImageOps
import random

def random_filter_image(image_path, output_path):
    # Load the image
    with Image.open(image_path) as img:
        # Randomly choose a filter from the available ImageFilter module
        filters = [ImageFilter.BLUR, ImageFilter.CONTOUR, ImageFilter.EMBOSS, ImageFilter.FIND_EDGES, ImageFilter.GAUSSIAN_BLUR, ImageFilter.SHARPEN]
        filter = random.choice(filters)
        
        # Apply the filter to the image
        filtered_img = img.filter(filter)
        
        # Convert the image to grayscale
        grayscale_img = ImageOps.grayscale(filtered_img)
        
        # Save the processed image
        grayscale_img.save(output_path)