""" CS 101 image manipulation examples """ from PIL import Image def justBlue(image): """Return a new image containing just the blue values from an image. The input should be a PIL image object created using something like image = Image.open(filename), where filename is a string. """ # create a copy of the original image so we don't lose the original newImage = image.copy() # create our 2D structure of pixels from the image so we can work with individual pixels pixels = newImage.load() # get the bounding box -- this is returned as a tuple and we use some python # magic to automatically break the tuple up into four variables minX,minY,width,height = image.getbbox() # iterate over every pixel in the image for y in range(height): for x in range(width): # get the rgb value of the pixel (as a tuple in the order (red, green, blue)) rgb = pixels[x,y] # set the pixel to a new RGB value (in this instance, we keep the original # blue value and set the red and green to 0) pixels[x,y] = (0,0, rgb[2]) # return the new image return newImage def grayscale(image): """Return a new grayscale version of an image. The input should be a PIL image object created using something like image = Image.open(filename), where filename is a string. """ # create a copy of the original image so we don't lose the original newImage = image.copy() # create our 2D structure of pixels from the image so we can work with individual pixels pixels = newImage.load() # get the bounding box -- this is returned as a tuple and we use some python # magic to automatically break the tuple up into four variables minX,minY,width,height = image.getbbox() # iterate over every pixel in the image for y in range(height): for x in range(width): # get the rgb value of the pixel (as a tuple in the order (red, green, blue)) rgb = pixels[x,y] # set the pixel to a new RGB value # average of red, green, blue avg = int((rgb[0] + rgb[1] + rgb[2]) / 3) pixels[x,y] = (avg, avg, avg) # return the new image return newImage """ Example usage in the shell: >>> img1 = Image.open('statue.jpg') >>> img1_gray = grayscale(img1) >>> img1_gray.show() >>> img1_gray.save('statue_gray.png') """