Tuesday 16 June 2015

Opencv and Matlab image structure

I need to use opencv to read an image but process it in a C++ function written for Matlab mex. Therefore, the opencv mat structure needs to be transformed to the Matlab image structure. A naive way would be to allocating memory for a new image space with Matlab layout, and then copy the pixel values one by one. But it is reported here that this takes 50 ms!

To speed up the process, we should dig into the data structures and see what is different. According to this blog, Mat.data gives a pointer referring to the original data matrix, which is a 1D array with values arranged as b1,g1,r1,b2,g2,r2,… in the BGR format. To get pixels in the i th row and j th col, simply use
b = image[img.step * j + i ] ;
g = image[img.step * j + i + 1];
r = image[img.step * j + i + 2];

It is a different story for Matlab, based on the official documentation here
In array C, each element of C specifies the color for one pixel of the image. The resulting image is an m-by-n grid of pixels where m is the number of columns and n is the number of rows in C. This means that the image is stored column first, instead of row first. Also, the RGB values are stored as [j, i, r], [j, i, g], [j, i, b] in three dimensions. 



No comments:

Post a Comment