Problems with pixel points in image processing: unsigned char and Char

Source: Internet
Author: User
Tags arithmetic

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.