Exercises for Lesson 16

Back to Lesson 16

Exercise 1: Grayscale based on human perception

We can choose the grayscale value for a pixel using the following calculation:

Y = 0.2126 * R + 0.7152 * G + 0.0722 * B

Fill in the following program. It should compute Y for each pixel, and color that pixel (Y,Y,Y) instead. Note that you’ll need an image to run it. Here is one you can use, just save it in a folder named images that lives in the same folder as your code: cheddar.gif.

from graphics import *

def getGrayscaleColor(image, x, y):
    """
    Converts the pixel to grayscale using the formula
       Y = 0.2126*r + 0.7152*g + 0.0722*b.

    r: the red channel (int in the range 0 to 255)
    g: the green channel (int in the range 0 to 255)
    b: the blue channel (int in the range 0 to 255)
    returns: the result of color_rgb (int in the range 0 to 255)
    """
    return None # replace with your code

def createGrayscaleImage(origImage):
    """
    Creates a copy of the original image, and colors it grayscale.

    origImage: the original image (graphics.py Image object)
    returns: the grayscale image
    """
    return None # replace with your code

def processImage(filename, outputFolder="."):
    # Load the original image
    image = Image(Point(0,0), filename)
    width = image.getWidth()
    height = image.getHeight()

    # Create the window to display both images
    win = GraphWin("Image Processing", width*2, height)

    # Draw the original image
    image.move(width/2, height/2)
    image.draw(win)

    # Create the grayscale image
    grayscaleImage = createGrayscaleImage(image)
    grayscaleImage.move(width, 0)
    grayscaleImage.draw(win)
    grayscaleImage.save(f"{outputFolder}/grayscale.png")

    # Exit after the user clicks
    win.getMouse()
    win.close()

def main():
    processImage("images/cheddar.gif")

if __name__ == "__main__":
    main()

Back to Lesson 16

Exercise 2: Mixing for and while

Consider the following program. How many times does the print() statement execute? What is printed when this program runs?

def divide(n):
    for i in range(n):
        j = i
        while j > 0:
            print(i, j)
            j = j // 2

def main():
    num = 6
    divide(num)

if __name__ == "__main__":
    main()

Back to Lesson 16