简体   繁体   中英

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM