เราได้ประกาศตัวแปรสามตัวชื่อ - 'blue_Channel', 'green_channel' และ 'red_channel' เป้าหมายของตัวแปรเหล่านี้คือการบันทึกค่าพิกเซล เราใช้ตัวแปรเหล่านี้ใน 'for loops' จากนั้นเราก็ประกาศเมทริกซ์ชื่อ 'color_Image_Matrix'
ไวยากรณ์ของวิธีนี้คือ:
blue_Channel = color_image_Matrix.at<Vec3b>(i, j)[0];
เราใช้อิมเมจ BGR มันมีสามช่อง ช่องเหล่านี้รักษาลำดับเฉพาะ color_image_Matrix.at
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...
โปรแกรมนี้ใช้เวลาหลายนาทีในการทำงาน มันอ่านค่าแต่ละพิกเซลจากช่องต่างๆ นั่นเป็นเหตุผลที่ต้องใช้เวลาสองสามนาทีในการแสดงผลลัพธ์ทั้งหมด