I can't put white background on transparent image with OpenCV

Question:

I’m new to OpenCV, and I need to put a white background on transparent images to do the manipulation

My transparente image is completely black, like the example:
black "rectangle"

To be able to put a white background, I create an write image using numpy, in the same dimensions as the transparent image:

img1 = cv.imread("rectangle.png", cv.IMREAD_ANYCOLOR)
arrayImg1 = np.asarray(img1)

rows, columns = arrayImg1.shape[:2]
print(f'Columns: {columns}')
print(f'Lines: {lines}')

writeImg = np.ones((rows, columns, 3)) * 255

But when I merge the images, the black part does not appear over the white part

I tried to use the "cv2.add()" method to join the images, but this not solved my problem and I don’t know any other method to do this

Asked By: Alberto Oliveira

||

Answers:

OpenCV images are already Numpy arrays. So you do not need to convert using asarray. Separate the alpha channel and the BGR channels from img1. Then use the alpha channel as a mask with Numpy to change the color using the alpha channel as a mask.

import cv2
import numpy as np

img1 = cv2.imread("rectangle.png", cv2.IMREAD_UNCHANGED)
bgr = img1[:,:,0-3]
print(bgr.shape)
alpha = img1[:,:,3]
print(alpha.shape, np.amin(alpha), np.amax(alpha))
result = bgr.copy()
result[alpha==0] = 255

cv2.imwrite('rectangle_white.png', result)

cv2.imshow('bgr', bgr)
cv2.imshow('alpha', alpha)
cv2.waitKey(0)

Turns out that your image is single channel with alpha rather than 3 channel with alpha. So the color assigned at the end should be just 255 rather than (255,255,255). See the print results to the terminal from the above.

Answered By: fmw42
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.