20934254 Python Module 3
20934254 Python Module 3
Monday
* Until about 35 years ago, computers processed numbers and text almost
exclusively. Since then, the computational processing of images, video,
and sound has become increasingly important.
Simple Graphics
- Commands direct the turtle as it moves across the paper and tell it to lift
or lower its tail, turn some number of degrees left or right, and
move a specified distance.
- Whenever the tail is down, the pen drags along the paper, leaving a trail.
In this manner, it is possible to program the turtle to draw pictures ranging
from the simple to the complex.
* The pen, too, has attributes: color, width, and on/off state (also called
down and up).
- For example, a turtle will draw when it is moved, if its pen is currently
down, but it will simply move without drawing when its pen is currently
up.
- Operations also change a turtle’s state. For instance, moving a turtle
changes its position, but not its direction, pen width, or pen color.
* Two other important classes used in Python’s Turtle graphics system are
Screen , which represents a turtle’s associated window, and Canvas,
which represents the area in which a turtle can move and draw lines.
Turtle Operations
* The next code segment creates and returns a Turtle object and opens a
drawing window.
>>> t = Turtle()
* As you can see, the turtle’s icon is located at the home position (0, 0) in
the center of the window, facing east and ready to draw.
The Screen object’s attributes include its width and height in pixels, and its
background color, among other things.
You access a turtle’s Screen object using the notation t.screen , and then
call a Screen method on this object.
The following code resets the screen’s background color, which is white by
default, to orange, and prints the coordinates of the upper left and lower
right corners of the window:
- The smaller the pixel, the smoother the lines drawn with them will be.
- Among the various schemes for representing colors, the RGB system is a
common one. The letters stand for the color components of red, green, and
blue, to which the human retina is sensitive.
* The colour components are mixed together to form a unique color value.
Each color component can range from 0 through 255. The value 255
represents the maximum saturation of a given color component, whereas
the value 0 represents the total absence of that component
* The Turtle class includes the pencolor and fillcolor methods for
changing the turtle’s drawing and fill colors, respectively. These methods
can accept integers for the three RGB components as arguments.
* fillcolor(col): This helps to choose the color for filling the shape. It takes
the input parameter as the color name or hex value of the color and fills the
upcoming closed geographical objects with the chosen color. Color names
are basic color names i.e. red, blue, green, orange.
begin_fill(): This function tells turtle that all upcoming closed graphical
objects needed to be filled by the chosen color.
end_fill(): this function tells turtle to stop the filling upcoming closed
graphical objects.
* Illustration 1 :
import turtle
* Illustration 2
import turtle
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
- Early recording and playback devices for images and sound were all
analog devices.
* 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. Here the cost is
that the file size of the image can be quite large. But the benefit is that
the display of a raw image will be the most true to life.
* Two of the most popular image file formats are JPEG (Joint Photo-
graphic Experts Group) and GIF (Graphic Interchange Format).
* Various data-compression schemes are used to reduce the file size of a
JPEG image.
- Lossy scheme: To save even more bits, another scheme analyzes larger
regions of pixels and saves a color value that the pixels’ colors
approximate. Here some of the original color information is lost. However,
when the image is decompressed and displayed, the human eye usually is
not able to detect the difference between the new colors and the original
ones.
In the first phase, the algorithm analyzes the color samples to build a table
called color palette, of up to 256 of the most prevalent colors.
-The algorithm then visits each sample in the grid and replaces it with the
key of the closest color in the color palette.
The resulting image file thus consists of at most 256 color values and the
integer keys of the image’s colors in the palette.
- The decompression algorithm uses the keys and the color palette to
restore the grid of pixels for display.
Image-Manipulation Operations
1. Rotate an image
2. Convert an image from color to grayscale
3. Apply color filtering to an image
4. Highlight a particular area in an image
5. Blur all or part of an image
6. Sharpen all or part of an image
7. Control the brightness of an image
8. Perform edge detection on an image
9. Enlarge or reduce an image’s size
10. Apply color inversion to an image
11. Morph an image into another image
The Properties of Images
- It allows the programmer to load an image from a file, view the image
in a window, examine and manipulate an image’s RGB values, and save
the image to a file.
* The images module includes a class named Image . The Image class
represents an image as a two-dimensional grid of RGB values.
* The images module accepts only image files in GIF for mat.
* Basic Operations on images
Output:
* Python raises an exception if it cannot locate the file in the current
directory, or if the file is not a GIF file.
II. Once an image has been created, you can examine its width and height,
as follows:
>>> image.getWidth()
198
>>> image.getHeight()
149
>>> print(image)
Filename: smokey.gif
Width: 198
Height: 149
IV. The method getPixel returns a tuple of the RGB values at the given
coordinates.
To get the information for the pixel at position (0, 0), which is at the
image’s upper-left corner.
>>> image.getPixel(0, 0)
(194, 221, 114)
- The programmer specifies the image’s width and height; the resulting
image consists of transparent pixels.
- Such images are useful for creating backgrounds for drawing simple
shapes, or for creating new images that receive information from existing
images.
- The programmer can use the method setPixel to replace an RGB value at
a given position in an image.
- Problem:
Output:
3. You can save an image under its current filename or a different
filename.
>>> image.save("horizontal.gif")
- For each pixel, the algorithm computes the average of the red, green, and
blue values.
-The algorithm then resets the 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.
Output:
2. Converting an Image to Grayscale
- The method of replacing the color values of each pixel with their average
does not reflect the manner in which the different color components affect
human perception.
- The human eye is actually more sensitive to green and red than it is to
blue. As a result, the blue component appears darker than the other
two components.
-The relative luminance proportions of green, red, and blue are .587, .299,
and .114, respectively
3. 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.
- The two images are thus structurally equivalent but not identical
ie, changes to the pixels in one image will have no impact on the pixels in
the same positions in the other image.
4. Blurring an Image
* edge in an image are the lines that represent a transition from one group
of similar pixels in the image to another different group.
One example of an edge is the pixels that represent the boundaries of
an object in an image, where the background of the image ends and the
object begins.
- blurring an image means, we make the colour transition from one side of
an edge in the image to another smooth rather than sudden.
- Blurring makes these areas appear softer, but at the cost of losing some
definition.
* The blurring algorithm resets each pixel’s color to the average of the
colors of the four pixels that surround it.
At #1, the nested auxiliary function tripleSum is defined. This function
expects two tuples of integers as arguments and returns a single tuple
containing the sums of the values at each position.
At #2, five tuples of RGB values are wrapped in a list and passed with the
tripleSum function to the reduce function. This function repeatedly applies
tripleSum to compute the sums of the tuples, until a single tuple containing
the sums is returned.
At #3, a lambda function is mapped onto the tuple of sums, and the result
is converted to a tuple. The lambda function divides each sum by 5. Thus,
you are left with a tuple of the average RGB values.
5. Edge Detection
* Edge detection removes the full colors on a color image to uncover the
outlines of the objects represented in the image.
- When artists paint pictures, they often sketch an outline of the subject in
pencil or char coal. They then fill in and color over the outline to complete
the painting. Edge detection performs the inverse function on a color
image.
- If the luminance of the pixel differs from that of either of these two
neighbors by a significant amount, you have detected an edge, and you set
that pixel’s color to black.
- if the height and width of an image are each reduced by a factor of N, the
number of color values in the resulting image is reduced by a factor of N2 .
* A size reduction usually preserves an image’s aspect ratio (that is, the
ratio of its width to its height).
- The algorithm then copies the color values of just some of the original
image’s pixels to the new image
- The function expects the original image and a positive integer shrinkage
factor as parameters.
A shrinkage factor of 2 tells Python to shrink the image to half of its
original dimensions, a factor of 3 tells Python to shrink theimage to one-
third of its original dimensions, and so forth.
* The loop traversesthe larger image (the original) and skips positions by
incrementing its coordinates by the shrinkage factor. The new image’s
coordinates are incremented by 1, as usual.
Graphical User Interfaces
- A GUI displays text as well as small images (called icons) that represent
objects such as folders, files of different types, command buttons,
and drop-down menus.
* A GUI program is event driven, meaning that it is inactive until the user
clicks a button or selects a menu option.
- a GUI program allows users to enter inputs in any order and waiting for
them to press a command button or select a menu option.
* The terminal-based version of the program prompts the user for his gross
income and number of dependents.
* To obtain results for a different set of input data, the user must run the
program again. At that point, all of the inputs must be re-entered.
The GUI-Based Version
1. A title bar at the top of the window. This bar contains the title of the
program, “Tax Calculator.”
The user can use the mouse to click the left disk to quit the program, the
middle disk to minimize the window, or the right disk to zoom the
window.
- The user can also move the window around the screen by holding the left
mouse button on the title bar and dragging the mouse.
2. A set of labels along the left side of the window. These are text
elements that describe the inputs and outputs. For example, “Gross
income” is one label.
3. A set of entry fields along the right side of the window. These are
boxes within which the program can output text or receive it as input from
the user.
At program start-up, the fields contain default values
5. The user can also alter the size of the window by holding the mouse on
its lower-right corner and dragging in any direction.
6. Define a main function that instantiates the window class and runs the
appropriate method to launch the GUI.
* In the GUI version of the tax calculator program consists of the window
and its components, including the labeled entry fields and the Compute
button.
- The action triggered when Compute button is clicked, is a method call.
This method fetches the input values from the input fields and performs
the computation.
http://home.wlu.edu/~lambertk/breezypythongui/.
- The EasyFrame class provides the basic functionality for any window.
- The __init__ method runs a method with the same name on the
EasyFrame class and then sets up any window components to display in
the window.
- In this case, the addLabel method is run on the window itself.
4. The last five lines of code define a main function and check to see if the
Python code file is being run as a program.
Note that mainloop , as the name implies, enters a loop. The Python
Virtual Machine runs this loop behind the scenes. Its purpose is to wait for
user events, as mentioned earlier. The loop terminates when the user clicks
the window’s close box.
06/06/23
Tuesday
A Template for All GUI Programs
*The __init__ method initializes the window by setting its attributes and
populating it with the appropriate GUI components.
* The last lines of code, beginning with the definition of the main function,
create an instance of the application window class and run the mainloop
method on this instance.
- The window then pops up and waits for user events. Pressing the
window’s close button will quit the program normally.
* When you make a new class a subclass of another class, your new class
inherits and thereby acquires the attributes and behavior defined by its
parent class, and any of its ances tor classes, for free.
* A window has several attributes. The most important ones are its
- title (an empty string by default)
- width and height in pixels
- resizability (true by default)
- background color (white by default)
- Along with that you can provide a custom initial width and height in
pixels.
- The window’s background color can be set to yellow with the following
statement:
self["background"] = "yellow"
self.setResizable(False)
Window Layout
- The grid’s row and columns are numbered from the position (0, 0) in the
upper left corner of the window.
- The values of sticky are the strings “N,” “S,” “E,” and “W,” or any
combination thereof.
Illustration: Code that centers the four labels in their grid positions:
- When a window has two components in the first row and only one
component in the second row, the latter component might be centered in its
row, thus occupying two grid positions.
- The programmer can force a horizontal and/ or vertical spanning of grid
positions by supplying the rowspan and columnspan keyword arguments
when adding a component
07/06/23
Wednesday
Types of Window Components and Their Attributes
- These include labels, entry fields, text areas, command buttons, drop-
down menus,sliding scales, scrolling list boxes, canvases, and many
others.
3. Places the component in its grid position (the row and column are
required arguments)
Displaying Images
- This program adds two labels to the window. One label displays the
image.
The image label is first added to the window with an empty text string.
The program then creates a PhotoImage object from an image file and sets
the image attribute of the image label to this object.
- Like a label, a button can display an image, usually a small icon, instead
of a string.
When the user clicks Clear, the label is erased, the Clear button is
disabled, and the Restore button is enabled.
When the user clicks Restore, the label is redisplayed, the Restore button
is disabled, and the Clear button is enabled.
* An entry field is a box in which the user can position the mouse cursor
and enter a number or a single line of text.
* It allows a GUI program to take input text or numbers from a user and
display text or numbers as output.
Text Fields
* IntegerField and FloatField are used for the input and output of integers
and floating-point numbers, respectively.
* The methods getNumber and setNumber are used for the input and
output of numbers with integer and float fields.
Illustration: Take an input integer from a field, computes the square root
of this value, and outputs the result, rounded to the nearest hundredth, to a
second field.
* The program as written will run correctly if the inputs are integers, and
these integers are greater than or equal to 0. If the input text is not an
integer or is a negative integer, Python raises an exception
- The program detects the error, pops up the dialog to inform the user, and,
when the user closes the dialog, continues to accept and check input data.
- To recover gracefully from this event, we can modify the code of the
program’s computeSqrt method by embedding it in Python’s try-except
statement.
* In the try clause, our program attempts to input the data, compute the
result, and output the result, as before.
* Python will raise the ValueError in the getNumber method, if the datum
is not an integer, or in the math.sqrt function, if the integer is negative. In
either case, the except clause traps the exception and allows the user to
correct the input after closing the message box.