Pixel problems in image processing: unsigned char and Char

Source: Internet
Author: User
Tags arithmetic

Before doing image processing, has been not too concerned about this problem, the image of each pixel point of gray values, always think that char can also, unsigned char can also be. Although they are all 8 bits, the range of 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;
unsigned char g;
One unsigned char b;
}pixel_ut;

If you don't use the above definition for arithmetic operations on pixels, but only for assignment operations, OK, no problem. But as soon as arithmetic is done, the hidden bugs come along.

Consider the following:
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 are equal, then you are wrong, they are not only unequal, but they are far apart.  
Ans0 = -254; 
ans1 = 2; 

The reason is: 
When we assign 129 to PIX2.R, because the type of PIX2.R is char, the PIX2.R The value is not 129, but  
-127. So when we do the operation, there is an error.

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.