Why “cout” works weird for “unsigned char”?

后端 未结 1 711
旧时难觅i
旧时难觅i 2020-12-04 04:22

I have the following code:

cvtColor (image, image, CV_BGRA2RGB);
Vec3b bottomRGB;
bottomRGB=image.at(821,1232);

When I display

相关标签:
1条回答
  • 2020-12-04 04:56

    As you have commented, the reason is that you use cout to print its content directly. Here I will try to explain to you why this will not work.

    cout << bottomRGB[0] << endl;
    

    Why "cout" works weird for "unsigned char"?

    It will not work because here bottomRGB[0] is a unsigned char (with value 218), cout actually will print some garbage value (or nothing) as it is just a non-printable ASCII character which is getting printed anyway. Note that ASCII character corresponding to 218 is non-printable. Check out here for the ASCII table.

    P.S. You can check whether bottomRGB[0] is printable or not using isprint() as:

    cout << isprint(bottomRGB[0]) << endl; // will print garbage value or nothing
    

    It will print 0 (or false) indicating the character is non-printable


    For your example, to make it work, you need to type cast it first before cout:

    cout << (int) bottomRGB[0] << endl; // correctly printed (218 for your example) 
    
    0 讨论(0)
提交回复
热议问题