0
void onMouse(int event, int x, int y, int flags, void* param)
{
//  Mat *pMat = (Mat*)param;
//  Mat image = Mat(*pMat);
    Mat image(512, 512, CV_8UC3, Scalar(255, 255, 255));
    Vec3b planes = image.at<Vec3b>(y, x);

    switch (event)
    {
    case EVENT_LBUTTONDOWN:
        cout << "(" << y << "," << x << ") = (" << planes.val[0] + '0'<< ", " << planes.val[1] + '0' << ", " << planes.val[2] + '0' << ")" << endl;
    }
}

I tried to get each value of RGB colors, but the appropriate value didn't show up. Instead, it showed up like some characters such as '↓' '┐' these things. Therefore, I simply add '0' to the end of the variable planes.val[0], so the result number came out, but the problem is the number went up to 303(instead of 255).

And by applying some unexpected step, I finally get a right value.

I add -'0' to the end, (so it is => planes.val[0]+'0'-'0' )(instead of planes.val[0] or planes.val[0]+'0') and now I can get the right value.

But, I don't know why this happens.

underscore_d
  • 6,309
  • 3
  • 38
  • 64
Sean
  • 301
  • 1
  • 2
  • 10
  • 3
    What happens is the integral promotion of `char` caused by `+` operator which results in an `int`. You may as well do `static_cast(planes.val[0])` or `+planes.val[0]`. – milleniumbug Oct 26 '17 at 13:43
  • If you do `+0` instead of `+'0'` you would not need to subtract anything – Slava Oct 26 '17 at 13:45
  • @milleniumbug thank you! now I know the reason. – Sean Oct 26 '17 at 13:59

2 Answers2

4

Vec3b is basically an array of 3 uchar (unsigned char). It displays it as a weird character, since a number as an uchar is a character (look at ascii table). The character '0' is the number 48 (48+255 = 303) so the 303 comes from there. Finally you substracted that number, and pow you get back 255... To display it in cout as a number the correct was is to cast it to int.

The code will look like:

cout << "(" << y << "," << x << ") = (" << static_cast<int>(planes.val[0]) << ", " << static_cast<int>(planes.val[1]) << ", " << static_cast<int>(planes.val[2])<< ")" << endl;

Just to add a little bit more. As milleniunbug said, what happens behind it is call integral promotion, and that is why you get displayable numbers... however this may give undesirable behavior if used in other case that it is not printing.

api55
  • 11,070
  • 4
  • 41
  • 57
3

Simply print the values using:

static_cast<unsigned>(planes.val[0])

Without it they are interpreted as chars

Daniel Trugman
  • 8,186
  • 20
  • 41