Question: PYTHON _ NESTED FOR LOOPS Write function GRAYSCALE using nested for loops and these two helper functions: def invert(filename): loads a PNG image from

PYTHON _ NESTED FOR LOOPS

Write function GRAYSCALE using nested for loops and these two helper functions:

def invert(filename): """ loads a PNG image from the file with the specified filename and creates a new image in which the colors of the pixels are inverted. input: filename is a string specifying the name of the PNG file that the function should process. No value is returned, but the new image is stored in a file whose name is invert_filename, where filename is the name of the original file. """ # create an image object for the image stored in the # file with the specified filename img = load_image(filename)

# determine the dimensions of the image height = img.get_height() width = img.get_width()

# process the image, one pixel at a time for r in range(height): for c in range(width): # get the RGB values of the pixel at row r, column c rgb = img.get_pixel(r, c) red = rgb[0] green = rgb[1] blue = rgb[2]

# invert the colors of the pixel at row r, column c new_rgb = [255 - red, 255 - green, 255 - blue] img.set_pixel(r, c, new_rgb)

# save the modified image, using a filename that is based on the # name of the original file. new_filename = 'invert_' + filename img.save(new_filename)

def brightness(rgb): """ takes the RGB values of a pixel (an [R, G, B] list) and returns a value between 0 and 255 that represents the brightness of that pixel. """ red = rgb[0] green = rgb[1] blue = rgb[2] return (21*red + 72*green + 7*blue) // 100

Write a function grayscale(filename)that loads the PNG image file with the specifiedfilename, creates a new image that is a grayscale version of the original image, and stores it in a file named gray_*filename*, where *filename* is the name of the original file.

The pixels of your grayscale image should be based on the brightness of each pixel. The brightness of a pixel [r,b,g] can be computed using this formula:

21r + 72g + 7b

Weve given you a helper function called brightness() that you should use to make this computation.

Once you have a pixels brightness, you should use it as the value forall three of the colorsof the grayscale version of the pixel. For example, the pixel [100,200,0] has a brightness of 165, and thus it should be replaced by the pixel [165,165,165] in the grayscale version of the image. For example, here is the grayscale version of spam.png:

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Programming Questions!