SoFunction
Updated on 2025-05-14

Two ways to convert transparent background of picture to white background of python

Method 1: Use OpenCV function encapsulation

Install the library

pip install opencv-python

Implement code

import cv2
import numpy as np

def convert_transparent_to_white_opencv(input_image_path, output_image_path):
    """
     Convert a picture of a transparent background to a white background, using OpenCV to implement it.

     parameter:
     input_image_path: str, input the path to the image
     output_image_path: str, the path to output the image

     return:
     none
     """
    # Read an image with a transparent background (assuming the image is in PNG format)    img = (input_image_path, cv2.IMREAD_UNCHANGED)

    # Check whether the read is successful    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # Separate RGBA Channels    b, g, r, a = (img)

    # Create a fully white background with the same size as the Alpha channel    white_background = np.ones_like(a) * 255

    # Normalize the Alpha channel to the 0-1 range    a = a / 255.0

    # Mix the original image and white background according to the transparency of the Alpha channel    r = r * a + white_background * (1 - a)
    g = g * a + white_background * (1 - a)
    b = b * a + white_background * (1 - a)

    # Merge BGR Channels    result = ((b, g, r))

    # Save the processed picture    (output_image_path, result)

# Sample callconvert_transparent_to_white_opencv('input_image.png', 'output_image_opencv.png')

Method 2: Function encapsulation using PIL

Install the library

pip install pillow

Complete code

from PIL import Image

def convert_transparent_to_white_pil(input_image_path, output_image_path):
    """
     Convert a picture of a transparent background to a white background, using PIL to implement it.

     parameter:
     input_image_path: str, input the path to the image
     output_image_path: str, the path to output the image

     return:
     none
     """
    # Read an image with a transparent background (assuming the image is in PNG format)    img = (input_image_path).convert("RGBA")

    # Create a white background with the same size as the original image    white_background = ("RGB", , (255, 255, 255))

    # Paste the original image on a white background and use the Alpha channel as the mask    white_background.paste(img, (0, 0), img)

    # Save the processed picture    white_background.save(output_image_path)

# Sample callconvert_transparent_to_white_pil('input_image.png', 'output_image_pil.png')

Detailed explanation

OpenCV method function encapsulation

  • Function definition: Define a function convert_transparent_to_white_opencv, which accepts the input image path and the output image path as parameters.
  • Read pictures: Use () to read pictures inside the function and perform transparent channel processing.
  • Image processing: Follow the previous steps to separate the channel, create a white background, and image synthesis.
  • Save picture: Save the processed picture to the specified path.

PIL method function encapsulation

  • Function definition: Define a function convert_transparent_to_white_pil, accepting the input image path and the output image path as parameters.
  • Read pictures: Use () to read pictures inside the function and perform transparent channel processing.
  • Image Paste: Create a white background as follows the previous steps and paste the original image onto a white background.
  • Save picture: Save the processed picture to the specified path.

Through the above encapsulation function, it is easier to convert pictures with transparent background to pictures with white background.

You can convert pictures with transparent backgrounds to pictures with any color background and convert between any color backgrounds. The following is a method using OpenCV and PIL and is encapsulated with function, allowing the user to specify any background color.

1. Function encapsulation using OpenCV

import cv2
import numpy as np

def convert_transparent_to_color_opencv(input_image_path, output_image_path, bg_color=(255, 255, 255)):
    """
    Convert a picture of a transparent background to any color background,useOpenCVaccomplish。

    parameter:
    input_image_path: str,Enter the path to the image
    output_image_path: str,The path to output the image
    bg_color: tuple,Background color(Default is white (255, 255, 255))

    return:
    none
    """
    # Read an image with a transparent background (assuming the image is in PNG format)    img = (input_image_path, cv2.IMREAD_UNCHANGED)

    # Check whether the read is successful    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # Separate RGBA Channels    b, g, r, a = (img)

    # Create a specified color background with the same size as the Alpha channel    background = np.ones_like(a) * (bg_color[::-1], dtype=np.uint8)[:, None, None]

    # Normalize the Alpha channel to the 0-1 range    a = a / 255.0

    # Mix original image and background according to the transparency of the Alpha channel    r = r * a + background[0] * (1 - a)
    g = g * a + background[1] * (1 - a)
    b = b * a + background[2] * (1 - a)

    # Merge BGR Channels    result = ((b, g, r))

    # Save the processed picture    (output_image_path, result)

# Sample callconvert_transparent_to_color_opencv('input_image.png', 'output_image_opencv.png', bg_color=(0, 128, 255))

2. Function encapsulation using PIL

from PIL import Image

def convert_transparent_to_color_pil(input_image_path, output_image_path, bg_color=(255, 255, 255)):
    """
    Convert a picture of a transparent background to any color background,usePILaccomplish。

    parameter:
    input_image_path: str,Enter the path to the image
    output_image_path: str,The path to output the image
    bg_color: tuple,Background color(Default is white (255, 255, 255))

    return:
    none
    """
    # Read an image with a transparent background (assuming the image is in PNG format)    img = (input_image_path).convert("RGBA")

    # Create a background image with the same size as the original image    background = ("RGB", , bg_color)

    # Paste the original image on the specified color background and use transparency as the mask    (img, (0, 0), img)

    # Save the processed picture    (output_image_path)

# Sample callconvert_transparent_to_color_pil('input_image.png', 'output_image_pil.png', bg_color=(0, 128, 255))

Detailed explanation

Method function encapsulation

  • Function definition: Define a function convert_transparent_to_color_opencv, which accepts input image path, output image path and background color as parameters.
  • Read pictures: Use() inside the function to read pictures with transparent background and perform transparent channel processing.
  • Check whether the read is successful: Make sure the image is read successfully, otherwise an exception will be thrown.
  • Separate RGBA channels: Use () to separate the image into four channels (RGBA).
  • Create background: Create a specified color background with the same size as the Alpha channel, and the colors are converted to BGR order in accordance with OpenCV's color order.
  • Image synthesis: Normalize the alpha channel to the range 0-1 and mix the original image and background according to the transparency of the alpha channel.
  • Merge channels and save pictures: Merge BGR channels and save the processed pictures.

Method function encapsulation

  • Function definition: Define a function convert_transparent_to_color_pil, which accepts input image path, output image path and background color as parameters.
  • Read the picture: Use() inside the function to read the picture with a transparent background and convert it to RGBA mode.
  • Create background: Creates a background image of the specified color that is the same size as the original image.
  • Image paste: Paste the original image onto the background using the paste() method and use transparency as the mask.
  • Save the picture: Save the processed picture.

Both methods can convert transparent backgrounds to any color background and support conversion between any color backgrounds. You can choose the appropriate tools and methods according to your specific needs.

Use OpenCV to add a slightly larger white background to the picture transparent background

import cv2
import numpy as np

def add_white_background_with_padding_opencv(input_image_path, output_image_path, padding=10):
    """
     Convert a picture of a transparent background to a picture with a slightly larger white background, using OpenCV.

     parameter:
     input_image_path: str, input the path to the image
     output_image_path: str, the path to output the image
     padding: int, the extended size of the background (default is 10 pixels)

     return:
     none
     """
    # Read an image with a transparent background (assuming the image is in PNG format)    img = (input_image_path, cv2.IMREAD_UNCHANGED)

    # Check whether the read is successful    if img is None:
        raise ValueError(f"Image at path {input_image_path} could not be read.")

    # Separate RGBA Channels    b, g, r, a = (img)

    # Get the size of the original image    height, width = 

    # Create a slightly larger white background    new_height = height + 2 * padding
    new_width = width + 2 * padding
    white_background = ((new_height, new_width, 3), dtype=np.uint8) * 255

    # Normalize the Alpha channel to the 0-1 range    a = a / 255.0

    # Create a new RGBA image and place the original image in the center    result = ((new_height, new_width, 3), dtype=np.uint8)
    for c in range(3):
        result[padding:padding + height, padding:padding + width, c] = img[:, :, c] * a + white_background[padding:padding + height, padding:padding + width, c] * (1 - a)

    # Save the processed picture    (output_image_path, result)

# Sample calladd_white_background_with_padding_opencv('input_image.png', 'output_image_with_padding.png', padding=20)

Detailed explanation

  • Function definition: Define a function add_white_background_with_padding_opencv, which accepts input image path, output image path and background extension size as parameters.
  • Read the picture: Use() to read the picture with a transparent background and specify cv2.IMREAD_UNCHANGED to ensure that the transparent channel (Alpha channel) is read.
  • Check whether the read is successful: Make sure the image is read successfully, otherwise an exception will be thrown.
  • Separate RGBA channels: Use () to separate the image into four channels (RGBA).
  • Get the original image size: Get the height and width of the original image.
  • Create a white background: Create a slightly larger white background with the background size plus twice the extended size of the original image.
  • Normalize the Alpha channel: Normalize the value of the Alpha channel to the range 0-1.
  • Image Composition: Create a new image and place the original image in the center while mixing the original image and the white background according to the transparency of the Alpha channel.

Save processed picture: Save the processed picture to the specified path.

In this way, the image with a transparent background can be converted to an image with a slightly larger white background.

The above is the detailed content of two methods for Python to convert transparent backgrounds to white backgrounds. For more information on converting python image backgrounds, please pay attention to my other related articles!