Image Filter App Project (code) in Python

← Back to Projects

Image Filter App in Python

About the project: This is a project for a Image Filter App using Python. This project will use the Pillow library (PIL) to perform various image manipulations like converting to grayscale, applying a blur, and enhancing sharpness.

This is a great project for learning about image processing and file handling in Python. The code is self-contained in a single file and provides a simple command-line interface for the user to select an image and apply a filter.

Instructions

  1. Install Pillow: This project requires the Pillow library. You can install it using pip:
    
      pip install Pillow
      
  2. Save the Code: Save the code above as a file named image_filter_app.py.
  3. Place an Image: Make sure you have an image file (e.g., my_photo.jpg) in the same directory as your Python script.
  4. Run the App: Open your terminal or command prompt, navigate to the directory where you saved the file, and run it:
    
      python image_filter_app.py
      
  5. Follow the Prompts: The application will guide you to enter the image file name and the filter you want to apply. It will save the new, filtered image in the same directory.

Project Level: Intermediate

You can directly copy the below snippet code with the help of green copy button, paste it and run it in any Python editor you have.

Steps: Follow these steps

Step 1: Copy below code using green 'copy' button.

Step 2: Paste the code on your chosen editor.

Step 3: Save the code with filename and .py extention.

Step 4: Run (Press F5 if using python IDLE).



# image_filter_app.py

from PIL import Image, ImageFilter, ImageEnhance
import os
import sys

def apply_filter(image_path, filter_type):
    """
    Loads an image, applies a specified filter, and saves the new image.

    Args:
        image_path (str): The path to the input image file.
        filter_type (str): The type of filter to apply ('grayscale', 'blur', 'sharpen').

    Returns:
        str or None: The path of the saved output image, or None if an error occurs.
    """
    try:
        # Open the image file
        with Image.open(image_path) as img:
            print(f"Applying '{filter_type}' filter to '{os.path.basename(image_path)}'...")

            # Apply the selected filter
            if filter_type == 'grayscale':
                filtered_img = img.convert("L")
            elif filter_type == 'blur':
                filtered_img = img.filter(ImageFilter.BLUR)
            elif filter_type == 'sharpen':
                # Use ImageEnhance for a more customizable effect
                enhancer = ImageEnhance.Sharpness(img)
                filtered_img = enhancer.enhance(2.0) # 2.0 is a good starting point for sharpness
            else:
                print(f"Error: Unknown filter type '{filter_type}'.")
                return None

            # Create a new file name for the filtered image
            file_name, file_extension = os.path.splitext(os.path.basename(image_path))
            output_path = f"{file_name}_{filter_type}{file_extension}"

            # Save the new image
            filtered_img.save(output_path)
            print(f"Filtered image saved as '{output_path}'")
            return output_path

    except FileNotFoundError:
        print(f"Error: The file at path '{image_path}' was not found.")
        return None
    except Exception as e:
        print(f"An unexpected error occurred: {e}")
        return None

def main():
    """
    Main function to run the Image Filter App with a user interface.
    """
    print("--- Python Image Filter App ---")
    print("This app applies filters to a local image file.")

    while True:
        # Get the file path from the user
        image_path = input("\nEnter the path to an image file (e.g., 'image.jpg') or 'q' to quit: ").strip()
        
        if image_path.lower() == 'q':
            print("Exiting Image Filter App. Goodbye!")
            sys.exit(0) # Exit the program

        # Check if the file exists
        if not os.path.exists(image_path):
            print("Error: File not found. Please enter a valid path.")
            continue

        # Get the desired filter type
        print("\nAvailable filters:")
        print("1. Grayscale")
        print("2. Blur")
        print("3. Sharpen")
        
        filter_choice = input("Enter the number of the filter to apply: ").strip()
        
        filter_map = {
            '1': 'grayscale',
            '2': 'blur',
            '3': 'sharpen'
        }
        
        filter_type = filter_map.get(filter_choice)

        if not filter_type:
            print("Invalid choice. Please enter 1, 2, or 3.")
            continue

        # Apply the filter and get the result
        output_path = apply_filter(image_path, filter_type)

        if output_path:
            print(f"\nSuccessfully created: {output_path}")

        print("\n---")


# This ensures that main() is called only when the script is executed directly.
if __name__ == "__main__":
    main()




← Back to Projects