opencv Pixel Access Pixel Access in Mat


Example

Individual pixel access in OpenCV Mat structure can be achieved in multiple ways. To understand how to access, it is better to learn the data types first.

Basic Structures explains the basic datatypes. Shortly, CV_<bit-depth>{U|S|F}C(<number_of_channels>) is the basic structure of a type. Along with that, it is important to understand Vec structures.

typedef Vec<type, channels> Vec< channels>< one char for the type>

where type is one of uchar, short, int, float, double and the characters for each type are b, s, i, f, d, respectively.

For example, Vec2b indicates an unsigned char vector of 2 channels.

Consider Mat mat(R,C,T) where R is #rows, C is #cols and T is type. Some examples for accessing the (i,j) coordinate of mat are:

2D:

If the type is CV_8U or CV_8UC1 ---- //they are alias
mat.at<uchar>(i,j) // --> This will give char value of index (i,j)
//If you want to obtain int value of it
(int)mat.at<uchar>(i,j)

If the type is CV_32F or CV_32FC1 ---- //they are alias
mat.at<float>(i,j) // --> This will give float value of index (i,j)

3D:

If the type is CV_8UC2 or CV_8UC3 or more channels
mat.at<Vec2b/Vec3b>(i,j)[k] // note that (k < #channels)
//If you want to obtain int value of it
(int)mat.at<uchar>(i,j)[k] 

If the type is CV_64FC2 or CV_64FC3 
mat.at<Vec2d/Vec3d>(i,j)[k] // note that k < #channels

Note that, it is very crucial to enter correct type in <...>, otherwise, you can have runtime error or unwanted results.