The challenge for this month’s Exercise is to fill a cup without overflowing it. That cup is an unsigned char value, which goes only to 255 maximum. If your goal is increase the value of an unsigned char variable by 10 percent, any value over 255 - (255/10)
, or 220
, must be set to 255.
Obviously, some sore of if test is required to ensure that you don’t overflow the pixel value beyond 255. For my solution, I used the tertiary operator, ?:
. Here’s a sample statement:
pixels[i].r = pixels[i].r+br > 255 ? 255 : pixels[i].r+br
Variable pixels[i].r
represents the red pixel of element i
in the pixels
structure array. Its value is set to its current value plus the value of br
, calculated as:
br = 255/10;
The first part of the tertiary operator compares the result of adding 10 percent to the pixel’s value with 255: pixels[i].r+br>255
. This operation does not add br
to the pixel’s value; it’s only compared.
After the ?
operator you see the TRUE and FALSE conditions, respectively. If the result of adding br
to the pixel’s value is greater than 255, the value 255 is assigned to pixels[i].r
. That value fits into the range for an unsigned char variable — no overflow.
If the result of adding br
to the pixel’s value is less than 255, meaning the comparison is false, the value of br
is added to the pixel’s value and assigned as the pixel’s value.
The net effect of both operations is to either maximize the pixel’s value to 255 or increase it by 10 percent. This process is repeated for the blue and green pixel members of the pixels[]
structure array.
Click here to view my code. You’ll see that I used the direct result of the tertiary operator instead of assigning the values to the structure array.
Here’s output from a sample run:
247 63 29 -> 255 88 54
251 100 33 -> 255 125 58
250 146 38 -> 255 171 63
252 196 46 -> 255 221 71
252 223 51 -> 255 248 76
250 225 56 -> 255 250 81
196 225 53 -> 221 250 78
134 252 49 -> 159 255 74
66 221 48 -> 91 246 73
63 251 158 -> 88 255 183
60 253 233 -> 85 255 255
54 236 250 -> 79 255 255
35 181 249 -> 60 206 255
0 104 249 -> 25 129 255
0 54 251 -> 25 79 255
You don’t see any values greater than 255 in any of the columns, which means it worked.
Of course, the real test is to see how this solution succeeds graphically, as applied to an image. In Figure 1, I used the same equation from my solution in code that draws a highlight box around the sun in the sunset image.
Of course, you can see that the value 10 percent could be increased to further highlight the box. Also, this 10-percent effect might not work when the image is mostly white or saturated. Still, this was the optimal solution for the exercise I was given.
If your solution yields similar results, great! An if-else comparison also works. To be honest, the primary reason I chose the tertiary operator for my solution is that I could easily copy and paste it on a single line, which made it easier to manipulate all the rows and columns of pixels.