實驗環境:VS2010 + OpenCV2.4.9.0
參考手冊:The OpenCV Tutorials, Release 2.4.9.0
Mat:OpenCV中圖像的基本容器,自OpenCV2.0之後的新功能,正在逐漸代替IplImage和CvMat。相比於IplImage和CvMat,Mat型側重於計算,數學性較高,OpenCV對Mat類型的計算也進行了優化。而CvMat和IplImage類型更側重於“圖像”,OpenCV對其中的圖像操作(縮放、單通道提取、圖像閾值操作等)進行了優化。在OpenCV2.0之前,OpenCV是完全用C實現的,但是,IplImage類型與CvMat類型的關係類似於面向對象中的繼承關係。實際上,CvMat之上還有一個更抽象的基類----CvArr,這在源代碼中會常見。根據參考手冊看來,Mat類表示一個 n 維的密集數值單通道或多通道數組。它可以用於存儲實數或複數值的向量和矩陣、灰度或彩色圖像、體素、向量場、點雲、張量、直方圖 (儘管較高維的直方圖存儲在SparseMat可能更好)。大概介紹至此,下面學習一些最基本用法:都以main函數的形式列出,頭文件略。
1、Mat矩陣的建立
int main(int argc,char** argv)
{
Mat M(2,2,CV_8UC3,Scalar(0,0,255));
//Mat M;
//M.create(4,4,CV_8UC2);
cout << "M = " << endl <<" " << M << endl << endl;
system("pause");
return 0;
}
//Define some matrices
int main(int argc,char** argv)
{
Mat E = Mat::eye(4,4,CV_64F);
cout << "E = " << endl <<" " << E<< endl << endl;
Mat ON = Mat::ones(4,4,CV_32F);
cout << "ON = " << endl <<" " << ON << endl << endl;
Mat Z = Mat::zeros(3,3,CV_8UC1);
cout << "Z = " << endl << " " << Z << endl << endl;
system("pause");
return 0;
}
//For small matrices,may use comma separated initializers
int main(int argc,char** argv)
{
Mat C = (Mat_<double>(3,3)<<0,-1,0,-1,5,-1,0,-1,0);
cout << "C = " << endl <<" " << C<< endl << endl;
//Create a new header for an existing Mat object and clone() or copyTo() it
Mat rowClone = C.row(1).clone();
cout << "rowClone = " << endl <<" " << rowClone << endl << endl;
Mat rowCopy;
C.row(1).copyTo(rowCopy);
cout << "rowCopy = " << endl <<" " << rowCopy << endl << endl;
system("pause");
return 0;
}
//random function
int main(int argc,char** argv)
{
Mat R = Mat(3,2,CV_8UC3);
randu(R,Scalar::all(0),Scalar::all(255));
cout << "R = " << endl <<" " << R << endl << endl;
system("pause");
return 0;
}
5、C++容器和Mat
int main(int argc,char** argv)
{
//2D Point
Point2f P(5,1);
cout << "Point (2D) = " << P << endl << endl;
//3D Point
Point3f P3f(2,6,7);
cout << "Point (3D) = " << P3f << endl << endl;
//std::vector via cv::Mat
vector<float> v;
v.push_back((float)CV_PI);
v.push_back(2);
v.push_back(3.01f);
cout << "Vector of float via Mat = " << Mat(v) << endl << endl;
//std::vector of points
vector<Point2f> vPoints(20);
for(size_t i = 0;i < vPoints.size();i++)
vPoints[i] = Point2f((float)(i*5),(float)(i % 7));
cout << "A vector of 2D Points = " << vPoints << endl << endl;
system("pause");
return 0;
}