Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

The number of channels can be considered as a third dimension of your matrix; so you can treat it just like any other dimension (width, depth). With 3D Mat variables, your code becomes:

int dims[]={640,480,48};
Mat image2(3,dims,CV_32F);

Accessing an element (let's say, channel 30 of pixel 10,10):

float ch30=image2.at<float>(10,10,30);

As the matrix lines are continuous, you can also use line/element pointers. It's faster when you do an operation on the whole image or you want to access all the channels of a pixel. The following code gets a pointer to the line 10, the pixel (10,10) and the channel 30 of this pixel:

float *line10=(float*)image2.ptr(10);
float *pixel10=line10+10*image2.channels();
float ch30=pixel10[30];

The number of channels can be considered as a third dimension of your matrix; so you can treat it just like any other dimension (width, depth). With 3D Mat variables, your code becomes:

int dims[]={640,480,48};
Mat image2(3,dims,CV_32F);

Accessing an element (let's say, channel 30 of pixel 10,10):

float ch30=image2.at<float>(10,10,30);

As the matrix lines are continuous, you can also use line/element pointers. It's faster when you do an operation on the whole image or you want to access all the channels of a pixel. The following code gets a pointer to the line 10, the pixel (10,10) and the channel 30 of this pixel:

float *line10=(float*)image2.ptr(10);
float *pixel10=line10+10*image2.channels();
*pixel10=line10+10*image2.channels;
float ch30=pixel10[30];

[EDIT] Processing a whole image and a pixel in 3D Mat is pretty straightforward, but I put it here to give a complete answer (the multidimensional Mat isn't well detailed in the docs):

for(y=0;y<image2.rows;y++) {
    float *p=(float*)image2.ptr(y);
    for(pos=0;pos<image2.cols*image2.channels;pos++)
        p[pos]=1-p[pos];
}

And a pixel:

float *p=(float*)image2.ptr(y)+x*image2.channels;
for(c=0;c<image2.channels;c++) p[c]=1-p[c];