如何在非灰度图像的彩色通道中显示图像?

时间:2017-12-13 12:20:32

标签: python opencv python-3.6

我试图在彩色通道中获取图像,但不是灰度图像。以下是代码: -

img = cv2.imread("image.jpg")
blue = img[:,:,0].copy() # Blue channel image
blue[:,:,1] = 0  # Making green channel 0
blue[:,:,2] = 0  # Making red channel 0

但是,当我尝试制作“image.jpg”蓝色通道的绿色通道和红色通道0时,它会指向第3行和第4行的错误。

错误:IndexError: too many indices for array

我在Mac上使用OpenCV 3.3和python 3.6。

2 个答案:

答案 0 :(得分:3)

好的,你走了:

import cv2
import numpy as np

def get_channel(im, n):
    if 0 <= n <= 2 and im.shape[2]==3:
        new_im = np.zeros_like(im)
        new_im[:, :, n] = im[:, :, n]

        return new_im
    return False

im = cv2.imread(your_image_filename_goes_here)
cv2.imshow("Chanel", get_channel(im, 0))
cv2.waitKey(0)
cv2.destroyAllWindows()

在您的示例中,blue具有形状(x,y),而img具有形状(x,y,3)。这就是显示蓝色的原因是灰度,因为作为二维数组opencv并不知道它是蓝色通道。

彩色图像只是三个&#34;灰度图像&#34;虽然它们并不像普通灰度图像那样代表光强度,但它们代表了某些颜色的光强度。并且三个通道的组合给出了颜色。

灰度图像只是一个整数的二维数组(3,3):

y y y
y y y
y y y

RGB(或OpenCV BGR)图像是三维整数数组(3,3,3):

B B B    G G G    R R R
B B B    G G G    R R R
B B B    G G G    R R R

如果您只是拍摄BGR图像的第一个频道,那么您正在拍摄(3,3):

B B B
B B B
B B B

对于与灰度图像相同的OpenCV。

答案 1 :(得分:3)

将频道拆分,然后与零合并:

img = cv2.imread("ColorChecker.png")
b,g,r = cv2.split(img)
I0 = np.zeros(img.shape[:2], np.uint8)
B = np.dstack([b,I0,I0])
G = np.dstack([I0,g,I0])
R = np.dstack([I0,I0,r])

enter image description here

相关问题