如何使用 C++ 从 OpenCV 中的多通道图像中读取像素值?
我们已经声明了三个名为“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 firstchannel.Herethe 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 firstchannel.Herethe 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 firstchannel.Herethe 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...
该程序需要几分钟才能运行。它从不同的通道读取每个像素值。这就是为什么需要几分钟才能显示完整结果的原因。
以上是 如何使用 C++ 从 OpenCV 中的多通道图像中读取像素值? 的全部内容, 来源链接: utcz.com/z/338772.html