Images: Chris Piech and Mehran Sahami CS106A, Stanford University
Images: Chris Piech and Mehran Sahami CS106A, Stanford University
Images: Chris Piech and Mehran Sahami CS106A, Stanford University
def main():
balance = int(input("Initial balance: "))
while True:
amount = int(input("Deposit (0 to quit): "))
if amount == 0:
break
balance = deposit(balance, amount)
Encapsulation Principle:
def deposit(balance, amount): Data used by a function
balance += amount
return balance
should be a parameter or
encapsulated in function
Learning Goals
1. Understanding how images are represented
2. Learning about the SimpleImage library
3. Writing code that can manipulate images
y
Piech + Sahami, CS106A, Stanford University
Pixels in an Image Close-Up
image = SimpleImage("flower.jpg")
for pixel in image:
# Body of loop
This code gets
# Do something with pixel repeated once for
each pixel in image
def darker(filename):
"""
Reads image from file specified by filename.
Makes image darker by halving red, green, blue values.
Returns the darker version of image.
"""
# Demonstrate looping over all the pixels of an image,
# changing each pixel to be half its original intensity.
image = SimpleImage(filename)
for pixel in image:
pixel.red = pixel.red // 2
pixel.green = pixel.green // 2
pixel.blue = pixel.blue // 2
return image
def red_channel(filename):
"""
Reads image from file specified by filename.
Changes the image as follows:
For every pixel, set green and blue values to 0
yielding the red channel.
Return the changed image.
"""
image = SimpleImage(filename)
for pixel in image:
pixel.green = 0
pixel.blue = 0
return image
for y in range(height):
for x in range(width):
pixel = image.get_pixel(x, y)
# do something with pixel
y (height) x (width)
for y in range(height):
for x in range(width):
pixel = image.get_pixel(x, y)
mirror.set_pixel(x, y, pixel)
mirror.set_pixel((width * 2) - (x + 1), y, pixel)
return mirror
Nothing!
We only want to use nested for loops if
we care about x and y.
(Needed that for mirroring image.)
Piech + Sahami, CS106A, Stanford University
Learning Goals
1. Understanding how images are represented
2. Learning about the SimpleImage library
3. Writing code that can manipulate images