9.7. Changing which data we use

Now that we are using coordinates to iterate through all of the pixels, we can also change which part of the picture we read and manipulate. Instead of writing a loop that visits every possible x and y, we can chose to only visit some of the coordinate pairs.

This program changes only the upper-left 1/4 of the image. To do so, it uses loops that only go up to 1/2 the width and 1/2 the height. At each location, it gets the existing pixel and then inverts each color channel (subtracts it from 255 so that a value of 0 becomes 255, a value of 1 becomes 254, 2 becomes 253, etc…).

You may have noticed that we used // 2 to divide by two in that sample. Why? range only works with whole numbers. And / 2 produces a decimal value (also known as a float for “floating decimal point”). Try this example and note the error you get.

Change the first line to set max to 10 / 2. It is the same problem - / produces a decimal even for whole numbers and range does not want that. Then try changing the first line to set max to 11 // 2. Recall that the // operator does integer division and drops the decimal part of the answer. So using // ensures that we always get a whole number (or int for integer).

We could even use two sets of loops to visit two different parts of the image. This program has two copies of the code for steps 3-6. The first one visits the top 30 rows. The second copy visits the last 30 rows. In each of those locations, we don’t even both accessing the existing color. Instead we use the Pixel(red, green, blue) function to make a new red pixel (255 red, 0 green and blue) and store it into the image at the current location.

Try modifying the program so that the red bars are on the left and right side of the image. To do so, you will have to “fix” for y... loops AND change the for x loops to only cover a limited distance. The first for x should cover a range from 0 to 30. The second one should start at the width - 30 and continue until it hits the full width.

You have attempted of activities on this page