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

南楼画角 提交于 2019-11-30 23:10:43

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<uchar>(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<uchar>(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<class T>
T getValueAs(int i) { return static_cast<T>(i); }

typedef unsigned char uchar;

int main() {
    int i = 56;
    std::cout << getValueAs<uchar>(i) << " " << (int)getValueAs<uchar>(i);
}

Simply, because although uchar is an integer type, the stream operation << prints the character it represents, not a sequence of digits. Passing the type int you get a different overload of that same stream operation, which does print a sequence of digits.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!