Adjust Image Brightness and Contrast with Python

  • Share this:

Code introduction


This function takes an image path and brightness and contrast factors to adjust the brightness and contrast of the image, and saves the adjusted image.


Technology Stack : Pillow

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageEnhance

def adjust_brightness_contrast(image_path, brightness_factor=1.0, contrast_factor=1.0):
    # Load the image
    with Image.open(image_path) as img:
        # Adjust brightness
        enhancer = ImageEnhance.Brightness(img)
        img = enhancer.enhance(brightness_factor)
        
        # Adjust contrast
        enhancer = ImageEnhance.Contrast(img)
        img = enhancer.enhance(contrast_factor)
        
        # Save the image with adjusted brightness and contrast
        img.save("adjusted_" + image_path)                
              
Tags: