1. 調用Mat的構造函數或者create函數,如:
// make a 7x7 complex matrix filled with 1+3j.
Mat M(7,7,CV_32FC2,Scalar(1,3));
// and now turn M to a 100x60 15-channel 8-bit matrix.
// The old content will be deallocated
M.create(100,60,CV_8UC(15));
2. 調用拷貝構造函數或賦值操作符。注意,調用拷貝構造函數或賦值操作符時,只會拷貝Mat的頭部,並增加reference count,並不會真正拷貝數據。如果要進行數據拷貝,可以調用clone或copyTo函數。
Mat M1(M);
Mat M2 = M;
Mat M3 = M.clone();
Mat M4;
M.copyTo(M4);
這裏的M1, M2與M共用同一處數據;而M3,M4是拷貝了M的數據。
3. 給user-allocated數據增加頭部信息。如:
void process_video_frame(const unsigned char* pixels,
int width, int height, int step)
{
Mat img(height, width, CV_8UC3, pixels, step);
GaussianBlur(img, img, Size(7,7), 1.5, 1.5);
}
另外,可以調用Mat::operator CvMat() 和Mat::operator IplImage()將CvMat和IplImage轉換成Mat:
IplImage* img = cvLoadImage("greatwave.jpg", 1);
Mat mtx(img); // convert IplImage* -> Mat
CvMat oldmat = mtx; // convert Mat -> CvMat
參考:
http://docs.opencv.org/modules/core/doc/basic_structures.html#mat