Convert RGBA to RGB | OpenCV vs Pillow | Python

In this tutorial, I will show you how to convert RGBA images to RGB images in the simplest ways using OpenCV (cv2) and Pillow (PIL).

An RGBA image has 4 channels: red, green, blue, and alpha. The alpha channel stores how transparent each pixel is, while an RGB image only has the 3 color channels and no transparency. So when you simply drop the alpha channel, the transparent areas often turn black, because the hidden color values behind them are usually 0.

This method simply removes the alpha channel from the RGBA images, the transparency will turn into black (or sometimes noises) in the resulting images. If you want to set the background color, please read: Keep a White (or Any Color) Background.

Convert RGBA to RGB by removing the alpha channel
Convert RGBA to RGB by removing the alpha channel

RGBA to RGB

# OpenCV
cv2_rgb_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGRA2BGR)

# Pillow
pil_img.convert('RGB')

Note: The resulting image is actually in BGR format instead of RGB. Here 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). To pass the result to PIL, see BGR in OpenCV vs RGB in PIL.

Advertisement

Keep a White (or Any Color) Background

Simply removing the alpha channel can turn the transparent background black (or even into noise). To fix this, we blend each pixel with a background color, using the alpha value as the weight. The background is white by default, but you can pick any color.

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

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

Pillow

Advertisement
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

To use another color, pass it as bg. For example, bg=(255,255,127) gives a light yellow background. The OpenCV version also needs import numpy as np.

Full Example

OpenCV

import cv2

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

# convert RGBA to RGB
cv2_rgb_img = cv2.cvtColor(cv2_img, cv2.COLOR_BGRA2BGR)

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

Pillow

from PIL import Image

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

# convert RGBA to RGB
pil_img.convert('RGB')

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

Syntax

OpenCV

cv2.cvtColor(src, code[, dst[, dstCn]])

Parameters:

  • src: input image: 8-bit unsigned, 16-bit unsigned ( CV_16UC… ), or single-precision floating-point.
  • dst: output image of the same size and depth as src.
  • code: color space conversion code (see ColorConversionCodes).
  • dstCn: number of channels in the destination image; if the parameter is 0, the number of channels is derived automatically from src and code.

Returns:

  • The converted image (Numpy array)

Pillow

Image.convert(mode=None, matrix=None, dither=None, palette=Palette.WEB, colors=256)

Parameters:

  • mode: The requested mode. See Modes.
  • matrix: An optional conversion matrix. If given, this should be 4- or 12-tuple containing floating point values.
  • dither: Dithering method, used when converting from mode “RGB” to “P” or from “RGB” or “L” to “1”. Available methods are Dither.NONE or Dither.FLOYDSTEINBERG (default). Note that this is not used when matrix is supplied.
  • palette: Palette to use when converting from mode “RGB” to “P”. Available palettes are Palette.WEB or Palette.ADAPTIVE.
  • colors: Number of colors to use for the Palette.ADAPTIVE palette. Defaults to 256.

Returns:

References

Avatar photo
Steins

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