Fundamentals of Python: From First Programs Through Data

Download Report

Transcript Fundamentals of Python: From First Programs Through Data

Fundamentals of Python:
First Programs
Chapter 7: Simple Graphics
and Image Processing
Modifications
by
Mr. Dave Clausen
Objectives
After completing this chapter, you will be able to:
• Use the concepts of object-based programming—
classes, objects, and methods—to solve a problem
• Develop algorithms that use simple graphics
operations to draw two-dimensional shapes
• Use the RGB system to create colors in graphics
applications and modify pixels in images
Fundamentals of Python: First Programs
2
Objectives (continued)
• Develop recursive algorithms to draw recursive
shapes
• Write a nested loop to process a two-dimensional
grid
• Develop algorithms to perform simple
transformations of images, such as conversion of
color to grayscale
Fundamentals of Python: First Programs
3
Simple Graphics
• Graphics: Discipline that underlies the
representation and display of geometric shapes in
two- and three-dimensional space
• A Turtle graphics toolkit provides a simple and
enjoyable way to draw pictures in a window
– turtle is a non-standard, open-source Python
module
Fundamentals of Python: First Programs
4
Overview of Turtle Graphics
• Turtle graphics originally developed as part of the
children’s programming language Logo
– Created by Seymour Papert and his colleagues at
MIT in the late 1960s
• Analogy: Turtle crawling on a piece of paper, with a
pen tied to its tail
– Sheet of paper is a window on a display screen
– Position specified with (x, y) coordinates
• Cartesian coordinate system, with origin (0, 0) at the
center of a window
Turtle Graphics Documentation
Fundamentals of Python: First Programs
5
Overview of Turtle Graphics
(continued)
• Together, these attributes make up a turtle’s state
Fundamentals of Python: First Programs
6
Turtle Operations
Fundamentals of Python: First Programs
7
Turtle Operations (continued)
Fundamentals of Python: First Programs
8
Turtle Motion (Move and Draw)
turtle.forward(distance)
turtle.ftance)
integer or float
Move the turtle forward by the specified distance, in the
direction the turtle is headed.
turtle.back(distance)
turtle.bk(distance)
turtle.backward(distance)
integer or float
Move the turtle backward by distance, opposite to the
direction the turtle is headed. Do not change the turtle’s
heading
turtle.right(angle)
turtle.rt(angle)
integer or float
Turn turtle right by angle units. (Units are by default
degrees, but can be set via
the degrees() and radians() functions.) Angle orientation
depends on the turtle mode,
turtle.left(angle)
turtle.lt(angle)
integer or float
Turn turtle left by angle units. (Units are by default degrees,
but can be set via the degrees() and radians() functions.)
Angle orientation depends on the turtle mode
turtle.goto(x, y=None)
turtle.setpos(x, y=None)
turtle.setposition(x, y=None)
x – a number or a
pair/vector of
numbers
y – a number
or None
If y is None, x must be a pair of coordinates or
a Vec2D (e.g. as returned by pos()).
Move turtle to an absolute position. If the pen is down, draw
line. Do not change the turtle’s orientation.
Fundamentals of Python: First Programs
9
Turtle Motion (Move and Draw 2)
turtle.setx(x)
integer or float
Set the turtle’s first coordinate to x, leave second coordinate unchanged.
turtle.sety(y)
integer or float
Set the turtle’s second coordinate to y, leave first coordinate unchanged.
turtle.setheading(to_angle)
turtle.seth(to_angle)
integer or float
Set the orientation of the turtle to to_angle. Here are some common
directions in degrees:
standard mode
logo mode
0 - east
0 - north
90 - north
90 - east
180 - west
180 - south
270 - south
270 – west
Move turtle to the origin – coordinates (0,0) – and set its heading to its
start-orientation (which depends on the mode, see mode())
turtle.home()
turtle.circle(radius, extent=Non
e, steps=None
radius – a
number
extent – a
number
(or None)
steps – an
integer
(or None)
Fundamentals of Python: First Programs
Draw a circle with given radius. The center is radius units left of the
turtle; extent – an angle – determines which part of the circle is drawn. If
extent is not given, draw the entire circle. If extent is not a full circle, one
endpoint of the arc is the current pen position. Draw the arc in
counterclockwise direction if radius is positive, otherwise in clockwise
direction. Finally the direction of the turtle is changed by the amount
of extent.
As the circle is approximated by an inscribed regular
polygon, steps determines the number of steps to use. If not given, it will
be calculated automatically. May be used to draw regular polygons.
10
Turtle Motion (Move and Draw 3)
turtle.dot(size=Non
e, *color)
size – an integer >= 1 (if
given)
color – a colorstring or a
numeric color tuple
turtle.stamp()
Draw a circular dot with diameter size, using color. If size is not given,
the maximum of pensize+4 and 2*pensize is used.
Stamp a copy of the turtle shape onto the canvas at the current turtle
position. Return a stamp_id for that stamp, which can be used to
delete it by calling clearstamp(stamp_id).
turtle.clearstamp(sta
mpid)
stampid – an integer, must
be return value of
previous stamp() call
Delete stamp with given stampid.
turtle.clearstamps(n
=None)
n – an integer (or None)
Delete all or first/last n of turtle’s stamps. If n is None, delete all
stamps, if n > 0 delete first n stamps, else if n < 0 delete
last n stamps
turtle.undo()
turtle.speed(speed=
None)
Undo (repeatedly) the last turtle action(s). Number of available undo
actions is determined by the size of the undobuffer..
speed – an integer in the
range 0..10 or a speedstring
(see below)
Fundamentals of Python: First Programs
Set the turtle’s speed to an integer value in the range 0..10. If no argument is given,
return current speed. If input is a number greater than 10 or smaller than 0.5, speed
is set to 0. Speedstrings are mapped to speedvalues as follows: “fastest”: 0 “fast”:
10 “normal”: 6
“slow”: 3 “slowest”: 1 Speeds from 1 to 10 enforce increasingly faster animation of
line drawing and turtle turning.Attention: speed = 0 means that no animation takes
place. forward/back makes turtle jump and likewise left/right make the turtle turn
instantly.
11
Tell Turtle’s State
Return the turtle’s current location (x,y) (as a Vec2D vector).
turtle.position()
turtle.pos()
turtle.towards(x, y=None)
x – a number or a pair/vector of
numbers or a turtle instance
y – a number if x is a number,
else None
Return the angle between the line from turtle position to
position specified by (x,y), the vector or the other turtle. This
depends on the turtle’s start orientation which depends on
the mode - “standard”/”world” or “logo”).
turtle.xcor()
Return the turtle’s x coordinate.
turtle.ycor()
Return the turtle’s y coordinate.
turtle.heading()
Return the turtle’s current heading (value depends on the
turtle mode, see mode())
turtle.distance(x, y=None
)
x – a number or a pair/vector of
numbers or a turtle instance
y – a number if x is a number,
else None
Fundamentals of Python: First Programs
Return the distance from the turtle to (x,y), the given vector,
or the given other turtle, in turtle step units..
12
Drawing State
turtle.pendown()
turtle.pd()
turtle.down()
Pull the pen down – drawing when moving..
turtle.penup()
turtle.pu()
turtle.up()
Pull the pen up – no drawing when moving.
turtle.pensize(width=None)
turtle.width(width=None)
width – a positive
number
Return True if pen is down, False if it’s up.
turtle.isdown()
turtle.pen(pen=None, **pen
dict)
Set the line thickness to width or return it. If resizemode is set to “auto”
and turtleshape is a polygon, that polygon is drawn with the same line
thickness. If no argument is given, the current pensize is returned.
pen – a dictionary
with some or all of
the below listed keys
pendict – one or
more keywordarguments with the
below listed keys as
keywords
Fundamentals of Python: First Programs
Return or set the pen’s attributes in a “pen-dictionary” with the following key/value
pairs:
“shown”: True/False
“pendown”: True/False
“pencolor”: color-string or color-tuple
“fillcolor”: color-string or color-tuple
“pensize”: positive number
“speed”: number in range 0..10
“resizemode”: “auto” or “user” or “noresize”
“stretchfactor”: (positive number, positive number)
“outline”: positive number
“tilt”: number
This dictionary can be used as argument for a subsequent call to pen() to restore the
former pen-state. Moreover one or more of these attributes can be provided as
keyword-arguments. This can be used to set several pen attributes in one statement.
13
Color Control
turtle.pencolor(*args)
Return or set
the pencolor.
Four input formats are allowed:
pencolor() Return the current pencolor as color specification string or as a tuple (see example).
May be used as input to another color/pencolor/fillcolor call.
pencolor(colorstring) Set pencolor to colorstring, which is a Tk color specification string, such
as "red", "yellow", or "#33cc8c".
pencolor((r, g, b)) Set pencolor to the RGB color represented by the tuple of r, g, and b. Each
of r, g, and b must be in the range 0..colormode, where colormode is either 1.0 or 255
(see colormode()).
pencolor(r, g, b) Set pencolor to the RGB color represented by r, g, and b. Each of r, g, and b must
be in the range 0..colormode.
turtle.fillcolor(*args)
Return or set
the fillcolor.
Four input formats are allowed:
fillcolor() Return the current fillcolor as color specification string, possibly in tuple format (see
example). May be used as input to another color/pencolor/fillcolor call.
fillcolor(colorstring) Set fillcolor to colorstring, which is a Tk color specification string, such
as "red", "yellow", or "#33cc8c".
fillcolor((r, g, b)) Set fillcolor to the RGB color represented by the tuple of r, g, and b. Each of r, g,
and b must be in the range 0..colormode, where colormode is either 1.0 or 255 (see colormode()).
fillcolor(r, g, b) Set fillcolor to the RGB color represented by r, g, and b. Each of r, g, and b must be
in the range 0..colormode
turtle.color(*args)
Return or set
pencolor and
fillcolor.
Several input formats are allowed. They use 0 to 3 arguments as follows:
color() Return the current pencolor and the current fillcolor as a pair of color specification strings or
tuples as returned by pencolor() andfillcolor().
color(colorstring), color((r,g,b)), color(r,g,b)Inputs as in pencolor(), set both, fillcolor and pencolor,
to the given value.
color(colorstring1, colorstring2), color((r1,g1,b1), (r2,g2,b2))Equivalent
to pencolor(colorstring1) and fillcolor(colorstring2) and analogously if the other input format is used.
Fundamentals of Python: First Programs
14
Filling Shapes
turtle.filling()
Return fillstate (True if filling, False else).
turtle.begin_fill()
To be called just before drawing a shape
to be filled.
turtle.end_fill()
Fill the shape drawn after the last call
to begin_fill().
Fundamentals of Python: First Programs
15
More Drawing Control
turtle.reset()
Delete the turtle’s drawings from the screen, recenter the turtle and set variables to the default
values.
turtle.clear()
Delete the turtle’s drawings from the screen. Do
not move turtle. State and position of the turtle as
well as drawings of other turtles are not affected.
turtle.write(arg, move=False,
align="left", font=("Arial", 8,
"normal"))
arg – object to be
written to the
TurtleScreen
move – True/False
align – one of the
strings “left”, “center” or
right”
font – a triple
(fontname, fontsize,
fonttype)
Fundamentals of Python: First Programs
Write text - the string representation of arg - at the
current turtle position according to align (“left”,
“center” or right”) and with the given font.
Ifmove is true, the pen is moved to the bottomright corner of the text. By default, move is False.
16
Turtle State - Visibility
turtle.hideturtle()
turtle.ht()
Make the turtle invisible. It’s a good idea to do this
while you’re in the middle of doing some complex
drawing, because hiding the turtle speeds up the
drawing observably.
turtle.showturtle()
turtle.st()
Make the turtle visible.
turtle.isvisible()
Return True if the Turtle is shown, False if it’s
hidden.
Fundamentals of Python: First Programs
17
Window Control
turtle.bgcolor(*args)
args – a color string or
three numbers in the range
0..colormode or a 3-tuple of
such numbers
Set or return background color of the TurtleScreen
turtle.clear()
turtle.clearscreen()
Delete all drawings and all turtles from the TurtleScreen.
Reset the now empty TurtleScreen to its initial state: white
background, no background image, no event bindings and
tracing on.
turtle.reset()
turtle.resetscreen()
Reset all Turtles on the Screen to their initial state.
turtle.screensize(canvwidth=Non
e, canvheight=None, bg=None)
canvwidth – positive
integer, new width of
canvas in pixels
canvheight – positive
integer, new height of
canvas in pixels
bg – colorstring or colortuple, new background
color
Fundamentals of Python: First Programs
If no arguments are given, return current (canvaswidth,
canvasheight). Else resize the canvas the turtles are
drawing on. Do not alter the drawing window. To observe
hidden parts of the canvas, use the scrollbars. With this
method, one can make visible those parts of a drawing
which were outside the canvas before.
18
How to Configure Screen and Turtles
If you want to use a different configuration which better reflects the features of this module or which better fits to your needs,,
you can prepare a configuration file turtle.cfg which will be read at import time and modify the configuration according to its
settings.
The built in configuration would correspond to the following turtle.cfg:
width = 0.5
height = 0.75
leftright = None
topbottom = None
canvwidth = 800
canvheight = 400
mode = standard
colormode = 1.0
delay = 10
undobuffersize = 1000
shape = classic
pencolor = black
fillcolor = black
resizemode = noresize
visible = True
language = english
exampleturtle = turtle
examplescreen = screen
title = Python Turtle Graphics
using_IDLE = False
Fundamentals of Python: First Programs
19
Turtle Operations (continued)
• Interface: set of methods of a given class
– Used to interact with an object
– Use docstring mechanism to view an interface
• help(<class name>)
• help(<class name>.<method name>)
drawSquare.py
Fundamentals of Python: First Programs
20
Object Instantiation and the
turtle Module
• 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:
• To instantiate the Turtle class:
Fundamentals of Python: First Programs
21
Object Instantiation and the
turtle Module (continued)
• To close a turtle’s window, click its close box
• Attempting to manipulate a turtle whose window
has been closed raises an error
Fundamentals of Python: First Programs
22
Object Instantiation and the
turtle Module (continued)
Fundamentals of Python: First Programs
23
Drawing Two-Dimensional Shapes
• Many graphics applications use vector graphics,
or the drawing of simple two-dimensional shapes,
such as rectangles, triangles, and circles
drawPolygon.py
Fundamentals of Python: First Programs
24
Drawing Two-Dimensional Shapes
(continued)
Fundamentals of Python: First Programs
25
Taking a Random Walk
• Like any animal, a turtle can wander around
randomly: randomWalk.py
Fundamentals of Python: First Programs
26
Taking a Random Walk (continued)
Fundamentals of Python: First Programs
27
Colors and the RGB System
• Display area on a computer screen is made up of
colored dots called picture elements or pixels
• Each pixel represents a color – the default is black
• RGB is a common system for representing colors
– RGB stands for red, green, and blue
– Each color component can range from 0 – 255
• 255  maximum saturation of a color component
• 0  total absence of that color component
– A true color system
Fundamentals of Python: First Programs
28
Colors and the RGB System (cont’d)
• 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)
Fundamentals of Python: First Programs
29
Example: Drawing with Random
Colors
• The Turtle class includes a pencolor method
for changing the turtle’s drawing color
– Expects integers for the three RGB components
Fundamentals of Python: First Programs
30
Examining an Object's Attributes
• Mutator methods change the internal state of a
Turtle method
– Example: pencolor method
• Accessor methods return the values of a Turtle
object’s attributes without altering its state
– Example: position method
Fundamentals of Python: First Programs
31
Manipulating a Turtle’s Screen
• The Screen object’s attributes include its width
and height in pixels and its background color
• Use t.screen to access a turtle’s Screen
object, then call a Screen method on this object
Fundamentals of Python: From First Programs Through Data Structures
32
Background Scenes
• After you have drawn your background scenes with turtle
commands:
– Press the “Print Screen” key on the keyboard to capture each
background scene.
– Edit and crop the picture in Paint or Photoshop to only include what
you have drawn (keep this as 800 by 400 pixels, or as close to this as
possible).
– Save the pictures as GIF files using filenames like, Scene1.gif,
Scene2.gif, etc.
• Comment out all the function calls to functions that draw the
backgrounds (Do NOT delete these functions.)
• Load the background scene using
screen.bgpic("BackgroundPic.gif")
and the name of your background pictures.
Fundamentals of Python: From First Programs Through Data Structures
33
Using Multiple Turtles
• Instantiate more than one turtle, for example:
t = Turtle()
t2 = Turtle()
t3 = Turtle()
• Register and associate the turtles to shapes (.gif)
t.screen.register_shape(“picture1name.gif")
t2.screen.register_shape(“picture2name.gif")
t3.screen.register_shape(“picture3name.gif")
• Set the shape for each turtle
t.shape(“picture1name.gif")
t2.shape(“picture2name.gif")
t3.shape(“picture3name.gif")
• Use transparent GIF files for turtle shapes.
Fundamentals of Python: From First Programs Through Data Structures
34
Simple Animation
• You could have a loop moving each turtle with a delay to adjust the
speed of the animation. Here is an example that moves three
turtles a random number of pixels each iteration of the loop:
for point in range(600):
t.fd(random.randint(1,3))
t2.fd(random.randint(1,3))
t3.fd(random.randint(1,4))
screen.delay(3)
Fundamentals of Python: From First Programs Through Data Structures
35
Case Study: Recursive Patterns in
Fractals
• Fractals are highly repetitive or recursive patterns
• A fractal object appears geometric, yet it cannot
be described with ordinary Euclidean geometry
• Strangely, a fractal curve is not one-dimensional,
and a fractal surface is not two-dimensional
– Every fractal shape has its own fractal dimension
• One example of a fractal curve is the c-curve
Fundamentals of Python: First Programs
36
Case Study: Recursive Patterns in
Fractals (continued)
Fundamentals of Python: First Programs
37
Case Study: Recursive Patterns in
Fractals (continued)
• Request:
– Write a program that allows the user to draw a
particular c-curve in varying degrees
• Analysis:
– Program should prompt the user for the level of the
c-curve
– Next, program should display a Turtle graphics
window in which it draws the c-curve
Fundamentals of Python: First Programs
38
Case Study: Recursive Patterns in
Fractals (continued)
• Design:
Fundamentals of Python: First Programs
39
Case Study (continued)
• Implementation: ccurve.py
Fundamentals of Python: First Programs
40
Case Study (continued)
• Implementation (continued):
Fundamentals of Python: First Programs
41
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
Fundamentals of Python: First Programs
42
Analog and Digital Information
• Computers must use digital information which
consists of discrete values
– Example: Individual integers, characters of text, or
bits
• The information contained in images, sound, and
much of the rest of the physical world is analog
– Analog information contains a continuous range
of values
• Ticks representing seconds on an analog clock’s
face represent an attempt to sample moments of
time as discrete values (time itself is analog)
Fundamentals of Python: First Programs
43
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
Fundamentals of Python: First Programs
44
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
Fundamentals of Python: First Programs
45
Image-Manipulation Operations
• Image-manipulation programs either transform the
information in the pixels or alter the arrangement of
the pixels in the image
• Examples:
–
–
–
–
–
–
–
Rotate an image
Convert an image from color to grayscale
Blur all or part of an image
Sharpen all or part of an image
Control the brightness of an image
Perform edge detection on an image
Enlarge or reduce an image’s size
Fundamentals of Python: First Programs
46
The Properties of Images
• The coordinates of pixels in the two-dimensional
grid of an image range from (0, 0) at the upper-left
corner to (width-1, height-1) at lower-right corner
– width/height are the image’s dimensions in pixels
– Thus, the screen coordinate system for the display
of an image is different from the standard Cartesian
coordinate system that we used with Turtle graphics
• The RGB color system is a common way of
representing the colors in images
Fundamentals of Python: First Programs
47
The images Module
• Non-standard, open-source Python tool
– Image class represents an image as a twodimensional grid of RGB values: smokey.gif
Fundamentals of Python: First Programs
48
The images Module (continued)
Fundamentals of Python: First Programs
49
A Loop Pattern for Traversing a Grid
• 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
Fundamentals of Python: First Programs
50
A Loop Pattern for Traversing a Grid
(continued)
• Previous loop uses a row-major traversal
– We use this template to develop many of the
algorithms that follow:
Fundamentals of Python: First Programs
51
A Word on Tuples
• A pixel’s RGB values are stored in a tuple:
Fundamentals of Python: First Programs
52
Converting an Image to Black and
White
• For each pixel, compute average of R/G/B values
• Then, reset pixel’s color values to 0 (black) if the
average is closer to 0, or to 255 (white) if the
average is closer to 255: blackAndWhite.py
Fundamentals of Python: First Programs
53
Converting an Image to Black and
White (continued)
Fundamentals of Python: First Programs
54
Converting an Image to Grayscale
• 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:
– Problem: Does not reflect manner in which different
color components affect human perception
• Scheme needs to take differences in luminance
into account
grayScale.py
Fundamentals of Python: First Programs
55
Converting an Image to Grayscale
(continued)
Fundamentals of Python: First Programs
56
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
Fundamentals of Python: First Programs
57
Blurring an Image
• Pixilation can be mitigated by blurring
Fundamentals of Python: First Programs
58
Edge Detection
• Edge detection removes the full colors to uncover
the outlines of the objects represented in the image
edgeDetection.py
Fundamentals of Python: First Programs
59
Edge Detection (continued)
Fundamentals of Python: First Programs
60
Reducing the Image Size
• 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 (DPI)
• The resolution of an image can be set before the
image is captured
– A higher DPI causes sampling device to take more
samples (pixels) through the two-dimensional grid
• A size reduction usually preserves an image’s
aspect ratio
imageShrink.py
Fundamentals of Python: First Programs
61
Reducing the Image Size (continued)
• Reducing size throws away some pixel information
Fundamentals of Python: First Programs
62
Summary
• Object-based programming uses classes, objects,
and methods to solve problems
• A class specifies a set of attributes and methods
for the objects of that class
• The values of the attributes of a given object make
up its state
• A new object is obtained by instantiating its class
• The behavior of an object depends on its current
state and on the methods that manipulate this state
• The set of a class’s methods is called its interface
Fundamentals of Python: First Programs
63
Summary (continued)
• Turtle graphics is a lightweight toolkit used to draw
pictures in a Cartesian coordinate system
• RGB system represents a color value by mixing
integer components that represent red, green, and
blue intensities
• A grayscale system uses 8, 16, or 256 distinct
shades of gray
Fundamentals of Python: First Programs
64
Summary (continued)
• Digital images are captured by sampling analog
information from a light source, using a device such
as a digital camera or a flatbed scanner
– Can be stored in several formats, like JPEG and GIF
• 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
Fundamentals of Python: First Programs
65