如何在 OpenCV 中使用 C++ 將影像分割成不同的通道?


RGB影像有三個通道——紅、綠、藍。紅色、綠色和藍色通道表示影像的顏色空間稱為 RGB 顏色空間。在 OpenCV 中,使用 BGR 序列而不是 RGB。這意味著第一個通道是藍色,第二個通道是綠色,第三個通道是紅色。要將 RGB 影像分割成不同的通道,我們需要定義一個 3 通道矩陣。我們使用 'Mat different_Channels[3]' 來定義一個三通道矩陣。

接下來,我們使用 OpenCV 的 'split()' 函式分割載入的影像。此函式的格式為 'split(源矩陣, 目標矩陣)'。 此函式將源矩陣的影像分割成影像的通道,並將它們儲存到目標矩陣中。執行此行 – 'split(myImage, different_Channels);'

split 函式已將藍色、綠色和紅色通道載入到 'different_channels' 矩陣中。使用以下幾行,我們將儲存在不同通道中的影像載入到新的矩陣中。

Mat b = different_Channels[0];//loading blue channels//
Mat g = different_Channels[1];//loading green channels//
Mat r = different_Channels[2];//loading red channels//

最後,我們使用以下幾行以不同的方式顯示每個通道:

imshow("Blue Channel",b);//showing Blue channel//
imshow("Green Channel",g);//showing Green channel//
imshow("Red Channel",r);//showing Red channel//

這就是我們將影像分割成其通道的方式。

以下程式將 RGB 影像分割成藍色、綠色和紅色通道。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
#include<opencv2/imgproc/imgproc.hpp>
using namespace cv;
using namespace std;
int main(int argc,const char** argv) {
   Mat myImage;//declaring a matrix to load the image//
   Mat different_Channels[3];//declaring a matrix with three channels//  
   myImage= imread("RGB.png");//loading the image in myImage matrix//
   split(myImage, different_Channels);//splitting images into 3 different channels//  
   Mat b = different_Channels[0];//loading blue channels//
   Mat g = different_Channels[1];//loading green channels//
   Mat r = different_Channels[2];//loading red channels//  
   imshow("Blue Channel",b);//showing Blue channel//
   imshow("Green Channel",g);//showing Green channel//
   imshow("Red Channel",r);//showing Red channel//
   imshow("Actual_Image", myImage);//showing actual image//
   waitKey(0);//wait for key stroke
   destroyAllWindows();//closing all windows//
   return 0;
}

輸出

更新於: 2021年3月10日

4K+ 次瀏覽

啟動您的 職業生涯

透過完成課程獲得認證

開始學習
廣告
© . All rights reserved.