void scale_brightness( uint8_t array[],
unsigned int cols,
unsigned int rows,
double scale_factor )
{
for (int x = 0; x < (cols*rows); x++)
{
array[x] = round(scale_factor * (double)(array[x]));
if (array[x] > 255 )
{
array[x] = 255;
}
}
}
This function is supposed to multiply pixels by a scale factor, and it brightens or darkens an image based on what the factor is multiplied by. If the image that's multiplied is bigger than 255, the pixel gets thresholded to 255. I tried out the code and i put in scale_brightness (array, 256, 256, 2). This is supposed to multiply every pixel by 2 and so it should brighten up the image. But when I ran it, it turned all black, completely opposite of what it was supposed to do. I also tried doing 0, and it turned black. And any other color just gave me a dark gray. Would anybody be able to help me find out why it does that?
Your logic doesn't work because array[x]
cannot be more than 255, so if
body is never executed, and array[x]
is just truncated. Use additional double
value for calculation:
double d = round(scale_factor * (double)(array[x]));
if (d >= 255.0 )
{
array[x] = 255;
}
else
{
array[x] = (uint8_t)d;
}
Note that this loop can be effectively optimized by excluding floating point operations. Multiplication by double
factor can be replaced by multiplication by int
and shifting right.