OpenCV Python 如何将图像分割成不同的颜色通道
颜色图像由三个颜色通道-红色、绿色和蓝色组成。可以使用 cv2.split() 函数来分割这些颜色通道。让我们来看一下将图像分割成不同颜色通道的步骤:
- 导入所需的库。在以下所有的示例中,所需的Python库是 OpenCV 。请确保您已经安装了它。
-
使用 cv2.imread() 方法读取输入图像。指定图像的完整路径和图像类型(即png或jpg)。
-
在输入图像 img 上应用 cv2.split() 函数。它以numpy数组的形式返回蓝色、绿色和红色通道的像素值。将这些值赋给变量 blue、green和red。
blue,green,red = cv2.split(img)
- 将三个通道显示为灰度图像。
让我们看一些实例以便更清楚地理解。
我们将使用此图像作为以下示例中的 输入文件 :
示例
在这个示例中,我们将一个输入图像分割成其组成的颜色通道:蓝色、绿色和红色。我们还显示这些颜色通道的灰度图像。
# import required libraries
import cv2
# read the input color image
img = cv2.imread('bgr.png')
# split the Blue, Green and Red color channels
blue,green,red = cv2.split(img)
# display three channels
cv2.imshow('Blue Channel', blue)
cv2.waitKey(0)
cv2.imshow('Green Channel', green)
cv2.waitKey(0)
cv2.imshow('Red Channel', red)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出
当您运行以上Python程序时,它将产生以下 三个输出窗口 ,每个窗口显示一个灰度图像作为颜色通道(蓝色、绿色和红色)。
示例
在这个示例中,我们将输入图像分割成其组成的颜色通道:蓝色、绿色和红色。我们还显示这些颜色通道的彩色图像(BGR)。
# import required libraries
import cv2
import numpy as np
# read the input color image
img = cv2.imread('bgr.png')
# split the Blue, Green and Red color channels
blue,green,red = cv2.split(img)
# define channel having all zeros
zeros = np.zeros(blue.shape, np.uint8)
# merge zeros to make BGR image
blueBGR = cv2.merge([blue,zeros,zeros])
greenBGR = cv2.merge([zeros,green,zeros])
redBGR = cv2.merge([zeros,zeros,red])
# display the three Blue, Green, and Red channels as BGR image
cv2.imshow('Blue Channel', blueBGR)
cv2.waitKey(0)
cv2.imshow('Green Channel', greenBGR)
cv2.waitKey(0)
cv2.imshow('Red Channel', redBGR)
cv2.waitKey(0)
cv2.destroyAllWindows()
输出
当您运行上述python程序时,它将生成以下 三个输出窗口 ,每个窗口显示一个颜色通道(蓝色、绿色和红色)作为彩色图像。