Reputation: 15
How can I add alpha channel to png image? Precisely I have the background using grabcut function, now I want to add it to the png image.
After that I want to set the alpha channel to transparent by use of a mask
img[np.all(img == [0, 0, 0, 255], axis=2)] = [0, 0, 0, 0]
Upvotes: 0
Views: 3772
Reputation: 171
Here is fill channel approach.
import cv2
# path to your own images
rgb = cv2.imread('images/5v63T_RGB.png')
alpha = cv2.imread('images/5v63T_Alpha.png')
rgba = cv2.cvtColor(rgb, cv2.COLOR_RGB2RGBA)
one_channel_alpha = cv2.cvtColor(alpha, cv2.COLOR_RGB2GRAY)
# fill alpha channel with image (needs to be same size)
rgba[:, :, 3] = one_channel_alpha
cv2.imshow("rgb", rgb)
cv2.imshow("alpha", one_channel_alpha)
cv2.imshow("rgba", rgba)
# you can't visualize alpha channel as transparency.
# the 32 bits PNG image, so let's save and use other view.
cv2.imwrite("images/result_rgba.png", rgba)
cv2.waitKey(0)
cv2.destroyAllWindows()
Good Luck.
Upvotes: 2