Reputation: 2302
I am trying to combine multiple color channel images to single image. Like:
img1 = cv2.imread('This image is red channel image')
img1 = cv2.imread('This image is red channel image')
img1 = cv2.imread('This image is red channel image')
img1 = cv2.imread('This image is red channel image')
Now, I have researched online and I got 2 different answers, First way:
finalImage = np.stack((img1, img2, img3, img4), axis=-1)
Other way I searched and I got is:
finalImage = img1/4 + img2/4 + img3/4 + img4/4
Which one is the right way ? Thanks in advance.
Upvotes: 1
Views: 315
Reputation: 207355
It depends what you want.
If you want to read 4 distinct, single channel images and stack them along the final axis to get a 4-channel image, use:
finalImage = np.stack((img1, img2, img3, img4), axis=-1)
and the shape of finalImage
will be
(H, W, 4)
If you want to read 4 distinct, single channel images and average them to get a 1-channel image, use:
finalImage = img1/4 + img2/4 + img3/4 + img4/4
and the shape of finalImage
will be
(H, W)
I doubt you want this. IMHO it seems unlikely you would want to lump the Y
channel in with the colour channels, but stranger things have happened.
Upvotes: 1
Reputation: 3143
You can combine separate channels like this:
# images are loaded in "bgr" format
img_r = cv2.imread("red.png");
img_g = cv2.imread("green.png");
img_b = cv2.imread("blue.png");
# split and extract relevant channel
_,_,r = cv2.split(img_r);
_,g,_ = cv2.split(img_g);
b,_,_ = cv2.split(img_b);
# merge together as one image
bgr = cv2.merge(b,g,r);
You can also load them in as grayscale and merge without doing the split, but then you need to remember to multiply them by the their relative scaling factor. OpenCV's grayscale algorithm for BGR -> Gray is this:
Y = 0.299 R + 0.587 G + 0.114 B
Upvotes: 0