If and Else with Images¶
What if we want to identify objects in a picture? For example we might want to find the swan in the following picture. One way to get started looking for an object is to find the points where the color changes substantially from one pixel to the next. This is called edge detection and it is an important step in image processing.
To look for substantial color changes calculate the average color for the current pixel and the one to the the right of it. You can calculate the average as the sum of the red, green, and blue values divided by 3 (the number of values). Then compare the absolute value of the difference in the averages and if it is greater than some amount set the current pixel to black, otherwise set it to white. This will result in what looks like a simple pencil sketch of the picture. Try larger and smaller values than 10 in line 21 to see how they change the result.
Notice that the code above loops from 0 to the width - 1 as the last value through the loop (remember that range doesn’t include the last value). This is necessary since we are comparing the current pixel’s average color with the average color in the pixel to the right. There is no pixel to the right of the last pixel in a row so we have to stop after processing the one before the last one.
Try other ways to detect big changes in color from one pixel to another.
-
csp-15-3-1: How many different colors will be in our image (except the last column) when
we are done?
- 0
- Black and white are colors.
- 2
- This image will only have black or white pixels in all columns except the rightmost one. The pixel colors in the rightmost column will not be changed.
- 256
- This would be true if we were only using shades of gray, but we are only using two colors.
- 16,777,216 (= 256 * 256 * 256)
- This would be true if we were using all color values, but we are only using black and white.