A Pattern for Image Processing¶
As we have seen with turtles and words, there are some general patterns in the programs that we write. With turtles, there was a polygon pattern (based on the Total Turtle Trip Theorem). When working with words and numbers, we used the accumulator pattern.
The image processing pattern is shown in the program below. This program changes the red to the original green, the green to the original blue, and the red to the original green. But, mostly we are trying to describe a pattern that you can use to create many image effects.
Here are our seven steps:
- Step 1: IMPORT Image from the Python Image Library (PIL). We need to import Image from PIL to use it to load an image.
- Step 2: Pick the image. We link a variable to a particular image from our library by creating an Image object and using it to open the image file.
- Step 3: Load the pixels. This loads the matrix of pixels that make up an image.
- Step 4: Loop through the pixels. This example gets every pixel in the image one at a time by looping over each column and then each row therein.
- Step 5: Get the data. Pixels are a combination of three values - red, green, and blue.
- Step 6: Modify the color. This is the part that you will most often change. Here’s where you can change the red, green, and/or blue values of a pixel.
- Step 7: Show the result. This will draw the changed image.