0
点赞
收藏
分享

微信扫一扫

OpenCV Mat类型的遍历与访问

辰鑫chenxin 2022-03-30 阅读 54
c++opencv

1、指针遍历

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include<vector>
#include<Eigen/Core>
#include <corecrt_math_defines.h>
using namespace std;
using namespace cv;

int main()
{
	//生成一个3*4的矩阵
	Mat M = Mat::eye(3,4,CV_8UC1);
	cout << "M=\n" << M << endl;
	//访问第1行第1列的元素(使用指针访问):显示时需要强转
	uchar *sample11 = M.ptr<uchar>(0);
	cout << "强转(1,1)=" << (int)sample11[0] << endl;
	cout << "不强转(1,1)=" <<  sample11[0] << endl;
	//访问第2行第2列的元素(直接访问):在访问时用double/int接收就已经强转
	double sample22 = M.ptr<uchar>(1)[1];
	cout << "(2,2)=" << sample22 << endl;
	cv::waitKey(0);
	return 0;
}

2、step地址遍历

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include<vector>
#include<Eigen/Core>
#include <corecrt_math_defines.h>
using namespace std;
using namespace cv;

int main()
{
	//生成一个3*4的矩阵
	Mat M = Mat::eye(3,4,CV_8UC1);
	cout << "M=\n" << M << endl;
	//访问第1行第1列的元素
	double sample11 = *(M.data+M.step[0]*0+M.step[1]*0);
	cout << "(1,1)=" << sample11 << endl;
	//访问第2行第2列的元素
	double sample22 = *(M.data+M.step[0]*1+M.step[1]*1);
	cout << "(2,2)=" << sample22 << endl;
	cout << "M.step[0]="<<M.step[0] << endl;
	cout << "M.step[1]="<<M.step[1] << endl;
	cv::waitKey(0);
	return 0;
}

 3、动态地址at遍历

单通道:M.at<uchar>(row,col)
三通道:M.at<Vec3b>(row,col)[0]//B通道
       M.at<Vec3b>(row,col)[1]//G通道
       M.at<Vec3b>(row,col)[0]//R通道

#include <iostream>
#include <opencv2/core.hpp>
#include <opencv2/highgui.hpp>
#include <opencv2/imgproc.hpp>
#include<vector>
#include<Eigen/Core>
#include <corecrt_math_defines.h>
using namespace std;
using namespace cv;

int main()
{
	//生成一个3*4的矩阵
	Mat M = Mat::eye(3,4,CV_8UC1);
	M.at<uchar>(2, 3) = 9;
	cout << "M=\n" << M << endl;
	//访问第1行第1列的元素
	double sample11 = M.at<uchar>(0,0);
	cout << "(1,1)=" << sample11 << endl;
	//访问第2行第2列的元素
	double sample22 = M.at<uchar>(1,1);
	cout << "(2,2)=" << sample22 << endl;
	//访问第3行第4列的元素
	double sample34 = M.at<uchar>(2,3);
	cout << "(3,4)=" << sample34 << endl;
	cv::waitKey(0);
	return 0;
}

举报

相关推荐

0 条评论