2. Image Processing Practice¶
Quick Overview of Day
Use nested loops to practice simple image processing.
2.1. Nested Loop Review¶
In the previous section, we used a lot of nested loops, which is a loop inside another loop. Use what you learned from that section to answer the following:
2.2. Warmup Problems¶
Your teacher may choose to work through the following problems to help build your confidence before you attempt the practice problems.
2.2.1. Gray Scale¶
See if you can create a gray scale version of the image. When looking at each pixel, you should average the red, green and blue intensities and then using that average value for setting the new red, new green, and new blue intensities. Note that any RGB value that contains the same value for it’s R, G and B amounts will be a gray value. For example, (50, 50, 50) is a dark gray, and (200, 200, 200) is a lighter gray.
2.2.2. Black and White Threshold¶
You can create interesting black and white images by setting a threshold (if the sum of the intensities is larger than some value) and choosing to either insert a white pixel or a black pixel at the current location. For example, if you use the
skflag.png image, it looks like this originally:
If you look at every pixel to find the sum of the red, green, and blue values, then insert a black pixel whenever the sum is greater than 200 (or a white pixel if it is not), you will create the following image:
2.3. Practice Problems¶
As we have seen, nested loops allow us to look through all of the pixels for an image. You will need to use a nested for loop for each of the following practice problems. Although you could copy/paste much of the same template code for these problems, try to write out a full solution from scratch for at least 3 of the problems!
For the following problems, use one of these images:
2.3.1. Red Remover¶
Write a program that opens an image and uses a nested loop to look at all of the pixels. For each pixel, you should remove all of the red intensity from the pixel. The green and blue intensities should remain unchanged.
2.3.2. Color Swapping¶
Write a program that sets the red value to the original green value, the green value to the original blue value, and the blue value to the original red value.
2.3.3. Keep the Green¶
Write a program that keeps only the green values of all pixels in the image.
2.3.4. Half Red¶
Write a program that sets each pixel’s red intensity to be half of the original value. The green and blue intensities should remain the same as in the original image.
2.3.5. Combining Bits of Colors¶
Write a program that sets each pixel’s blue intensity to be an eighth of the original green value plus an eighth of the original red value. The red and green intensities should remain the same as in the original image.
2.3.6. Half Each Color¶
Write a program that sets each pixel’s RGB intensities to be half of their original value.