OpenCV访问Mat对象中数据时发生异常---Mat中的数据访问

来源:互联网 发布:mac搜索不到蓝牙音箱 编辑:程序博客网 时间:2024/06/07 07:24

至于OpenCV中Mat中的数据如何访问,详见http://blog.csdn.net/yang_xian521/article/details/7161335,这里有普通青年、文艺青年、暴力青年的说法。

常见问题,上代码:

// newLDA.cpp : 定义控制台应用程序的入口点。///*#include "stdafx.h"#include <cxcore.hpp>#include <vector>#include <iostream>#include "lda.h"using namespace std;using namespace cv;int main(void){double data[6][2]={{0,1},{0,2},{1,4},{8,0},{8,2},{9,4}};Mat dmat=Mat(6,2,CV_64FC1,data);int labels[6]={0, 0, 0, 1, 1, 1};Mat lmat=Mat(1,6,CV_32SC1,labels);//---------------------------------------------------------------for(int i=0;i<dmat.rows;i++){for(int j=0;j<dmat.cols;j++){cout<<dmat.ptr<double>(i)[j]<<" ";}cout<<endl;}cout<<"--------------------------------"<<endl;Mat envalue;Mat envector;int classNum=2;MyLDA(dmat, lmat); system("pause");return 0;}*/#include "stdafx.h"#include <cxcore.hpp>#include <iostream>using namespace std;using namespace cv;int main(void){double data[2][2]={{1.0,2.0},{3.0,4.0}};Mat dmat=Mat(2,2,CV_64FC1,data);for(int i=0;i<dmat.rows;i++){for(int j=0;j<dmat.cols;j++){cout<<dmat.at<float>(i,j)<<" ";}cout<<endl;}system("pause");return 0;}

cout<<dmat.at<float>(i,j)<<" ";
改为

cout<<dmat.at<double>(i,j)<<" ";

可见当矩阵类型为CV_64FC1时,Mat::at()会执行类型检查。


但是

#include "stdafx.h"#include <cxcore.hpp>#include <iostream>using namespace std;using namespace cv;int main(void){float data[2][2]={{1.0,2.0},{3.0,4.0}};Mat dmat=Mat(2,2,CV_32FC1,data);for(int i=0;i<dmat.rows;i++){for(int j=0;j<dmat.cols;j++){cout<<dmat.at<int>(i,j)<<" ";}cout<<endl;}system("pause");return 0;}



可见此时只是读取的结果不正确,但是并没有发生异常

cout<<dmat.at<int>(i,j)<<" ";
改为

cout<<dmat.at<double>(i,j)<<" ";
发生异常


故当矩阵为其他类型时(不是CV_64FC1),只要读取时使用的类型小于原数据的存储类型,就不会发生异常。

读取时的类型匹配至关重要。



0 0
原创粉丝点击