Adjust Image Brightness and Contrast with Pillow

  • Share this:

Code introduction


This function takes an image path, then uses the Pillow library's ImageEnhance module to adjust the brightness and contrast of the image, and finally saves the modified image to a new file.


Technology Stack : Pillow, Image, ImageEnhance

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageEnhance

def adjust_brightness_contrast(image_path, brightness_factor=1.5, contrast_factor=1.5):
    # Load the image
    with Image.open(image_path) as img:
        # Enhance brightness and contrast
        enhancer = ImageEnhance.Brightness(img)
        img = enhancer.enhance(brightness_factor)
        enhancer = ImageEnhance.Contrast(img)
        img = enhancer.enhance(contrast_factor)
    
    # Save the modified image
    img.save("enhanced_" + image_path)