OpenCV matrix types

OpenCV is a framework for image processing, machine learning and related convenience processing of images and other data. One of the central data structures is the famous matrix, the Mat type. It can store multiple channel data, different color spaces (?), sparse and dense representations and who knows what else. Bref, it’s a big and complicated piece ¬†of software.

When using the matrices created, manipulated and returned by OpenCV’s functions, all is fine and simple. The trouble comes when you need to get your data in and out of the Mat object. There are multiple types of data that can be stored in the Mat object. You are all familiar with “CV_8U”, “CV_16U” etc. How do you know what type is stored in the matrix object after some long mangling in OpenCV internals? Is it int? Or is it unsigned int? Or may be even float or double?

Fortunately, you have access to a Mat class function type() which will return you a code. The code is a mere integer. See the table with correspondences:

CV_8U

0

8-bit unsigned integer (uchar)

CV_8S

1

8-bit signed integer (schar)

CV_16U

2

16-bit unsigned integer (ushort)

CV_16S

3

16-bit signed integer (short)

CV_32S

4

32-bit signed integer (int)

CV_32F

5

32-bit floating point number (float)

CV_64F

6

64-bit floating point number (double)

CV_USRTYPE1

7

User-defined type

 

When creating a Mat object from int, float, double or any other C/C++ type, you can use a convenience interface DataType. For example, you are manipulating a double type array data in your C/C++ code. Suppose that now you want to put that in a Mat object. Instead of guessing which CV_*** choose, do the following and the compiler will determine what to take:

Mat A = Mat( nRows, nCols, DataType<double>::type, data );

That’s all folks.

This entry was posted in Uncategorized. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *