如何在 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 程式時,它將生成以下 **三個輸出視窗**,每個視窗都顯示一個顏色通道(藍色、綠色和紅色)作為彩色影像。




更新於: 2022-12-02

8K+ 瀏覽量

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告