Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract individual channels from an RGB image

I found the opencv documentation to extract the single channels from an RGB image using the cv2.split (img) command, but it does not really return an image of the chosen channel. They all look like grayscale. Can someone help me? I enclose the photos.

b = img[:,:,0]
g = img[:,:,1]
r = img[:,:,2]

or

b,g,r = cv2.split(img)

starting image = enter image description here red channel extracted = enter image description here

Is it a correct extraction? Where is the full red channel - img?

like image 243
Da Nio Avatar asked Aug 07 '19 16:08

Da Nio


2 Answers

The extracted red channel may look like a grayscale image but it is correct. It is simply a 2D array with values in the range [0,255]. To visualize a specific channel, you need to set the other channels to zero. So to show the red channel, the blue and green channels need to be set to zero.

import cv2

img = cv2.imread('1.jpg')

# Set blue and green channels to 0
img[:,:,0] = 0
img[:,:,1] = 0

cv2.imshow('red_img', img)
cv2.waitKey()

enter image description here

like image 59
nathancy Avatar answered Oct 12 '22 23:10

nathancy


In either method, you are creating a grayscale image, so plotting it won't show the color of the channel it was derived from.

You can either use a colormap to add color to the image you display or convert it to an RGB image by setting the other channels to 0.

plt.imshow(r, cmap='Reds')

OR

img = np.stack([r, np.zeros_like(r), np.zeros_like(r)], axis=-1)
plt.imshow(img)
like image 34
busybear Avatar answered Oct 12 '22 23:10

busybear