Correctly Convert RGBA to RGB | OpenCV vs Pillow | Python

This tutorial will show you how to convert an RGBA image to an RGB image and set the transparent background to white (or any colors).

Although it is easy to convert an image from RGBA to RGB by simply removing the alpha channel, sometimes the transparent background turns into black (or even noises/weird artifacts) when the Alpha channel disappears. So, you might want to manually convert the transparent background to white (or any colors you like).

"Simply remove alpha channel" (wrong) vs "Remove alpha channel & set BG color" (correct)
“Simply remove alpha channel” vs “Remove alpha channel & set BG color”

Transparent to White Background

OpenCV

def cv2_RGBA2RGB(img, bg=(255,255,255)):
    b, g, r, a = cv2.split(img)
    alpha = a / 255
    r = (bg[0] * (1 - alpha) + r * alpha).astype(np.uint8)
    g = (bg[1] * (1 - alpha) + g * alpha).astype(np.uint8)
    b = (bg[2] * (1 - alpha) + b * alpha).astype(np.uint8)
    new_img = cv2.merge((b, g, r))
    return new_img

Note: The resulting image is actually in BGR format instead of RGB. In the context of this article, we use the term “RGB” to refer to a 3-channels image. (For details, please see the difference in the color format of cv2 and PIL).

Pillow

def pil_RGBA2RGB(img, bg=(255,255,255)):
    img.load() # for png.split()
    new_img = Image.new("RGB", img.size, bg)
    new_img.paste(img, mask=img.split()[3]) # 3 is the alpha channel
    return new_img

Full Example

OpenCV

import cv2
import numpy as np

# read image
cv2_img = cv2.imread("test_images/test2.png", cv2.IMREAD_UNCHANGED)

# RGBA to RGB conversion function
def cv2_RGBA2RGB(img, bg=(255,255,255)):
    b, g, r, a = cv2.split(img)
    alpha = a / 255
    r = (bg[0] * (1 - alpha) + r * alpha).astype(np.uint8)
    g = (bg[1] * (1 - alpha) + g * alpha).astype(np.uint8)
    b = (bg[2] * (1 - alpha) + b * alpha).astype(np.uint8)
    new_img = cv2.merge((b, g, r))
    return new_img

# convert RGBA to RGB
cv2_rgb_img = cv2_RGBA2RGB(cv2_img, bg=(255,255,127))

# show the image
cv2.imshow("cv2 RGB image", cv2_rgb_img)
cv2.waitKey(0)
cv2.destroyAllWindows()

Pillow

from PIL import Image

# read image
pil_img = Image.open("test_images/test2.png")

# RGBA to RGB conversion function
def pil_RGBA2RGB(img, bg=(255,255,255)):
    img.load() # for png.split()
    new_img = Image.new("RGB", img.size, bg)
    new_img.paste(img, mask=img.split()[3]) # 3 is the alpha channel
    return new_img

# convert RGBA to RGB
pil_rgb_img = pil_RGBA2RGB(pil_img, bg=(255,255,127))

# show the image
pil_rgb_img.show("pil RGB image")

References

Avatar photo
Steins

Developer & AI Researcher. Write about AI, web dev/hack.