Skip to main content

Section 21.3 Using Repetition with Images

In Python, the line of code img = Image("cat.jpg") creates an Image object in the program that has all of the data from the image cat.jpg and names it with the variable img. Once we have done that, we can draw the entire image using lines of code like this:
win = ImageWin(img.getWidth(), img.getHeight())  # Make a window to hold the image
img.draw(win)                                    # draw it in that window
To modify the colors in an image, we need to modify all of its pixels one by one. In an image with 60,000 pixels, we would not want to write a separate line of code for each pixel. What we would like to do is specify what code to run for each of the pixels.
That is exactly what a for loop does - it takes a list of values and some instructions and runs the instructions for each one of the values. We can get a list of all the pixels with the procedure img.getPixels().
The program below modifies the cat image to remove all the red from each of its pixels. There are lot of lines in the program below,

Warning 21.3.1.

Be patient with programs that modify images, they can take a little while to produce their results.
There are \(200 \times 300 = 60,000\) pixels in the pixelList. Our for loop takes that giant list of pixels and one by one, calls the current one p and then does the body of the loop with it. After the loop is done, we make a window to display the image in and draw it - but don’t worry too much about that code - we want to focus on the loop and what it does to each pixel. This program changes the red value of each pixel to 0 - it removes all the red from the image, making it look like we are looking through blue-green glass.
You have attempted of activities on this page.