15.3. 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.


Discuss topics in this section with classmates.

Show Comments
You have attempted of activities on this page