388 Intermediate C Programming
23.2.1 Image Pixels and Colors
The image’s colors are stored in the data attribute. Every pixel uses three consecutive
bytes. For example, the first pixel uses the first three bytes: data[0], data[1], and data[2].
The second pixel uses data[3], data[4], and data[5]. Among the three elements, the first
byte represents blue, the second represents green, and the third represents red. Thus, the
order is actually BGR (not RGB).
Each data element is a byte and has a value between 0 and 255 (inclusive). Larger values
mean brighter colors. If a given pixel is pure blue, then the first element is non-zero and the
other two elements are zero. If a given pixel is pure red, then the red element is non-zero
and the other two elements are both zero. If all three elements are 255, then the pixel is the
brightest white. If all three elements are 0, then the pixel is black.
Even though an image is two-dimensional, data stores the pixels in a one-dimensional
array. This is the most common method because managing one-dimensional arrays is simpler
than managing two-dimensional arrays.
Each pixel has an (x, y) coordinate. In high school geometry, the origin (0, 0) is the
lower left corner of a graph, the X coordinate increases to the right, and the Y coordinate
increases upward. Computer graphics is generally done with a different coordinate system.
The origin (0, 0) is the top left corner of the image. The X coordinate increases to the
right, and the Y coordinate increases downward. In this coordinate system, we can access
the color values of pixels (x, y) by calculating their index in data. The formula is:
• 3 × (y × width + x) for blue
• 3 × (y × width + x) + 1 for green
• 3 × (y × width + x) + 2 for red
23.2.2 Processing Functions
The following listing is a header file that declares the functions we will consider in the
rest of this chapter.
// bmpfunc .h1
#i f n d e f _BMPFUNC _H_2
#d ef in e _BMP F UNC_H_3
#in clude " bmpimage .h "4
// keep only one color ,5
// clr = 2, keep red6
// clr = 1, keep green7
// clr = 0, keep blue8
void BMP_color ( B M P_Image * image , in t clr ) ;9
// Invert all of the image data in a BMP image10
// ( value = 255 - value )11
void BMP_inve r t ( B MP_Image * image );12
// calc ulate ver t ical edges using the given threshold value13
void B MP_edge ( BMP_Image * image , i n t thrshd );14
// convert an RGB image to a gray - level image15
void B MP_gray ( BMP_Image * image );16
// calc ulate the h istogram of each color17
void BMP_h istogra m ( BMP_Image * image );18
// make a chec k erboard19
void BMP_che cker ( BMP_Im age * image );20
// mix the colors21
void BMP_mix ( BMP_Image * image );22