Image-3 Loops

< CS101

Previously, we had things like this pixel.setRed(200);
With one line of code, change the red value of one pixel. In this section, we'll look at the "for loop" construct, which can run a bit of code thousands of times -- a huge increase in power.

What Did We See Last Time?

Loops - Box Analogy

Flowers


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

Super simple body: set red, green, blue to 0.


image-loop-1

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


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?


image-loop-2

  // your code here
  pixel.setRed(0);

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 3


image-loop-3

  // your code here
  pixel.setGreen(0);
  pixel.setBlue(0);

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