Skip to main content

Section 26.1 Using Decisions with Images

In Chapter 21 we modified images in various ways by changing every pixel. But what if we don’t want to change every single pixel? Maybe we want to change the French flag (left image below), into the flag of Chad (right image):
Figure 26.1.1. French flag
Figure 26.1.2. Chadian flag
To do this, we need to change just the white pixels in the image and make them yellow. This means we need a way to answer the question “Is this pixel white?”. A pure white pixel has red, green, and blue values all of 255. A not-quite-pure white may not have 255 for each of the three values, but they will all be high, and they will all be very similar to each other. In comparison, a blue pixel is going to have a high blue value and low red and green (potentially 0 for a “perfect” blue). A red pixel will have a high red value and low blue and green ones.
So in general, to find a white pixel we could look for something where red > 250 and green > 250 and blue > 250. 250 is not always going to be the right number to use, it just represents a value that is pretty close to maxed out without counting on all three colors being exactly 255.
All of the white pixels need to be changed to yellow. A yellow will always have a relatively high green and red value and a low blue value. A good value for the yellow in the flag is 254 red, 242 green, and 0 blue.

Checkpoint 26.1.3.

Here is a program that changes the French flag to the flag of Chad. After running it, try removing the line that does the updatePixel - if you run that version you should get the unmodified French flag.

Checkpoint 26.1.4.

The Belgian flag is very similar to the Chad flag.
Figure 26.1.5. Chadian flag
Figure 26.1.6. Belgian flag
See if you can turn the Chad flag into the Belgian one. Do so by turning the blue pixels into black ones. Hints: blue pixels are not perfect blue. An approximate color value is (red = 0, green = 100, blue = 180), but you should not count on pixels having exactly those values - come up with a recipe using > and < that selects the blue pixels but not the yellow or red ones. Black pixels have r, g, and b values of 0.

Checkpoint 26.1.7.

    Which recipe is reasonable for checking for “is it a blue pixel” for the flag of Chad?
  • red < 20 and green > 80 and blue > 150
  • Correct, that works to select the blue but not the red or yellow.
  • red < 20 and green < 20 and blue > 200
  • The blue in the flag has a higher green value than 20
  • red < 20 and green > 20 and blue > 200
  • The blue in the flag isn’t actually that blue
  • red < 20 and green < 80 and blue > 150
  • The blue in the flag has a higher green value than 80
You have attempted of activities on this page.