2

I have two images, one with and other without alpha channel. Thus, image A and B has a shape of (x,y,4) and (x,y,3) respectively.

I want to merge both images in a single tensor using python, where B is the background and A is the upper image. The final image must have a shape of (x, y, 3). I tried if scikit-image or cv2 is capable of doing this, but I couldn't found any solution.

Jeru Luke
  • 20,118
  • 13
  • 80
  • 87
nunodsousa
  • 2,635
  • 4
  • 27
  • 49

2 Answers2

7

here is alpha blending in python

import numpy as np
import cv2

alpha = 0.4

img1 = cv2.imread('Desert.jpg')
img2 = cv2.imread('Penguins.jpg')

#r,c,z = img1.shape

out_img = np.zeros(img1.shape,dtype=img1.dtype)
out_img[:,:,:] = (alpha * img1[:,:,:]) + ((1-alpha) * img2[:,:,:])
'''
# if want to loop over the whole image
for y in range(r):
    for x in range(c):
        out_img[y,x,0] = (alpha * img1[y,x,0]) + ((1-alpha) * img2[y,x,0])
        out_img[y,x,1] = (alpha * img1[y,x,1]) + ((1-alpha) * img2[y,x,1])
        out_img[y,x,2] = (alpha * img1[y,x,2]) + ((1-alpha) * img2[y,x,2])
'''

cv2.imshow('Output',out_img)
cv2.waitKey(0)
user8190410
  • 1,264
  • 2
  • 8
  • 15
  • 1
    How does a JPG have ARGB color? This does not answer the question, IMHO. Don't know how this can be the accepted answer. It does not use the alpha channel of the upper picture. – Thomas Weller Jan 04 '22 at 12:33
  • Kindly check what is alpha blending first https://docs.opencv.org/3.4/d5/dc4/tutorial_adding_images.html . The answer does not say that it uses alpha channel. – user8190410 Jan 04 '22 at 12:50
  • 1
    OP: "I have two images, one with and other without alpha channel" What is (x,y,4) if not RGBA? – Thomas Weller Jan 04 '22 at 12:55
  • If you are using png images and want to use alpha mask then you can see this tutorial https://learnopencv.com/alpha-blending-using-opencv-cpp-python/ – user8190410 Jan 04 '22 at 12:56
  • Also, if you don't want transparency in your final image you can simply delete the 4th / alpha channel – user8190410 Jan 04 '22 at 13:03
0

The above solution works, however I have a more efficient one:

alpha = A[:,:,3]
A1 = A[:,:,:3]

C = np.multiply(A1, alpha.reshape(x,y,1)) + np.multiply(B, 1-alpha.reshape(x,y,1))
nunodsousa
  • 2,635
  • 4
  • 27
  • 49