user3361879
user3361879

Reputation: 85

how to convert alpha channel of the image to white color using opencv python?

I want to convert PNG and GIF images to JPEG using openCV, the alpha channel should be converted to white color. is there any way to achive this ?

Upvotes: 4

Views: 4819

Answers (2)

mqod
mqod

Reputation: 103

in RGBA images, alpha channel represent how background will effect in image. so you have an equation (not code) like this:

out = (bg * (1 - alpha)) + (image * alpha)

where out is final image and image is R,G and B channel of our RGBA image and bg is background image. here we have 0 <= alpha <= 1.

for your case, you want your background to be a plane white image so the calculation is very simple from this point. you can do something like this:

B, G, R, A = cv2.split(image)
alpha = A / 255

R = (255 * (1 - alpha) + R * alpha).astype(np.uint8)
G = (255 * (1 - alpha) + G * alpha).astype(np.uint8)
B = (255 * (1 - alpha) + B * alpha).astype(np.uint8)

image = cv2.merge((B, G, R))

and if you don't like this split and merge stuff (like me) you can use this implimentation:

bg = np.array([255, 255, 255])
alpha = (image[:, :, 3] / 255).reshape(image.shape[:2] + (1,))
image = ((bg * (1 - alpha)) + (image[:, :, :3] * alpha)).astype(np.uint8)

in first line i make background image, in second line i compute the alpha value between 0 and 1 and reshape it to make it 3-D array (it is necessary for multiplication) and the last line is the formula of alpha.

Upvotes: 4

Anuradha
Anuradha

Reputation: 1147

Using Open CV, you can open the image in RGB format, i.e, when you are doing an cv2.imread give the second parameter as 1 instead of -1. -1 opens the image in whatever be the original format of the image , i.e, it would retain the transparency. Keeping that parameter as 1 you can open it in RGB format. After that you can do an cv2.imwrite to save the RGB image without transparency. You can mention the file format as .jpg

Upvotes: 2

Related Questions