Search code examples
pythonopencvimread

Unable to split opencv image to RGB


I'm trying to split an image into B,G,R but after splitting, each B G & R have grayscale images.

import cv2
import numpy as np

image = cv2.imread('/path/image.jpg') #I have tried using CV_LOAD_IMAGE_COLOR flag as well as 1
#however,image is read as color image. It is not a grayscale image

b,g,r = cv2.split(image)
#[b,g,r]=np.dsplit(image,image.shape[-1])
#b,g,r = cv2.split(image)
#b = image[:,:,0]
#g = image[:,:,1]
#r = image[:,:,2]

#none of the above worked

cv2.imshow("green",g)
cv2.waitKey(0)
cv2.destroyAllWindows()

please help me to split the image into BGR. I have even tried it with different images.


Solution

  • You are sending one channel to imshow. The green one. This will be shown as gray scale. What you want to do is send an image with red and blue channel set to zero in order to "see" it as green.

    You are doing it right when splitting, you have the red, green and blue channels. It is the display code that is confusing you and showing the green channel as grayscale.

        import numpy as np
        import cv2
    
        image = np.random.rand(200, 200, 3)
        b, g, r = cv2.split(image)
        cv2.imshow('green', g)
        cv2.waitKey(0)
    
        black = np.zeros((200, 200, 3))
        black[:, :, 1] = g # Set only green channel
        cv2.imshow('green', black)
        cv2.waitKey(0)