pythonopencvmatplotlib

Channels of the image before and after conversion have not changed


I use OpenCV to read an RGB image and going to print it by matplotlib. So, I use the cvtColor to transfer the BGR(As I know, the imread ofen reads BGR channels) to RGB. But after print, i checked the channels didn't change! It seems img[:,:,0] == new[:,:,0].

img = cv2.imread(r'E:\jupyter\CVlearn\lab\lab1\Task1.jpg')
print(img[:,:,0])
new = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
print(new[:,:,0])
plt.imshow(new)
plt.show()

And then I tried use cvtColor to the input image directly. And the output seems have an intensity inversion. I dont really know what happen.

b,g,r = cv2.split(img)
test = cv2.merge((r,g,b))
print(test[:,:,0])
print(img[:,:,0])
plt.imshow(test)
plt.show()

Solution

  • Oh, I just found that image is gray but i read as a RGB image. That will cause some problems about the channels. The main reason: opencv will read images with three channels by default. If it is a grayscale image/infrared image, its layer will be copied three times (RGB is the default), so the read image is three-channel. If we want to read grayscale images/infrared images as a single channel from the beginning, we can add the relevant parameters (cv2.IMREAD_GRAYSCALE) to the imread() function:img = cv2.imread(img_path, cv2.IMREAD_GRAYSCALE)