You can download this code by clicking the button below.
This code is now available for download.
This function accepts an input image path, an output image path, and a filter type, then applies the specified filter to the image and saves the result to the output path.
Technology Stack : Pillow
Code Type : Image processing
Code Difficulty : Intermediate
from PIL import Image, ImageFilter, ImageOps
def apply_filter_to_image(input_path, output_path, filter_type):
"""
Apply a random filter to an image and save the result.
Args:
input_path (str): The path to the input image.
output_path (str): The path where the filtered image will be saved.
filter_type (str): The type of filter to apply from ImageFilter.
"""
# Load the image
image = Image.open(input_path)
# Apply the selected filter
if filter_type == "BLUR":
filtered_image = image.filter(ImageFilter.BLUR)
elif filter_type == "CONTOUR":
filtered_image = image.filter(ImageFilter.CONTOUR)
elif filter_type == "EMBOSS":
filtered_image = image.filter(ImageFilter.EMBOSS)
elif filter_type == "FIND_EDGES":
filtered_image = image.filter(ImageFilter.FIND_EDGES)
else:
raise ValueError("Unsupported filter type")
# Save the filtered image
filtered_image.save(output_path)