如何在 OpenCV 中使用 C++ 讀取多通道影像的畫素值?


我們聲明瞭三個名為“blue_Channel”、“green_channel”和“red_channel”的變數。這些變數的目的是儲存畫素值。我們在“for迴圈”中使用了這些變數。然後我們聲明瞭一個名為“color_Image_Matrix”的矩陣。

此方法的語法為

blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0];

我們使用了一張 BGR 影像。它有三個通道。這些通道維護特定的順序,color_image_Matrix.at<Vec3b> (i, j) 表示位於 (i,i) 處的畫素值,而 [0] 表示第一個通道。例如,如果我們這樣寫程式碼:

blue_Channel=color_image_Matrix.at<Vec3b> (30, 35) [0];

這意味著變數“blue_Channel”將包含位於 (30, 35) 處的第一個通道的畫素值。這就是我們如何使用 OpenCV 訪問畫素值。

以下程式讀取不同 RGB 影像的畫素值,並在控制檯視窗中顯示不同通道畫素的值。

示例

#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main() {
   int blue_Channel;
   int green_Channel;
   int red_Channel;
   Mat color_image_Matrix; //Declaring a matrix to load the image//
   color_image_Matrix = imread("colors.jpg"); //loading image in the matrix//
   //Beginning of for loop to read pixel values of blue channel//
   for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {
      for (int j = 0; j < color_image_Matrix.cols; j++) {
         //loop for columns//
         blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0];
         //To read the value of first channel.Here the blue channel is first channel//
         cout << "Value of pixel of blue channel" << "(" << i << "," << j << ")" << "="
            << blue_Channel << endl; //showing the values in console window//
      }
   }
   //End of for loop to read pixel values of blue channel//
   //Beginning of for loop to read pixel values of green channel//
   for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {
      for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// {
         green_Channel = color_image_Matrix.at<Vec3b>(i, j)[1];
         //To read the value of first channel.Here the green channel is first channel//
         cout << "Value of pixel of green channel" << "(" << i << ","
            << j << ")" << "=" << blue_Channel << endl;//showing the values in console window//
      }
   }
   //End of for loop to read pixel values of green channel//
   //Beginning of for loop to read pixel values of red channel//
   for (int i = 0; i < color_image_Matrix.rows; i++)//loop for rows// {
      for (int j = 0; j < color_image_Matrix.cols; j++)//loop for columns// {
         red_Channel = color_image_Matrix.at<Vec3b>(i, j)[2];
         //To read the value of first channel.Here the red channel is first channel//
         cout << "Value of pixel of red channel" << "(" << i << "," <<
            j << ")" << "=" << blue_Channel << endl; //showing the values in console window//
      }
   }
   //End of for loop to read pixel values of red channel//
   if (waitKey(0)==27);
      cout << "Image read successfully…!";
      return 0;
}

輸出

Image read successfully...

此程式需要幾分鐘才能執行。它讀取不同通道中的每個畫素值。這就是為什麼它需要幾分鐘才能顯示完整結果的原因。

更新於: 2021年5月3日

701 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

立即開始
廣告