Using an Image Library

Similarly, in the image processing example, we used from PIL import Image. That made the Image object accessible. We could also define a new function that returns a new color, or a new procedure that changes the image.

Note

Processing all the pixes in an image can take time, so please be patient after clicking the Run button as you await the results.

The for col in range(width) on line 13 and for row in range(height) on line 14 let us loop through all of the pixels in the image and change the red value for each pixel. We’ll talk more about looping (repeating steps) in the next chapter.

    csp-6-6-1: What does the line pixels[col, row] = (r * 0.5, g, b) do?
  • It sets the red value in the current pixel to half its previous value.
  • Multiplying by 0.5 is the same as dividing by 2.
  • It sets the red value in the current pixel to twice its previous value.
  • This would be true if it was r * 2, instead of r * 0.5
  • It leaves red value of the current pixel unchanged.
  • This would be true if it was r, instead of r * 0.5
  • It sets the red value in the current pixel to 5 times its previous value.
  • This would be true if it was r * 5 instead of r * 0.5

This ability to name functions and procedures, and sets of functions and procedures, and absolutely anything and any set of things in a computer is very powerful. It allows us to create abstractions that make the computer easier to program and use. More on that in a future chapter.

Next Section - Renaming Python’s Functions