JES functions/commands for files and
pictures
- pickAFile
returns a string with the file that was picked
- >>>
filename = pickAFile()
>>> filename
'C:\\Documents and Settings\\DevonJeff\\Desktop\\Jeff
School\\banner.jpg'
- pickAFolder
returns a string that has a folder or directory
writePictureTo
saves a picture that is in memory to a given file on the hard drive
- example
to ask where to put a picture and then save it:
>>> folder = pickAFolder()
>>> filename =
folder + "mypicture.jpg"
>>> writePictureTo(filename)
- makePicture
loads a picture into memory from a file
- >>> pic = makePicture(filename)
>>> pic =
makePicture(pickAFile())
- show
displays a picture on the screen
repaint
redraws a picture on the screen, showing any changes your functions have
done
- >>> show(pic)
- >>> repaint(pic)
- getPixel
gets a pixel from the specified column and row of a picture
- >>> pixel = getPixel(pic, 0, 0)
- getWidth
and getHeight
get the width and height of a picture
- >>> width = getWidth(pic)
>>> height = getHeight(pic)
- getRed,
getGreen,
and getBlue
get the value for each component in a pixel
setRed,
setGreen,
and setBlue
set the value for each component in a pixel
- example
to make the pixel half as bright as before:
>>> r = getRed(pixel)
>>> g =
getGreen(pixel)
>>> b =
getBlue(pixel)
>>> setRed(pixel, r/2)
>>> setGreen(pixel, g/2)
>>> setBlue(pixel, b/2)
- getColor
gets an entire color that has red, green, and blue packaged all into one
setColor
sets an entire color all at once
- example
to copy the color from one pixel to another:
>>> pixel1 = getPixel(pic, 0, 0)
>>> pixel2 =
getPixel(pic, 0, 1)
>>> color =
getColor(pixel1)
>>> setColor(pixel2, color)
- getPixels
returns an array/list that contains all pixels from the picture
- example
to use getPixels with a for loop to make the picture shades of red:
for p in getPixels(pic):
setGreen(p, 0)
setBlue(p, 0)
- makeColor
creates a color from given red, green, and blue values
- example
to create the color green and set a pixel to that color:
>>> color = makeColor(0, 255, 0)
>>>
setColor(pixel, color)
- makeEmptyPicture creates a
picture of specified width, height, and background color
- example to create a 100x200
picture that is all green
>>> color = makeColor(0, 255, 0)
>>> newPic =
makeEmptyPicture(100, 200, color)
- distance calculates the
distance between two colors.
If color1 has rgb values r1, g1, b1, and color2 has rgb values r2,
g2, b2, then distance(color1, color2) is equal to
sqrt( (r1-r2)*(r1-r2) + (g1-g2)*(g1-g2) + (b1-b2)*(b1-b2) )
- >>> distance(white,
black)
441.6729559300637
>>>
distance(black, red)
255.0
JES functions/commands for sounds
- makeSound loads a sound file
into JES.
play
plays a sound that has been loaded into JES. It does not wait for any other sounds to finish playing
before it plays.
blockingPlay
plays a sound that has been loaded into JES. It waits for any other sounds to finish playing before
it plays.
getLength
gets the number of samples in a sound.
getSamplingRate
gets the sampling rate.
getSampleValueAt
gets a sample value in the sound.
You specify the index of the sample you want (0 for first, 1 for
next one, etc.).
setSampleValueAt
sets a sample value in the sound
You specify the index of the sample you want (0 for first, 1 for
next one, etc.).
getSamples
gets an array/list that has all the sound samples in it. Each thing in the array is a
“sound object” that has the sample value and the index of where it is in
the sound. So that is like a
pixel of a picture.
getSampleValue
gets the sample value of a sample object.
setSampleValue
sets the sample value of a sample object.
writeSoundTo
writes a sound object to a file, it works much like
writePictureTo
makeEmptySoundBySeconds
creates an empty sound that is a certain number of seconds long
makeEmptySound
creates an empty sound that is a certain number of samples long
- >>> sound
= makeSound(pickAFile())
>>> # play it but
wait for the last sound to stop
>>>
blockingPlay(sound)
>>> # play it
right away
>>> play(sound)
>>> # get the
number of samples
>>> numSamples =
getLength(sound)
>>> print
numSamples
>>> # get the
sampling rate
>>> sampleRate =
getSamplingRate(sound)
>>> # compute
duration in seconds, using "+ 0.0 trick"
>>> # to make sure
it does floating point division
>>> seconds =
(numSamples + 0.0) / samplingRate
>>> # get the
first sample in the sound
>>> value =
getSampleValueAt(sound, 0)
>>> # change the
first sample in the sound
>>>
setSampleValueAt(sound, 0, value*2)
- # increase the volume of the sound
def increaseVolume(sound):
for s in getSamples(sound):
val =
getSampleValue(s)
setSampleValue(s, val*2)
blockingPlay(sound)
- # save a sound to a file
def saveSound(sound):
folder = pickAFolder()
file = folder + "mysound.wav"
writeSoundTo(sound, file)
- # empty sound 1 second long at 22050 samples/second
>>> newSound = makeEmptySoundBySeconds(1, 22050)
# empty sound 22050 samples long at 22050 samples/second,
# so also 1 second long.
>>> newSound = makeEmptySound(22050, 22050)
Other JES functions
- printNow prints a string to
the command area right away (without waiting for the program to finish
like print does)
requestString
displays a message box and gets a string from the user
requestInteger
displays a message box and gets an integer from the user
- def annoying():
there = false
while not there:
printNow("Driving,
driving, driving to vacation... ")
s =
requestString("Are we there yet? (y for yes) ")
if (s == "y"):
there = true
- >>> x = requestInteger("How old are you? ")
>>> # say the person entered 7
>>> print "In 5 years, you will be", x+5, "years
old"
In 5 years, you will be 12
years old
Python builtin functions
- range gives an array/list of
numbers, and is often used with for loops
- >>> range(2, 5)
[2, 3, 4]
>>> range(5)
[0, 1, 2, 3, 4]
>>> range(0, 10, 2)
[0, 2, 4, 6, 8]
- ord gives the ASCII “number value”
of a letter/character
- >>> ord(‘a’)
97
>>> ord(‘b’)
98
>>> ord(‘A’)
65
- abs gives the absolute value of a
number
- >>> abs(10.1)
10.1
>>> abs(-10.1)
10.1
- max gives the maximum of a bunch
of values
min gives the minimum of a
bunch of values
- >>> max(10, 5, 20, 7)
20
>>> min(10, 5, 20, 7)
5
- int gives just the “integer part”
of a number, even if it was a floating point number
- >>> int(10.1)
10
>>> int(10)
10
- float gives a number that is a
floating point number, even if you give it an integer
- >>> float(1)
1.0
>>> 1/2
0
>>> float(1)/2
0.5
Python keywords
- def
is used when defining a new function
return
is used to return a value from a function
for
is used when making a for loop
in
is used when making a for loop
- example
to create a function that uses a for loop to add up 1+2+…+n and return
the result
def addNumbers(n):
sum = 0
for i in range(1, n+1):
sum = sum + i
return sum
- print
is used to display a message to the screen
- To
display a list of things, separate them by commas
>>> print "hello"
hello
>>> print "1 + 2 =", 1+2
1 + 2 = 3
- if
is used to make Python do something “only if” something else is true
else
is used in combination with if to do one thing if some condition is true
and otherwise do something else
and or not
are used with the if to have more complicated tests for the if
true false
are used to mean true or false
- example
to check what grade range a number is in:
if (score >= 90):
print "A work"
if (score < 90 and score >= 80):
print "B work"
if (score < 80 and score >= 70):
print "C work"
if (score > 100 or score < 0):
print "Problem,
problem, crashing computer, oh dead..."
- if (score >= 90):
print "A work"
else:
print "not A work"
- >>> true
1
>>> false
0
>>> (2 == 2)
1
>>> (2 == 1)
0
- import
is used to load functions from another file, so you can use them in the
file you are working on right now.
setLibPath
is used to tell JES where to look for your Python files. When you do an import, JES will
look at that path for the Python file.
- (in file called someFile.py)
def someFunction():
print "hello world,
from some file... "
- (in some other file, called for example
anotherFile.py)
from someFile import *
def anotherFunction()
someFunction()
- >>> # in the next, pick the folder
where someFile.py is
>>> setLibPath(pickAFolder())
>>> anotherFunction()
hello world, from some
file...
- while
is used to make a loop that happens as long as some condition is true
- def add1ToN(n):
# adding up numbers 1 to n
total = 0
i = 1
while (i <= n):
total = total +
i
i = i + 1
return total
Very often used lines of code
- >>> pic = makePicture(pickAFile())
- >>> sound = makeSound(pickAFile())
- >>> sound = note(300, 1, 20500)
- >>> setLibPath(pickAFolder())
- >>> from cs151functions import *
Special characters in Python
- + * - / % are used for addition,
multiplication, subtraction, division, and remainder/modulus
. the period is used to make a
floating point number
- Numbers
can be either integers (whole numbers) or floating point numbers
(numbers with a decimal point).
% can only be used with integers. With integers, / does “integer division” (it gets rid
of the remainder).
>>> 3 * 3 / 2
4
>>> 3 * 3.0 / 2
4.5
>>> 15 / 7
2
>>> 15 % 7
1
- The period
is used to make a floating point number.
- ‘ ’ “ ” single or double quotes are used to specify a
string/text in Python
- Strings/text
can be appended/concatenated to each other using +
>>> "hello" + "
" + "world"
‘hello world’
- = is used to save a value into a
variable, called variable assignment
- >>> message = "hello world"
>>> myPic = makePicture(pickAFile())
>>> x = 2
>>> x
2
>>> message
‘hello world’
- ( ) are used for order of operations with arithmetic,
and
are also used when defining and calling functions
- >>> 3 * (2 + 5)
21
>>> range(3)
[0, 1, 2]
- : is used when defining functions
and when using a for loop
- First
line of a function –
def myFunction(variable1, variable2,
variable3):
First line of a for loop – for
p in getPixels(pic):
- # is used to make a comment in
Python – everything on a line starting with # is completely ignored
by Python, but the person reading your code can still read it
- # This line is a comment, Python ignores is
- , comma is used in between
different inputs to functions – both when they are called and when
they are defined like in the following
- First
line of function – def
myFunction(var1, var2):
Call the function – >>>
myFunction(10, 11)
- \ the backslash is a special
character that can be used in strings to create some “special” characters.
- Because
of this, to put a backslash in a string, you have to type \\
- >>> mystring = "What \\ are you
talking about? "
>>> print mystring
What \ are you talking
about?
- FYI,
\ can be used to print “new line” with \n and tab with \t
- [ ] square brackets are used when
Python displays an array/list.
You can also use [] to get a certain element of an array.
- >>> range(0,5)
[0, 1, 2, 3, 4]
>>> numbers = range(5, 10)
>>> numbers
[5, 6, 7, 8, 9]
>>> numbers[0]
5
>>> numbers[3]
8
- < <= > >= == comparison operators used with if. You can also use them on the
command area to test them out.
Python will show 1 if the condition evaluates to true, and 0 for
false
- >>> (10 < 11)
1
>>> (11 < 10)
0
>>> (10 < 11 or 11 < 10)
1
>>> (10 < 11 and 11 < 10)
0
General programming concepts
- Variables. A variable gives you a name that
you can use for a part of memory.
When you assign a value to a variable,
you are putting that value into memory and keeping a name that you can use
to get to that memory again.
So when you type >>> pic
= makePicture(pickAFile()) you are putting the picture into memory, and you have
the name pic that you can use to get to that picture in the rest of your
code.
- Functions. Defining functions gives you a way
to write some Python code and then use them again multiple times without
having to retype the commands each time. A function is defined so that it can take certain inputs
that are given to it each time the function is executed or invoked. In Python we give names to the
function inputs on the first line of the function definition, like
“ def myFunc(input1, input2):
”. So when you type “ >>> myFunc(1, 2) ”, Python
will start running your function and will start by setting input1 = 1 and
input = 2 before running the lines of code in your function. A function
can also produce an output by using the return
keyword. For example, if a
line like “ return 42 ” is
executed inside of the function myFunc, then running “ >>> x = myFunc(1, 2) ” would
result in the variable x having the value 42.
- For loops. A for loop gives you a convenient
way to make the same lines of code execute many times in a row, for
example to execute the same lines of code for every pixel in a picture. The for loop is executed in
phases. In the initialization
phase, a line like
“ for p in getPixels(pic): ” will
create an array of all the pixels in the picture pic. After this, the for loop is ready
to be run the first time. p
is set to be the first pixel in the array of pixels. Then the lines of code that are
indented for the for loop are executed. Those lines of code can use p as a variable to access
that pixel. After the lines
of code are executed, we “loop back” to the top of the for loop, p is set
to be the next pixel in the pixels array, and the lines of code are
executed again. The second
time the lines of code are executed, p is now the second pixel in the
array of pixels, so any changes to p will change the second pixel in the
array of pixels. This process
is repeated for all pixels in the array of pixels.
- If/conditional. An if test is a line that will
have Python check whether some condition is true or false. For example, you could test if a
variable redValue is greater than 100. You indent the next lines so that if the condition is true,
then Python will execute those lines; if the condition is false, then
Python will not execute those lines.
In order to make different types of conditions, you can use the
comparison operators (<, <=, >, >=, ==) and also the Boolean
operators (and, or, not).
- Functions,
variables, for loops, and if/conditionals are some of the basic concepts
of programming that are very important. Programming would be a royal pain without them, and
these concepts are used in just about any programming language you might
use. With these basic
concepts, you make a computer do just about anything you want it to…
- Bits and bytes. A bit is either 0 or 1, and is
the smallest amount of information we could store. A byte is 8 bits, so there are 2^8
= 256 different possible values.
- Overflow. We only have some number of bytes
to store a number on a computer.
For example, a picture uses 8 bits for the red value of a pixel. This means there is a maximum and
minimum that a value can have on the computer. For the red value of a pixel, the max is 255 and the
min is 0. If the number is
already at the max, and we try to add to it, we call that overflow. Sometimes the computer could give
us an error when we try to do this.
Or it might treat anything bigger than 255 as 255. Or it might do “wrap
around”, meaning 255+5 = 5.
Picture concepts
- Picture is “matrix of pixels”. A picture to a computer is just a
bunch of pixels. Pixels are
tiny dots that are so small we can’t really tell they are dots when we are
looking from far enough away.
By making the dots small enough, we don’t notice and the picture
looks normal. So a picture to
a computer is a matrix of pixels – a matrix has a width and a
height, and each pixel in the picture can be specified by its location in
the matrix with (x, y) value specifying the column and row in the
picture. Programming
languages almost always start counting from 0, so the upper left hand
pixel is in position (0, 0) and the bottom right is in position (height-1,
width-1).
- Color of pixel is RGB. Humans have three different color
sensors in their yes, roughly corresponding to red, green, and blue. This means that if we specify how
bright the red, green, and blue components are of a color, that fully
specifies what it looks like to humans (for color-blind people, we would
only need to specify two components because they only have two different
types of color receptors).
What this means is that the computer only needs to store the
intensity of red, green, and blue to recreate a color on the screen. Thus the color of each pixel is
defined by its red, green, and blue values. These values can be between 0 and 255. 0 means no brightness, and 255
means maximum brightness.
- Make black and white. For each
pixel, compute brightness, and if greater than a certain amount make it
white, else make it black.
- Copying pictures. When trying to copy or mirror
part of a picture to another (or to itself), first identify the ranges of
the pixels you are going to do something to. Then for some arbitrary pixel (x, y) in that range,
what is the formula for where you want to copy the pixel from? Check that what you plan to do
makes sense by looking at small example, like a picture that is 10 pixels
by 5 pixels.
- Removing red eye. For each pixel, check if the
color is close to that in the “red eye” part, and if it is then change it
to black.
- Darken or lighten. You can darken pixels by
multiplying their red, green, and blue values all by the same amount (like
.5 for example). You can
lighten the pixels by multiplying by an amount greater than 1 (and then
check to make sure value is not greater than 255).
Sound concepts
·
What is
sound. Sound is just
variations in pressure in air (or water if you happen to be underwater). The parts of our ear responsible for
sound are sensitive to these changes in pressure and will vibrate
accordingly. The brain takes this
information and we “hear” sound.
At any given point (like the tip of a microphone), we can look at how
the pressure is varying over time.
It will get larger, smaller, etc. as the sound travels through the
air. We can then graph this value
to get a curve. The curve might
look something like a sine curve.
·
What is a
speaker/microphone. A speaker
wants to “make sound”. Since sound
is just variations in pressure, the speaker pushes on the air to create the
variation in pressure. A
microphone is just a speaker in reverse.
It is like a little speaker that will get pushed in and out with
variations in pressure, and this creates a difference in voltage or current
that can then be recorded by the computer.
·
How is
sound stored on the computer.
To store sound on the computer, we just take the “pressure reading” at
regular intervals. We use really
small intervals, short enough that our ears won’t know the difference when we
recreate the sound based off of the pressure readings at these short
intervals. Each pressure reading
is called a sample. One way to
view this is that a sound file on the computer is regular-spaced points on the
sound curve. A sound file is made
up of: what is the sampling rate, and what are the sample values (the
regularly-space points on the curve).
·
Parts of
the curve, sound lingo. The frequency of something is just how often
it happens, normally per second.
Frequency is measured in hertz. 100 hertz would mean 100 times per
second. The frequency of sampling
is just the number of samples per second.
The frequency of a sound wave is the number of times it repeats per
second. So 400 hertz would mean it
repeats 400 times per second. That
would mean the part that is repeating is 1/400 of a second long. This is called the period or cycle length.
·
The amplitude
of a sound wave is just the maximum distance the curve gets away from the
baseline. We hear higher amplitude
curves as being louder – there is a greater difference in pressure, so
that makes sense.
·
We hear higher frequency sounds as having a
higher pitch, and lower frequency sounds as having a lower pitch.
·
An octave
is a range of sound frequencies from some value to double that value. So the sound frequencies between 200 and
400 hertz is an octave. The reason
we split it up like this is because doubling or halving a sound frequency makes
it still sound like the same note to us (a C note, maybe).
·
Splicing
sounds. If we have two
different sound objects, we can make a third object that has the first one
followed by the second one. The
third one would have to be as long as the other two combined, and we could use
for loops to copy the values.
·
Blending/adding
sounds. If we want to put two
sounds together so we hear both at the same time, we can create a third sound
where the sample values just come from adding the sample values of the two
sounds. This could result in
“overflow”, so we can get around that by blending the two sounds instead of
adding (add them up and divide by two).
·
Clipping
(or selecting part of a sound).
We could copy just part of a sound into another sound by changing what
the ranges are on the for loop.
·
Normalizing
sound. This is multiplying all
sample values in a sound by some value so that the maximum sample value is the
maximum value allowed (32767 for 16-bit samples).
·
Stereo
versus mono sound. Stereo
sound is actually made up of two different sound objects, one for the left
speaker and one for the right speaker.
In JES, we are using mono sounds – just a single sound wave that
goes to both speakers.
Common mistakes/advice
- Python is case sensitive with
keywords, function names, and variables. You have to use the right spelling and upper/lower case
for each letter when calling JES functions, Python functions, creating and
using your own variables, and creating and using your own functions.
- Follow the rules of using ( ) when
calling functions. You need
the ( right after the name of the function, then the inputs to the
function, then ). And you
cannot have extra ), so range(10)) would be an error.
- Create a variable before using it. You can only get/read/use the
value of a variable if the variable has already been created by assigning
something to it before.
- Variable assignment has variable on
left hand side of =. So “
2 = x ” is an error.
- First line of function definition and
for loop needs to end with :
- The “body” of a function definition
needs to be indented two spaces extra on each line.
- The “body” of a for loop needs to be
indented two spaces extra (in addition to the two spaces for the
function) on each line. If
you have one for loop inside of another, the second for loop needs to have
each line be indented an additional two spaces more than the first for
loop.
- Do not assign a value to a JES or Python
function. If you do
something like
“ setColor = 10 ”, Python will
let you do this but it is a mistake.
This creates a variable called setColor that is a number with the
value 10. The problem is that
you now won’t be able to call the JES function setColor anymore. At this point, you should close
JES and open it again so that it forgets about the mistaken value you
assigned to setColor.
- Load a function before calling it
and reload it each time after you have changed it.
- Use repaint(pic) rather than show(pic)
because repaint will make sure to redraw the picture.
- When trying to write a new program,
find one we have done in class or one in the book that is the most
similar to the new one you need to write. Then you can just make changes to the other program to
make it do what you want.
- When trying to call a function,
make sure you are calling it correctly. This means giving it the right number of
inputs/parameters and the right kind of inputs/parameters. For example, if you try something
like “getWidth(0, 0)” that is an error. getWidth wants you to give it a picture as input, not
two numbers.
Advice on
steps to write a program/function
(1) Understand
exactly what it is supposed to do, e.g., what would a picture look like after
running the function on it.
(2) Write
down a way that you would do this - the basic idea, a few sentences (e.g., for
red eye removal, change any pixel that is close to red to black).
(3) Write
down "pseudocode" - the basic outline of what your program will look
like to achieve what you want to do. For example, with red eye removal it could
be something like
a.
function definition line, take a picture as input.
b.
for each pixel in the picture do the following.
c.
if the pixel's red value is above 200, then change the
pixel's color to be black.
(4) Take
your pseudocode and write your function.
(5) Debug/test your function. If you do the other steps right and
take your time with them, this step won’t be too bad. If you don’t do the other steps, this step can take FOREVER.
Each step along the way you are getting
more and more precise about how exactly you are going to solve the problem. If
you take your time and think things out, you will get to the final solution
much faster! DO NOT JUST START
TYPING without understanding the problem or what you are typing. If you do not understand what you have
typed, then it almost certainly will not work!!
Debugging techniques
- Python error messages. READ THE MESSAGE and try to
understand what it is telling you.
Normally it tells you the line that the error is on. It will often tell you that a
function is not being called correctly (wrong number of parameters/inputs,
wrong type of parameters/intputs, etc.). Or it might tell you something like “The error
was:y Name not found
globally” – this means you tried to use a variable called y, but
that Python did not find one, so you probably have a misspelling or
miscapitalization somewhere.
Also, go through the “Common mistakes/advice” above to see if any
of those is a problem.
- “Trace code” – think like Python. If you can’t figure out what a
Python error is, or if there is no error but your function is not doing
what it should, start thinking like Python. Pretend you are Python and start keeping track of
exactly how you will execute the lines of code. On paper, keep track of what the values of variables
are as you think about what each line of code is doing. When you get to a for loop, go
through the steps of thinking about what happens the first time the for
loop is run, what happens the second time, etc.
- Explain <click> button. To remember how to use a JES
function and see an example, type the name of the function in the program
area, make sure the cursor is in the function you want to use, then click
on the “Explain <click” button.
JES functions are the ones that appear purple in the program area.
- Common sense – does the output
make sense? You should
always apply common sense when running your code. If the picture is supposed to be
shades of red with the original image still there, did that happen? If not, then you don’t have the
right answer yet.
- Use the MediaTools Picture Tool to
look at individual pixels in your picture. This is a quick way to look at the RGB values of pixels
in your picture. You can also
use getPixel along with getColor or getRed, getGreen, and getBlue to look
at the color value of individual pixels.
- Look at individual pixels to make sure
is what should be. If you
are supposed to do some transformation to a picture and are not sure if
your function works right, then start looking at individual pixels. Look at what the RGB values are
before your function is called and what the RGB values are after your
function is called. What
should the changed values be?
- To find Python error, comment things
out. If you can figure
out what the Python error is, start commenting out lines of code to make
your function simpler. If you
remove some lines of code and the error is still happening, you know the
error is not on the lines of code you just commented out. Keep “making the function simpler”
until you find the error.
- Repaint inside of for loop or
not. Normally, I put a
repaint at the very end of the function, but NOT inside of the for loop
(not indented like the other parts inside the for loop). So it then it just repaints the
picture when everything is done.
If you put the repaint INSIDE of the for loop (so indented like the
other things in the for loop), you can see how the picture is being
updated as it goes – and this might give you some insight about what
is going on.
- Send me your code! If you are confused, feel free to
send me your code in an email.
Next time I am on my computer, I will look at it and try to help
(oftentimes, you will get a response within a few minutes if I am on my
computer when you send the message).
- Look at the results of your program. Run your program then look at the
output (a sound or picture, or whatever) and make sure it seems to look
like what it should look like.
This is called a sanity check. If you tried to multiply numbers, you should get an
answer that is larger – if you got a smaller number then something
must be wrong. If something
does not make sense, then go back and trace through the code to see what
is happening.