如何使用C++在OpenCV中获取特定像素的值?
要读取特定像素的值,我们可以使用“at”方法或“直接访问”方法。在这里,我们将学习这两种方法。
让我们从“at”方法开始。下面的程序读取RGB图像中(10, 29)位置的像素值。
示例
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main() {
Mat image;//taking an image matrix//
image = imread("sky.jpg");//loading an image//
int x = image.at<Vec3b>(10, 29)[0];//getting the pixel values//
int y = image.at<Vec3b>(10, 29)[1];//getting the pixel values//
int z = image.at<Vec3b>(10, 29)[2];//getting the pixel values//
cout << "Value of blue channel:" << x << endl;//showing the pixel values//
cout << "Value of green channel:" << x << endl;//showing the pixel values//
cout << "Value of red channel:" << x << endl;//showing the pixel values//
system("pause");//pause the system to visualize the result//
return 0;
}输出

程序的结果将显示在控制台窗口中。在这里,我们使用下面的三行代码获取三个不同通道的像素值。
int x = image.at<Vec3b>(10, 29)[0]; int y = image.at<Vec3b>(10, 29)[1]; int z = image.at<Vec3b>(10, 29)[2];
第一行读取第一个通道(蓝色)中(10, 29)位置的像素值,并将值存储在变量'x'中。第二行和第三行分别存储第2个和第3个通道的值。现在让我们学习如何使用“直接访问”方法读取像素值。
下面的程序直接读取(10, 29)位置的像素值:
示例
#include<iostream>
#include<opencv2/highgui/highgui.hpp>
using namespace std;
using namespace cv;
int main() {
Mat_<Vec3b>image;//taking an image matrix//
image = imread("sky.jpg");//loading an image//
Vec3b x = image(10, 29);//getting the pixel values//
cout << x << endl;//showing the pixel values//
system("pause");//pause the system to visualize the result//
return 0;
}输出

广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP