You can download this code by clicking the button below.
This code is now available for download.
This function opens an image at a specified path and applies the corresponding filter based on the type of filter passed in. It then 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_type):
# Open the image
with Image.open(image_path) as img:
# Apply the selected 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)
elif filter_type == 'FIND_EDGES':
filtered_img = img.filter(ImageFilter.FIND_EDGES)
else:
raise ValueError("Unsupported filter type")
# Save the filtered image
filtered_img.save('filtered_' + image_path)