Simple Graphics and Image Processing
Simple Graphics and Image Processing
Second Edition
Chapter 7
Simple Graphics and Image Processing
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use
as permitted in a license distributed with a certain product or service or otherwise on a password-protected website for
classroom use. 1
Objectives (1 of 2)
7.1 Use the concepts of object-based programming—classes,
objects, and methods—to solve a problem
7.2 Develop algorithms that use simple graphics operations to
draw two-dimensional shapes
7.3 Use the RGB system to create colors in graphics applications
and modify pixels in images
© 2018 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain
product or service or otherwise on a password-protected website for classroom use.
Objectives (2 of 2)
7.4 Develop recursive algorithms to draw recursive shapes
7.5 Write a nested loop to process a two-dimensional grid
7.6 Develop algorithms to perform simple transformations of
images, such as conversion of color to grayscale
© 2018 Cengage. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license distributed with a certain
product or service or otherwise on a password-protected website for classroom use.
Simple Graphics
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 4
Overview of Turtle Graphics (1 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 5
Overview of Turtle Graphics (2 of 2)
Down This attribute, which can be either true or false, controls whether the
turtle's pen is up or down. When true (that is, when the pen is down),
the turtle draws a line when it moves. When false (that is, when the
pen is up), the turtle can move without drawing a line.
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 6
Turtle Operations (1 of 3)
t.home() Moves t to the center of the window and then points t east
t.pencolor(r, g, b) Changes the pen color of t to the specified RGB value or to the
t.pencolor(string) specified string
t.fillcolor(r, g, b) Changes the fill color of t to the specified RBG value or to the
t.fillcolor(string) specified string
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 7
Turtle Operations (2 of 3)
t.begin_fill() Enclose a set of turtle commands that will draw a filled shape
t.end_fill() using the current fill color
t.clear() Erases all of the turtle’s drawings, without changing the
turtle’s state
t.width(pixels) Changes the width of t to the specified number of pixels
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 8
Turtle Operations (3 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 9
Setting Up a turtle.cfg File and Running IDLE
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 10
Object Instantiation and the Turtle
Module (1 of 3)
• Before you apply any methods to an object, you must create the object (i.e., an
instance of)
• Instantiation: Process of creating an object
• Use a constructor to instantiate an object:
<variable name> = <class name>(<any arguments>)
• To instantiate the Turtle class:
>>> from turtle import Turtle
>>> t = Turtle()
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 11
Object Instantiation and the Turtle
Module (2 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 12
Object Instantiation and the Turtle
Module (3 of 3)
>>> t.width(2) # For bolder lines
>>> t.left(90) # Turn to face north
>>> t.forward(30) # Draw a vertical line in black
>>> t.left(90) # Turn to face west
>>> t.up() # Prepare to move without drawing
>>> t.forward(10) # Move to beginning of horizontal line
>>> t.setheading(0) # Turn to face east
>>> t.pencolor("red")
>>> t.down() # Prepare to draw
>>> t.forward(20) # Draw a horizontal line in red
>>> t.hideturtle() # Make the turtle invisible
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 13
Drawing Two-Dimensional Shapes (1 of 3)
• Many graphics applications use vector graphics, or the drawing of simple two-
dimensional shapes, such as rectangles, triangles, and circles
• Example code:
def square(t, length):
“““Draws a square with the given length.”””
for count in range(4):
t.forward(length)
t.left(90)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 14
Drawing Two-Dimensional Shapes (2 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 15
Drawing Two-Dimensional Shapes (3 of 3)
• The code for drawing a radial pattern using any regular polygon followed by a
session using it with squares and hexagons:
def radialpattern(t, n, length, shape):
“““Draws a radial pattern of n shapes with the given length.”””
for count in range(n):
shape(t, length)
t.left(360 / n)
>>> t = Turtle()
>>> radialPattern(t, n = 10, length = 50, shape = square)
>>> t.clear()
>>> radialPattern(t, n = 10, length = 50, shape = hexagon)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 16
Examining an Object’s Attributes
• Mutator methods - methods that change the internal state of a Turtle object
• Accessor methods – methods that return the values of a Turtle object’s
attributes without altering its state
• Code that shows accessor methods in action:
>>> from turtle import Turtle
>>> t = Turtle()
>>> t.position()
(0.0, 0.0)
>>> t.heading()
0.0
>>> t.isdown()
True
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 17
Manipulating a Turtle’s Screen
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 18
Taking a Random Walk (1 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 19
Taking a Random Walk (2 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 20
Colors and the RGB System (1 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 21
Colors and the RGB System (2 of 2)
• Each color component requires 8 bits; total number of bits needed to represent
a color value is 24
• Total number of RGB colors is 224 (16,777,216)
Black (0, 0, 0)
Red (255, 0, 0)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 22
Example: Filling Radial Patterns with
Random Colors (1 of 5)
• The Turtle class includes a pencolor method for changing the turtle’s drawing
color
• Expects integers for the three RGB components
• Script that draws radial patterns of squares and hexagons with random fill
colors at the corners of turtle’s window (output is shown in Figure 7-5):
“““
File: randompatterns.py
Draws a radial pattern of squares in a random fill color
at each corner of the window.
”””
from turtle import Turtle
from polygons import *
import random
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 23
Example: Filling Radial Patterns with
Random Colors (2 of 5)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 24
Example: Filling Radial Patterns with
Random Colors (3 of 5)
def main():
t = Turtle()
t.speed(0)
# Number of shapes in radial pattern
count = 10
# Relative distances to corners of window from center
width = t.screen.window_width() // 2
height = t.screen.window_height() // 2
# Length of the square
length = 30
# Inset distance from window boundary for squares
inset = length * 2
# Draw squares in upper-left corner
drawPattern(t, −width + inset, height − inset, count,
length, square)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 25
Example: Filling Radial Patterns with
Random Colors (4 of 5)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 26
Example: Filling Radial Patterns with
Random Colors (5 of 5)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 27
Image Processing
• Digital image processing includes the principles and techniques for the
following:
• The capture of images with devices such as flatbed scanners and digital cameras
• The representation and storage of images in efficient file formats
• Constructing the algorithms in image-manipulation programs such as Adobe
Photoshop
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 28
Analog and Digital Information
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 29
Sampling and Digitizing Images
• A visual scene projects an infinite set of color and intensity values onto a two-
dimensional sensing medium
• If you sample enough of these values, digital information can represent an image
more or less indistinguishable (to human eye) from original scene
• Sampling devices measure discrete color values at distinct points on a two-
dimensional grid
• These values are pixels
• As more pixels are sampled, the more realistic the resulting image will appear
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 30
Image File Formats
• Once an image has been sampled, it can be stored in one of many file formats
• A raw image file saves all of the sampled information
• Data can be compressed to minimize its file size
• JPEG (Joint Photographic Experts Group)
- Uses lossless compression and a lossy scheme
• GIF (Graphic Interchange Format)
- Uses a lossy compression and a color palette of up to 256 of the most prevalent colors in the
image
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 31
Image-Manipulation Operations
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 32
The Properties of Images
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 33
The images Module (1 of 5)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 34
The images Module (2 of 5)
• Once an image has been created, you can examine its width and height, as
follows:
>>> image.getWidth()
198
>>> image.getHeight()
149
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 35
The images Module (3 of 5)
• The method getPixel returns a tuple of the RGB values at the given coordinates
• The following session shows the information for the pixel at position (0,0):
>>> image.getPixel(0, 0)
(194, 221, 114)
• The programmer can use the method setPixel to replace an RGB value at a
given position in an image:
>>> image = Image(150, 150)
>>> image.draw()
>>> blue = (0, 0, 255)
>>> y = image.getHeight() // 2
>>> for x in range(image.getWidth()):
image.setPixel(x, y - 1, blue)
image.setPixel(x, y, blue)
image.setPixel(x, y + 1, blue)
>>> image.draw()
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 36
The images Module (4 of 5)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 37
The images Module (5 of 5)
• Use the save operation to write an image back to an existing file using the
current filename
• The following code saves the new image using the filename horizontal.g if:
>>> image.save("horizontal.gif")
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 38
A Loop Pattern for Traversing a Grid (1 of 2)
• Most of the loops we have used in this book have had a linear loop structure
• Many image-processing algorithms use a nested loop structure to traverse a
two-dimensional grid of pixels
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 39
A Loop Pattern for Traversing a Grid (2 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 40
A Word on Tuples
>>> r
194
>>> g
221
>>> b
114
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 41
Converting an Image to Black and
White (1 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 42
Converting an Image to Black and
White (2 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 43
Converting an Image to Grayscale (1 of 3)
• Black and white photographs contain various shades of gray known as grayscale
• Grayscale can be an economical scheme (the only color values might be 8, 16,
or 256 shades of gray)
• A simple method:
average = (r + g + b) // 3
image.setPixel(x, y, (average, average, average)
• Problem: Does not reflect manner in which different color components affect
human perception
• Scheme needs to take differences in luminance into account
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 44
Converting an Image to Grayscale (2 of 3)
def grayscale(image):
“““Converts the argument image to grayscale.”””
for y in range(image.getHeight()):
for x in range(image.getWidth()):
(r, g, b) = image.getPixel(x, y)
r = int(r * 0.299)
g = int(g * 0.587)
b = int(b * 0.114)
lum = r + g + b
image.setPixel(x, y, (lum, lum, lum))
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 45
Converting an Image to Grayscale (3 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 46
Copying an Image
• The method clone builds and returns a new image with the same attributes as
the original one, but with an empty string as the filename
>>> from images import Image
>>> image = Image("smokey.gif")
>>> image.draw()
>>> newImage = image.clone() # Create a copy of image
>>> newImage.draw()
>>> grayscale(newImage) # Change in second window only
>>> newImage.draw()
>>> image.draw() # Verify no change to original
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 47
Blurring an Image
• Pixilation can be mitigated by blurring
def blur(image):
"""Builds and returns a new image which is a
blurred copy of the argument image."""
def tripleSum(triple1, triple2):
#1
(r1, g1, b1) = triple1
(r2, g2, b2) = triple2
return (r1 + r2, g1 + g2, b1 + b2)
new = image.clone()
for y in range(1, image.getHeight() - 1):
for x in range(1, image.getWidth() - 1):
oldP = image.getPixel(x, y)
left = image.getPixel(x - 1, y) # To left
right = image.getPixel(x + 1, y) # To right
top = image.getPixel(x, y - 1) # Above
bottom = image.getPixel(x, y + 1) # Below
sums = reduce(tripleSum,
[oldP, left, right, top, bottom])
#2
averages = tuple(map(lambda x: x // 5, sums))
#3
new.setPixel(x, y, averages)
return new
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 48
Edge Detection (1 of 3)
• Edge detection removes the full colors to uncover the outlines of the objects
represented in the image
def detectEdges(image, amount):
“““Builds and returns a new image in which the edges of
the argument image are highlighted and the colors are
reduced to black and white.”””
def average(triple):
(r, g, b) = triple
return (r + g + b) // 3
blackPixel = (0, 0, 0)
whitePixel = (255, 255, 255)
new = image.clone()
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 49
Edge Detection (2 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 50
Edge Detection (3 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 51
Reducing the Image Size (1 of 2)
• The size and the quality of an image on a display medium depend on two
factors:
• Image’s width and height in pixels
• Display medium’s resolution
- Measured in pixels, or dots per inch (D PI)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 52
Reducing the Image Size (2 of 2)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 53
Chapter Summary (1 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 54
Chapter Summary (2 of 3)
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 55
Chapter Summary (3 of 3)
• When displaying an image file, each color value is mapped onto a pixel in a two-
dimensional grid
• A nested loop structure is used to visit each position
• Image-manipulation algorithms either transform pixels at given positions or
create a new image using the pixel information of a source image
© 2018 Cengage. All Rights Reserved. May not be copied, scanned, or duplicated, in whole or in part, except for use as permitted in a license
distributed with a certain product or service or otherwise on a password-protected website for classroom use. 56