Fundamentals%20of%20Python:%20First%20Programs - PowerPoint PPT Presentation

About This Presentation
Title:

Fundamentals%20of%20Python:%20First%20Programs

Description:

Fundamentals of Python: First Programs Chapter 7: Simple Graphics and Image Processing Modifications by Mr. Dave Clausen Fundamentals of Python: From First Programs ... – PowerPoint PPT presentation

Number of Views:253
Avg rating:3.0/5.0
Slides: 66
Provided by: DaveC175
Category:

less

Transcript and Presenter's Notes

Title: Fundamentals%20of%20Python:%20First%20Programs


1
Fundamentals of PythonFirst Programs
  • Chapter 7 Simple Graphics
  • and Image ProcessingModificationsby
  • Mr. Dave Clausen

2
Objectives
  • After completing this chapter, you will be able
    to
  • Use the concepts of object-based
    programmingclasses, objects, and methodsto
    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

3
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

4
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

5
Overview of Turtle Graphics
  • Turtle graphics originally developed as part of
    the childrens 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

6
Overview of Turtle Graphics (continued)
  • Together, these attributes make up a turtles
    state

7
Turtle Operations
8
Turtle Operations (continued)
9
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 turtles 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, yNone)turtle.setpos(x, yNone)turtle.setposition(x, yNone) 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 turtles orientation.
10
Turtle Motion (Move and Draw 2)
turtle.setx(x) integer or float Set the turtles first coordinate to x, leave second coordinate unchanged.
turtle.sety(y) integer or float Set the turtles 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 degreesstandard mode logo mode 0 - east 0 - north 90 - north 90 - east 180 - west 180 - south 270 - south 270 west
turtle.home() Move turtle to the origin coordinates (0,0) and set its heading to its start-orientation (which depends on the mode, see mode())
turtle.circle(radius, extentNone, stepsNone radius  a number extent  a number (or None) steps  an integer (or None) 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.
11
Turtle Motion (Move and Draw 3)
turtle.dot(sizeNone, color) size  an integer gt 1 (if given) color  a colorstring or a numeric color tuple Draw a circular dot with diameter size, using color. If size is not given, the maximum of pensize4 and 2pensize is used.
turtle.stamp() 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(stampid) stampid  an integer, must be return value of previous stamp() call Delete stamp with given stampid.
turtle.clearstamps(nNone) n  an integer (or None) Delete all or first/last n of turtles stamps. If n is None, delete all stamps, if n gt 0 delete first n stamps, else if n lt 0 delete last n stamps
turtle.undo() Undo (repeatedly) the last turtle action(s). Number of available undo actions is determined by the size of the undobuffer..
turtle.speed(speedNone) speed  an integer in the range 0..10 or a speedstring (see below) Set the turtles 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.
12
Tell Turtles State
turtle.position()turtle.pos() Return the turtles current location (x,y) (as a Vec2D vector).
turtle.towards(x, yNone) 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 turtles start orientation which depends on the mode - standard/world or logo).
turtle.xcor() Return the turtles x coordinate.
turtle.ycor() Return the turtles y coordinate.
turtle.heading() Return the turtles current heading (value depends on the turtle mode, see mode())
turtle.distance(x, yNone) 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 distance from the turtle to (x,y), the given vector, or the given other turtle, in turtle step units..
13
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(widthNone)turtle.width(widthNone) width  a positive number 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.
turtle.isdown() Return True if pen is down, False if its up.
turtle.pen(penNone, pendict) pen  a dictionary with some or all of the below listed keys pendict  one or more keyword-arguments with the below listed keys as keywords Return or set the pens 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.
14
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.
15
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().
16
More Drawing Control
turtle.reset() Delete the turtles drawings from the screen, re-center the turtle and set variables to the default values.
turtle.clear() Delete the turtles 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, moveFalse, 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) 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 bottom-right corner of the text. By default, move is False.
17
Turtle State - Visibility
turtle.hideturtle()turtle.ht() Make the turtle invisible. Its a good idea to do this while youre 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 its hidden.
18
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(canvwidthNone, canvheightNone, bgNone) canvwidth  positive integer, new width of canvas in pixels canvheight  positive integer, new height of canvas in pixels bg  colorstring or color-tuple, new background color 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.
19
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
20
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(ltclass namegt)
  • help(ltclass namegt.ltmethod namegt)drawSquare.py

21
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

22
Object Instantiation and the turtle Module
(continued)
  • To close a turtles window, click its close box
  • Attempting to manipulate a turtle whose window
    has been closed raises an error

23
Object Instantiation and the turtle Module
(continued)
24
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

25
Drawing Two-Dimensional Shapes (continued)
26
Taking a Random Walk
  • Like any animal, a turtle can wander around
    randomly randomWalk.py

27
Taking a Random Walk (continued)
28
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

29
Colors and the RGB System (contd)
  • 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)

30
Example Drawing with Random Colors
  • The Turtle class includes a pencolor method for
    changing the turtles drawing color
  • Expects integers for the three RGB components

31
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
    objects attributes without altering its state
  • Example position method

32
Manipulating a Turtles Screen
  • The Screen objects attributes include its width
    and height in pixels and its background color
  • Use t.screen to access a turtles Screen object,
    then call a Screen method on this object

33
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.

34
Using Multiple Turtles
  • Instantiate more than one turtle, for examplet
    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 turtlet.shape(picture1nam
    e.gif")
  • t2.shape(picture2name.gif")
  • t3.shape(picture3name.gif")
  • Use transparent GIF files for turtle shapes.

35
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)

36
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

37
Case Study Recursive Patterns in Fractals
(continued)
38
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

39
Case Study Recursive Patterns in Fractals
(continued)
  • Design

40
Case Study (continued)
  • Implementation ccurve.py

41
Case Study (continued)
  • Implementation (continued)

42
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

43
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 clocks
    face represent an attempt to sample moments of
    time as discrete values (time itself is analog)

44
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

45
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

46
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 images size

47
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 images 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

48
The images Module
  • Non-standard, open-source Python tool
  • Image class represents an image as a
    two-dimensional grid of RGB values smokey.gif

49
The images Module (continued)
50
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

51
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

52
A Word on Tuples
  • A pixels RGB values are stored in a tuple

53
Converting an Image to Black and White
  • For each pixel, compute average of R/G/B values
  • Then, reset pixels 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

54
Converting an Image to Black and White (continued)
55
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

56
Converting an Image to Grayscale (continued)
57
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

58
Blurring an Image
  • Pixilation can be mitigated by blurring

59
Edge Detection
  • Edge detection removes the full colors to uncover
    the outlines of the objects represented in the
    imageedgeDetection.py

60
Edge Detection (continued)
61
Reducing the Image Size
  • The size and the quality of an image on a display
    medium depend on two factors
  • Images width and height in pixels
  • Display mediums 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 images
    aspect ratio imageShrink.py

62
Reducing the Image Size (continued)
  • Reducing size throws away some pixel information

63
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 classs methods is called its
    interface

64
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

65
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
Write a Comment
User Comments (0)
About PowerShow.com