Image For-Loop

In this section, we'll look at the "for loop" construct, which can run a bit of code thousands of times -- a big increase in the power available to us.
yellow flowers

Accessing one pixel at a time, e.g. pixel at (0, 0), then the pixel at (1, 0), etc. is not a good way to work on an image which may have 100,000 or more pixels. We'd like to say something like "for each pixel do this", and let the computer fiddle with the details of going through all the (x, y) values to look at each pixel once.

The very powerful "for loop" structure we'll learn here provides exactly this "for each pixel do this" feature. The loop takes a few lines of our code, and runs those lines again and again, once for each pixel in the image.

For-Loop Structure

parts of the for-loop

For-Loop Example 1

Setting red, green, and blue all to 0 (for 164,520 pixels). What does that do? What if we set red, green, and blue all to 255?

For each pixel, the body code sets the red, green, and blue values all to be 0. The result is a pure black rectangle. None of the original flower data is left; it all got changed to zeros.

For-Loop Example 2

Result is a solid yellow rectangle. The code overwrites the flower data, changing each pixel in the original image into a pure yellow pixel.

For-Loop Example 3

yellow flowers

Look again at flowers.jpg.Yellow is made or red + green, so we know that the yellow parts of the image have high red and green values. So what happens if, for each pixel, we set red to 0? What are the RGB values for a typical pixel on the yellow flowers look like before this loop runs? What about after?

The body code pixel.setRed(0); is run by the loop again and again, once for each pixel in the image. Since the yellow flowers are made with red + green light, setting the red to 0 for each pixel results is greenish flowers. The green leaves aren't changed much, since their red values were near 0 anyway.

For-Loop Example 4

Setting green and blue to 0 everywhere, all that is left is the area of red light that went into the original image, aka the "red channel" of the image. The red light is most prominent for the area of yellow flowers, which makes sense as we know that yellow = red + green.

For-Loop Conclusions

< exercises