Mat in OpenCV

Mat is the basic C++ structure used in OpenCV to hold two and higher dimensional data. IplImage is the deprecated older C structure that was used for the same purpose earlier in OpenCV. The advantage of using Mat over IplImage is that it behaves like a proper C++ object, so it is easier to construct and is automatically destroyed at end of its scope.

  • Documentation about the Mat class can be found here. The declaration of the Mat class is in the modules/core/include/opencv2/core/mat.hpp file, as can be seen here.

  • The basic structure of Mat is simple:

class Mat
{
public:
    Mat();
    Mat(int rows, int cols, int type);
    Mat(Size size, int type);
    Mat(const Mat& m);
    Mat(int rows, int cols, int type, void* data, size_t step=AUTO_STEP);
    Mat(Size size, int type, void* data, size_t step=AUTO_STEP);

    int flags;
    int dims;
    int rows, cols;
    uchar* data;
};
  • To construct a Mat from existing array of data, without allocating its own buffer:
double darr[640*480];
cv::Mat dmat(480, 640, CV_64F, darr);
  • To construct a Mat from existing array of data, by making a copy to its own buffer:
double darr[640*480];
cv::Mat dmat(480, 640, CV_64F, darr);
cv::Mat cmat;
dmat.clone(cmat); // cmat has a separate copy of data now
  • To construct a Mat of a certain size and initialize each of its channels to a specific value:
const int frows = 480;
const int fcols = 640;
const cv::Scalar init_vals(10, 50, 255);

// Create a mat where B channel pixels are set to 10
// G channel pixels to 50 and R pixels to 255
cv::Mat fmat(frows, fcols, CV_8UC3, init_vals);
  • The data type of the elements of the image and the number of channels can be found using the depth and type methods as described here.

  • To set or get directly from the buffer of Mat:

// Set pixel 10 of CV_8UC3 mat to grey
cmat.data[3*10    ] = 40;
cmat.data[3*10 + 1] = 40;
cmat.data[3*10 + 2] = 40;
  • To convert between Mat and IplImage:
// To make Mat from IplImage*
// IplImage* img = cvCreateImage( ... );
cv::Mat mat(img);

// To make IplImage* from Mat
IplImage* img = new IplImage(mat);
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s