> 文章列表 > 【opencv】图像数字化——认识OpenCV中的Mat类(4 访问单通道Mat对象中的值)

【opencv】图像数字化——认识OpenCV中的Mat类(4 访问单通道Mat对象中的值)

【opencv】图像数字化——认识OpenCV中的Mat类(4 访问单通道Mat对象中的值)

4 访问单通道Mat对象中的值

4.1使用成员函数at()

  • 格式:m.at(r,c),访问第r行c列
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{//构造矩阵Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);cout << m << endl;for (int r = 0; r < m.rows; r++) {for (int c = 0; c < m.cols; c++) {cout << m.at<int>(r, c) << ",";}}cout << endl;return 0;
}

在这里插入图片描述

4.2使用point类和成员函数at()

  • 格式:m.at(Point(c,r));
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{//构造矩阵Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);cout << m << endl;for (int r = 0; r < m.rows; r++) {for (int c = 0; c < m.cols; c++) {cout << m.at<int>(Point(c, r)) << ",";}cout << endl;}return 0;
}

在这里插入图片描述

4.3使用成员函数ptr()

  • 通过成员函数ptr获得指向每一行首地址的指针
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{//构造矩阵Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);cout << m << endl;for (int r = 0; r < m.rows; r++) {const int* ptr = m.ptr<int>(r);//打印第r行的所有值for (int c = 0; c < m.cols; c++) {cout << ptr[c] << ",";}cout << endl;}return 0;
}

在这里插入图片描述

4.4使用成员函数isContinuous()和ptr()

  • isContinuous()返回true代表行与行之间是连续存储的,那么所有的值都是连续存储的
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{//构造矩阵Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);cout << m << endl;if (m.isContinuous()) {//得到矩阵第一个值得地址int* ptr = m.ptr<int>(0);for(int n=0;n<m.rows*m.cols;n++){cout << ptr[n] << ",";}   cout << endl;}  return 0;
}

在这里插入图片描述

4.5使用成员变量step和data

  • step[0]代表每一行所占字节数
  • step[1]代表每一个数值所占字节数
  • data是指向第一个数值的指针
  • 访问int类型的单通道矩阵第r行第c列的值
  • 格式:((int)(m.data+m.step[0]r+cm.step[1]))
#include <opencv2/core/core.hpp>  
#include<iostream>  
using namespace std;
using namespace cv;
int main()
{//构造矩阵Mat m = (Mat_<int>(3, 2) << 1, 2, 3, 4, 5, 6);cout << m << endl;for (int r = 0; r < m.rows; r++) {for (int c = 0; c < m.cols; c++) {cout << *((int*)(m.data + m.step[0] * r + c * m.step[1])) << ",";}} cout << endl;return 0;
}

在这里插入图片描述