In the past when doing image processing, has not been very concerned about this problem, the image of each pixel gray value, always think of char can also, unsigned char can also. Although they are all 8 bits, the range of the numbers represented is not the same: char: -128~127, unsigned char:0~255. It is clear that unsigned char is the right choice.
You can define this: 1 struct {
2 char R;
3 char g;
4 char b;
5}pixel_t;
6
You can also define this:
8 struct {
9 unsigned char R;
Ten unsigned char g;
One unsigned char b;
}pixel_ut;
If you do not use the above definition to perform arithmetic operations on pixels, but only to perform assignment operations, OK, no problem. But once the arithmetic operation is done, the hidden bug comes along.
Consider the following scenario:
2 struct pixel_t pix1;
3 struct pixel_t pix2;
4 struct pixel_ut pix3;
5 struct pixel_ut pix4;
6
7 int ans0, ans1;
8
9 PIX1.R = 127;
Ten PIX2.R = 129;
One
PIX3.R = 127;
PIX4.R = 129;
+
Ans0 = PIX2.R-PIX1.R;//ans0 =?
ans1 = pix4.r-pix3.r;//ans1 =?
If you think Ans0 and ans1 values are equal, then you're wrong, they're not only unequal, but they are far apart.
Ans0 = -254;
ans1 = 2;
Because:
When we assign a value of 129 to PIX2.R, because the type of PIX2.R is char, the PIX2.R The value is not 129, but
-127. So there was an error when we were doing the operation.