medical

RGBA images

#2
by jjaspe - opened

Not sure if this was mentioned somewhere, but I couldn't get it to work with RGBA images so we're doing this to turn them to RGB:

def convert_rgba_to_rgb(input_path, background_color=(255, 255, 255)):
    """
    Convert an RGBA image to RGB format.
    """
    # Open the image
    with Image.open(input_path) as img:
        # Check if image has an alpha channel
        if img.mode in ('RGBA', 'LA') or (img.mode == 'P' and 'transparency' in img.info):
            # Create a new background image with the same size
            background = Image.new('RGB', img.size, background_color)
            
            # Convert image to RGBA if it's not already
            if img.mode != 'RGBA':
                img = img.convert('RGBA')
            
            # Composite the image onto the background
            rgb_img = Image.alpha_composite(background.convert('RGBA'), img).convert('RGB')
        else:
            # If no alpha channel, just convert to RGB
            rgb_img = img.convert('RGB')    
    return rgb_img

Sign up or log in to comment