OpenCV documentation says that “uchar” is “unsigned integer” datatype. How?

前端 未结 2 531
一个人的身影
一个人的身影 2021-01-06 02:28

I got confused with the openCV documentation mentioned here.

As per the documentation, if i create an image with \"uchar\", the pixels of that image

2条回答
  •  北海茫月
    2021-01-06 02:49

    If you try to find definition of uchar (which is pressing F12 if you are using Visual Studio), then you'll end up in OpenCV's core/types_c.h:

    #ifndef HAVE_IPL
       typedef unsigned char uchar;
       typedef unsigned short ushort;
    #endif
    

    which standard and reasonable way of defining unsigned integral 8bit type (i.e. "8-bit unsigned integer") since standard ensures that char always requires exactly 1 byte of memory. This means that:

    cout << "  " << image.at(i,j);
    

    uses the overloaded operator<< that takes unsigned char (char), which prints passed value in form of character, not number.

    Explicit cast, however, causes another version of << to be used:

    cout << "  " << (int) image.at(i,j);
    

    and therefore it prints numbers. This issue is not related to the fact that you are using OpenCV at all.


    Simple example:

    char           c = 56; // equivalent to c = '8'
    unsigned char uc = 56;
    int            i = 56;
    std::cout << c << " " << uc << " " << i;
    

    outputs: 8 8 56

    And if the fact that it is a template confuses you, then this behavior is also equivalent to:

    template
    T getValueAs(int i) { return static_cast(i); }
    
    typedef unsigned char uchar;
    
    int main() {
        int i = 56;
        std::cout << getValueAs(i) << " " << (int)getValueAs(i);
    }
    

提交回复
热议问题