如何在 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 程序时,它将生成以下 **三个输出窗口**,每个窗口都显示一个颜色通道(蓝色、绿色和红色)作为灰度图像。
Learn Python in-depth with real-world projects through our Python certification course. Enroll and become a certified expert to boost your career.
示例
在此示例中,我们将输入图像分割成其组成颜色通道:蓝色、绿色和红色。我们还显示这些颜色通道的彩色图像(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 程序时,它将生成以下 **三个输出窗口**,每个窗口都显示一个颜色通道(蓝色、绿色和红色)作为彩色图像。
广告