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 Example 1

Run this. What does it do?


image-loop-1

 

For each pixel, the body code sets the red, green, and blue values all to 255, 255, 0.None of the original flower data is left; all the color numbers are changed in the loop.

For-Loop Structure

parts of the for-loop

For-Loop Example 2

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?
yellow flowers


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 - Red Channel


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. There are analogous green and blue channels we could look at, and the image is all three combined. The red light is most prominent for the area of yellow flowers, which makes sense as we know that yellow = red + green.

Red, Green, and Blue Channels

red channel flowers image
green channel flowers image
blue channel flowers image

For-Loop Conclusions

> exercises