Mat类型的一些操作

(1)自定义赋值,kernel = [ 1 ,2 ,3 ]:

Mat kernel = (Mat_<int>(1,3) << 1 ,2 ,3 );

(2)合并矩阵,类似matlab中 A = [ B ; C ];A = [ B C ]之类的操作:

//A = [ B ; C ]
//B = [ 1 ,2 ,3 ] ; C = [ 3 ,2 ,1 ] ; A = [ 1 ,2 ,3 ;3 ,2 ,1 ]
vconcat( B ,C , A );

//A = [ B  C ]
//B = [ 1 ,2 ,3 ] ; C = [ 3 ,2 ,1 ] ; A = [ 1 ,2 ,3 ,3 ,2 ,1 ]
hconcat( B ,C ,A );

//支持vector
vector<Mat> vec;
vec.push_back(B);
vec.push_back(C);
vconcat( vec, A );

(3)按像素读写

Mat A( 3 ,3 , CV_32FC1 );
A.at<float>(0 ,0) = value;   //at()模版函数,需要指定类型,参数为Point(x,y)

(4)图像类型转换,如CV_8UC1转CV_32FC1等,直接使用normalize()

Mat A = Mat( 3 ,3 ,CV_8UC1 );
normalize(A ,A ,1.0 ,0.0 ,NORM_MINMAX ,CV_32FC1);

//normalize(InputArray src ,OutputArray dst ,double alpha ,double
// beta ,int norm_type ,int dtype , InputArray mask)
//alpha 为最大值,beta 为最小值,dtype=-1表示原图像深度

(5)XML,YAML文件读写,用opencv自带类FileStorage

FileStorage file( "xxx.xml" , FileStorage::WRITE);
//FileStorage file;
//file.open( "xxx.xml" , FileStorage::WRITE);

file << "matrix" << (Mat_<float>(3,3) << 1,2,3,4,5,6,7,8,9);
file.release();     //关闭xml

FileStorage file( "xxx.xml" , FileStorage::READ);
Mat A = (Mat)file[ "matrix" ]; // A = [ 1 ,2 ,3 ; 4 ,5 ,6 ; 7 ,8 ,9 ]
//file["matrix"] >> A;

//读写vector类型
file << "strings" << "[";       //以 [ 开始
file << "123" << "234" << "345"; 
file << "]";              //关闭序列,vector = [ 123 , 234 , 345 ]

FileNode node = file["strings"];
auto iter = node.begin();     //迭代器循环

//读写map类型,用迭代器循环
file << "mapping" << "{";      //以 { 开始
file << "one"  << 1 << "two" << 2;
file << "}";

    原文作者:MisakaMikotoSAM
    原文地址: https://www.jianshu.com/p/b00127d0c20f
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞