Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why unsigned char for RGB pixel data?

Tags:

c++

types

colors

i'm approaching c++ with some basic computer graphics.

pixels data is usually represented as :

unsigned char *pixels

and an unsigned char is good because is a value between 0 and 255 (256 = 2^8 because a char is 2 byte and 1 byte is 8 bit?). and this is good because in RGB color are represented with a number between 0 and 255.

but.. i understand this as a monchromatic image, in a normal image i have RGB, i would have 3 array of unsiged char, one for red, one for green, one for blue. something like:

unsigned char *pixels[3]

but i never found something similar for RGB pixels data

like image 431
nkint Avatar asked Apr 21 '11 10:04

nkint


2 Answers

RGB images are usually stored in interleaved order (R1, G1, B1, R2, G2, B2, ...), so one pointer (to R1) is enough.

This makes it a bit harder to address individual pixels: pixel with index N is stored at pixels[3*N+0], pixels[3*N+1] and pixels[3*N+2] instead of just red[N], green[N], blue[N].

However, this has the advantage of allowing faster access: less pointers lead to easier programs, improving their speed; interleaved order also makes memory caching more effective.

like image 136
anatolyg Avatar answered Oct 08 '22 02:10

anatolyg


unsigned char *pixels[3];

declares an array of three pointers to unsigned char. I'm not sure if that's what you wanted.

There are several different ways to represent pixels. The simplest is probably something like:

struct Pixel
{
    unsigned char red;
    unsigned char green;
    unsigned char blue;
};

But you may have to (or want to) conform to some external format. Another frequent possibility is to put all three colors in a uint32_t. Also, in some graphic systems, there may be a fourth element, and alpha, representing transparency.

like image 25
James Kanze Avatar answered Oct 08 '22 03:10

James Kanze