Skip to main content

Section 26.2 A Pixel Selection Function

This time, we’re going to get a bit trickier. We are going to try to change the red scooter in this picture into a blue one.
To do that we need to select all the red pixels. But there are a lot of different “reds”. Obviously, a pixel with the color red = 255, green = 0, and blue = 0 is red. But most of the pixels in the scooter aren’t pure red. The red channel might not be 255. Or the blue or green might not be 0. Furthermore, a pixel with color values (255, 255, 255) has the maximum red value… but it is not red, it is white. Here are three examples of colors that might be part of the scooter:
122, 4, 18
194, 8, 20
247, 190, 194
We will say that if a pixel’s red value is at least 10 greater than both the green and the blue values, it is “red”. To express this as a conditional will look like r >= g + 20 and r >= b + 20, where r, g, b are the red, green, and blue color values. To test out our recipe, we are going to make a function isRed. It will accept values for r, g, and b and return True if they meet our criteria and false otherwise.
Now that we have some evidence that the function works, we can use it as the condition for our if statement. Because the function returns True or False, it can serve as the condition for the if: if isRed(r, g, b):.
If the pixel is determined to be “red”, we need to change it to a similar blue. A dark red should become a dark blue and a light red a light blue. The easiest way to do this is to swap the red and blue values. Like this:
122, 4, 18
18, 4, 122
Or this:
247, 190, 194
194, 190, 247
Here is the final program:
After running the program, try modifying it to answer the question below.

Checkpoint 26.2.1.

    A simpler test for “is it red” might just be to see if the red value is 250 or more and not worry about the green or blue. What happens if you change the condition in isRed to read if r >= 250:?
  • Almost identical to the complex version.
  • Try it!
  • All of the white pixels become blue too!
  • Try it!
  • You get something that looks like a blue flame pattern.
  • Correct, those are the only pixels that have a close to max red value.
  • Light red pixels are not affected and you get a "blue outline".
  • Try it!
You have attempted of activities on this page.