392 Intermediate C Programming
the new color. Let x and y be the old and the new colors, then a linear equation has two
coefficients: a and b.
y = ax + b (23.1)
Suppose M and m are the original minimum and the maximum values. They should
become 0 and 255 after the scaling. The following two equations are used to determine the
correct values for a and b.
0 = am + b
255 = aM + b
(23.2)
a =
255
M − m
and b = −
255m
M − m
(23.3)
The code listing below implements this color equalization scheme.
// bm p equalize . c1
#in clude " bmpfunc . h"2
void BMP_eq ualize ( B MP_Image * img )3
{4
int pxl ;5
unsigned char redmin = 255;6
unsigned char redmax = 0;7
unsigned char greenmin = 255;8
unsigned char greenmax = 0;9
unsigned char bluemin = 255;10
unsigned char bluemax = 0;11
// find the maximum and the minimum values of each color12
for ( pxl = 0; pxl < ( img -> data_ size ) ; pxl += 3)13
{14
unsigned char red = img -> data [ pxl + 2];15
unsigned char green = img -> data [ pxl + 1];16
unsigned char blue = img -> data [ pxl ];17
i f ( redmin > red ) { redmin = red ; }18
i f ( redmax < red ) { redmax = red ; }19
i f ( greenmi n > green ) { greenmin = green ; }20
i f ( greenma x < green ) { greenmax = green ; }21
i f ( bluemin > blue ) { bluemin = blue ; }22
i f ( bluemax < blue ) { bluemax = blue ; }23
}24
// calc ulate the scaling factors25
// max and min must be d ifferent to prevent26
// divided by zero error27
double r edscale = 1.0;28
double greensca l e = 1.0;29
double bluescale = 1.0;30
i f ( redmax > redmin )31
{32
redscale = 255.0 / ( redmax - redmin ) ;33
}34
i f ( greenma x > green m in )35
{36