Adjust Image Brightness and Contrast in Python

  • Share this:

Code introduction


This function is used to adjust the brightness and contrast of an image. It first opens the image, then uses the Brightness and Contrast enhancers from the ImageEnhance module to adjust the brightness and contrast, and finally saves the adjusted image.


Technology Stack : Pillow library

Code Type : Image processing

Code Difficulty : Intermediate


                
                    
from PIL import Image, ImageEnhance, ImageFilter

def adjust_brightness_contrast(image_path, brightness_factor, contrast_factor):
    # Open the image
    with Image.open(image_path) as img:
        # Adjust brightness
        enhancer = ImageEnhance.Brightness(img)
        brightened_img = enhancer.enhance(brightness_factor)
        
        # Adjust contrast
        enhancer = ImageEnhance.Contrast(brightened_img)
        contrast_img = enhancer.enhance(contrast_factor)
        
        # Save the image
        contrast_img.save("adjusted_image.jpg")                
              
Tags: