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).
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: Correctly Convert RGBA to RGB.
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).
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 fromsrc
andcode
.
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 areDither.NONE
orDither.FLOYDSTEINBERG
(default). Note that this is not used whenmatrix
is supplied.palette
: Palette to use when converting from mode “RGB” to “P”. Available palettes arePalette.WEB
orPalette.ADAPTIVE
.colors
: Number of colors to use for thePalette.ADAPTIVE
palette. Defaults to 256.
Returns:
- An
Image
object.