Answer a question

I have a OpenCv Image likewise;

opencvImage = cv2.cvtColor(numpy_image, cv2.COLOR_RGBA2BGRA)

Then with the following code piece, I want to remove the transparency and set a White background.

source_img = cv2.cvtColor(opencvImage[:, :, :3], cv2.COLOR_BGRA2GRAY)
source_mask = opencvImage[:,:,3]  * (1 / 255.0)

background_mask = 1.0 - source_mask

bg_part = (background_color * (1 / 255.0)) * (background_mask)
source_part = (source_img * (1 / 255.0)) * (source_mask)

result_image = np.uint8(cv2.addWeighted(bg_part, 255.0, source_part, 255.0, 0.0))

Actually, I am able to set the background white, however, the actual image color is change, as well. I believe COLOR_BGRA2GRAY methods causes this problem. That's why, I tried to use IMREAD_UNCHANGED method, but I have this error : unsupported color conversion code in function 'cvtColor’

Btw, I am open to any solution, I just share my code - might need a small fix.

Answers

Here's a basic script that will replace all fully transparent pixels with white and then remove the alpha channel.

import cv2
#load image with alpha channel.  use IMREAD_UNCHANGED to ensure loading of alpha channel
image = cv2.imread('your image', cv2.IMREAD_UNCHANGED)    

#make mask of where the transparent bits are
trans_mask = image[:,:,3] == 0

#replace areas of transparency with white and not transparent
image[trans_mask] = [255, 255, 255, 255]

#new image without alpha channel...
new_img = cv2.cvtColor(image, cv2.COLOR_BGRA2BGR)
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐