在Python中显示RGB图像的不同平面

彩色图像可以表示为3阶矩阵。第一个顺序用于行,第二个顺序用于列,第三个顺序用于指定相应像素的颜色。在这里,我们使用BGR颜色format(because OpenCV python library works on BGR format, not on RGB),因此三阶将分别采用蓝色,绿色和红色这3个值。

BGR图像的彩色平面:

然后考虑一个BGR图像阵列,

  • I [:,:,0]表示BGR图像的蓝色平面

  • I [:,:,1]表示BGR图像的绿色平面

  • I [:,:,2]表示BGR图像的红色平面

在此程序中,我们将使用OpenCV-python(cv2)模块的两个功能。我们先来看一下它们的语法和描述:

1) imread():
它将图像文件的绝对路径/相对路径作为参数,并返回其对应的图像矩阵。

2) imshow():
以窗口名称和图像矩阵为参数,以便在具有指定窗口名称的显示窗口中显示图像。

3)形状:这是图像矩阵的属性,其返回图像的形状,即由行数,列数和平面数组成。

Python程序可显示RGB图像的不同平面

# open-cv库在python中安装为cv2
# 将cv2库导入此程序
import cv2

# 导入numpy库为np
import numpy as np

# read an image using imread() function of cv2
# 我们只需要传递图像的路径
img = cv2.imread(r'C:/Users/user/Desktop/pic4.jpg')

# displaying the image using imshow() function of cv2
# 在此:第一个参数是框架的名称
# 第二个参数是图像矩阵
cv2.imshow('original image',img)

# 图像矩阵的shape属性给出尺寸
row,col,plane = img.shape

# 这里的图片是'uint8'类的,取值范围  
# 每个颜色分量可以具有的是[0-255]

# 创建与零阶相同的零矩阵
# 相同尺寸的原始图像矩阵顺序
temp = np.zeros((row,col,plane),np.uint8)

# 存储蓝色平面内容或图像矩阵数据
# to the corresponding plane(blue) of temp matrix
temp[:,:,0] = img[:,:,0]

# 显示蓝色平面图像
cv2.imshow('Blue plane image',temp)

# 再次采用图像矩阵形状的零矩阵
temp = np.zeros((row,col,plane),np.uint8)

# 存储绿色平面内容或图像矩阵数据
# to the corresponding plane(green) of temp matrix
temp[:,:,1] = img[:,:,1]

# 显示绿色平面图像
cv2.imshow('Green plane image',temp)

# 再次采用图像矩阵形状的零矩阵
temp = np.zeros((row,col,plane),np.uint8)

# 存储红色平面内容或图像矩阵数据
# to the corresponding plane(red) of temp matrix
temp[:,:,2] = img[:,:,2]

# 显示红色平面图像
cv2.imshow('Red plane image',temp)

输出结果

在Python中显示RGB图像的不同平面-输出
在Python中显示RGB图像的不同平面-输出