OpenCV文档说,“uchar”是“无符号整数”数据类型。怎么样? [英] OpenCV documentation says that "uchar" is "unsigned integer" datatype. How?
问题描述
我对openCV文档提到了 此处 。
I got confused with the openCV documentation mentioned here.
根据文档,如果我使用uchar ,该图片的像素可以存储无符号整数值,但如果我使用以下代码创建图片:
As per the documentation, if i create an image with "uchar", the pixels of that image can store unsigned integer values but if i create an image using the following code:
Mat image;
image = imread("someImage.jpg" , 0); // Read an image in "UCHAR" form
或执行
image.create(10, 10, CV_8UC1);
for(int i=0; i<image.rows; i++)
{
for(int j=o; j<image.cols; j++)
{
image.at<uchar>(i,j) = (uchar)255;
}
}
然后如果我尝试使用
cout<<" "<<image.at<uchar>(i,j);
然后我得到一些wierd结果在终端,但如果我使用下面的语句,然后我可以得到值in between 0-255。
then i get some wierd results at terminal but if i use the following statement then i can get the values inbetween 0-255.
cout<<" "<<(int)image.at<uchar>(i,j); // with TYPECAST
问题:为什么我需要做typecast
Question: Why do i need to do typecast to get print the values in range 0-255 if the image itself can store "unsigned integer" values.
推荐答案
如果您尝试使用无符号整数值,则可以打印范围为0-255的值。查找 uchar
的定义(如果使用的是Visual Studio,则为F12),那么最终会出现在OpenCV的 core / types_c.h :
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
这是标准和合理的定义无符号整数8位类型的方法>8位无符号整数),因为标准确保 char
总是需要1个字节的内存。这意味着:
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);
使用重载的运算符<<
需要 unsigned char
( char
),以字符形式打印传递的值,而不是数字。
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);
,因此它会打印数字。此问题与您使用OpenCV的事实无关。
and therefore it prints numbers. This issue is not related to the fact that you are using OpenCV at all.
简单示例:
char c = 56; // equivalent to c = '8'
unsigned char uc = 56;
int i = 56;
std::cout << c << " " << uc << " " << i;
输出: 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);
}
这篇关于OpenCV文档说,“uchar”是“无符号整数”数据类型。怎么样?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!