Skip to main content

Section 13.5 Compute with Images

Pictures on a computer are broken up into little bits called pixels, for picture (pix) elements (els). These are laid out on a grid, from left to right (the horizontal or x dimension) and top to bottom (the vertical or y dimension).
Figure 13.5.1. A grid with horizontal (x) and vertical (y) dimensions
Pixels are quite small. Even this small picture below has 200 columns and 300 rows of pixels:
Data: cat.jpg

Checkpoint 13.5.2.

    Which way does y increase on an image?
  • From left to right
  • The x value increases from left to right
  • From right to left
  • The horizontal direction is the x direction
  • From top to bottom
  • The y value increases from top to bottom
  • From bottom to top
  • This is common on a Cartesian coordinate system, but it is not true here
Each pixel has a color associated with it: An amount of red, an amount of green, and an amount of blue. The amount can be in the range of 0 to 255 where 0 is none of that color and 255 is the maximum amount of that color. A pixel is displayed using light, not paint, so it may work a bit differently than you might expect if you only have experience making colors by mixing paint. For example, you would mix blue and yellow paint to make green, but you mix red and green light to make yellow light.
Figure 13.5.3. How lights combine to make colors
All image manipulations in programs like Photoshop or Instagram filters are created by manipulating those red, green, and blue color components in each pixel.
Let’s remove the red from this picture. The program below does that.
In Python, images are another example of an object. To work with them, we will make use of another library, this one called image. That library will allow us to make an Image that holds the data from an image and an ImageWin where we can draw the image to.
The important lines are under the comments (lines that start with a #). Press the Save & Run button to run the program and show the changed image. Please note that processing all those pixels can take a few seconds.

Checkpoint 13.5.4.

    What do you think happens when you set all the colors to 0? Try adding lines that say p.setBlue(0) and p.setGreen(0) to the program after the p.setRed(0) (but before img.updatePixel(p)) and run it to check. You will have to make sure the lines are indented just like p.setRed(0) is.
  • You still see the picture, but it is all in shades of gray.
  • Not if you set all the color values to 0.
  • The picture is all white.
  • Did you try it? This would be true if you set all the values to 255 instead of 0.
  • The picture is all black.
  • Black is the absence of light so setting all colors to 0 results in an all-black image since there is no light.
You have attempted of activities on this page.