Ask Your Question
0

Accessing each pixel of a Mat .at vs pointer arithmetic gives differnet result

asked 2016-05-13 12:42:57 -0600

carobnodrvo gravatar image

updated 2016-05-13 12:52:45 -0600

Today I stumbled across this (for me) weird thing, namely when I run this code

m.convertTo(tmp_mat, CV_32FC3, 1./255);
cvtColor(tmp_mat, tmp_mat, CV_RGB2XYZ, 3);
split(tmp_mat, xyz_channels);

y_channel = xyz_channels[1].clone();

int i,j;
uint8_t* p = y_channel.data;
for( i = 0; i < y_channel.rows; ++i)
{
    for ( j = 0; j < y_channel.cols; ++j)
    {
       std::cout << y_channel.at<float>(i,j) << std::endl;
       std::cout << saturate_cast<float>(p[i*y_channel.cols + j]) << std::endl;
    }
}

this is the output I get

0.984314
123
0.984314
63
0.984314
254
0.984314
251
0.984314
123
0.984314
63
0.984314
254
0.984314
251
0.984314
123
0.984314
63
...

So now I am confused - shouldn't it be same?

edit retag flag offensive close merge delete

Comments

CV_32FC3 implies mat.at<float>(r,c) , not mat.at<double>(r,c) (which would require CV_64F3C)

berak gravatar imageberak ( 2016-05-13 12:49:37 -0600 )edit

@berak Thanks for the hint but problem is same... Please check edited question.

carobnodrvo gravatar imagecarobnodrvo ( 2016-05-13 12:53:08 -0600 )edit

2 answers

Sort by ยป oldest newest most voted
1

answered 2016-05-13 22:05:07 -0600

updated 2016-05-14 03:11:17 -0600

You have to change the line:

 uint8_t* p = y_channel.data;

to:

float * p = (float*)y_channel.data;

and no need to use saturate_cast<>, just do like this:

std::cout << p[i*y_channel.cols + j] << std::endl;
edit flag offensive delete link more
1

answered 2016-05-13 16:09:10 -0600

Tetragramm gravatar image

You have p as type uint8_t, when the data inside is of type float. You should declare it as a pointer of type float and cast the pointer you get from .data

As it is, you are accessing the 8 bits as a uint8, then converting that to a float, which is of course, wrong. You need to access the full 32 bits as a float.

edit flag offensive delete link more

Question Tools

1 follower

Stats

Asked: 2016-05-13 12:42:57 -0600

Seen: 332 times

Last updated: May 14 '16