#!/usr/bin/env python ''' image_example.py Jeff Ondich, 28 October 2015 Using the Python Imaging Library (PIL, https://python-pillow.github.io/) to directly modify pixels. Over-commented for pedagogical purposes. ''' import sys import argparse from PIL import Image def main(args): # Open the original image's file as an Image object. try: image = Image.open(args.input_image) print >>sys.stderr, 'Original image:', image.format, image.size, image.mode except: print >>sys.stderr, 'Can\'t open image {0}'.format(args.image) exit() # Use the load() method to get direct access to the image's pixels. pixels = image.load() # Create a new image, the same size as the original. Initialize to black # and load() the pixels. new_image = Image.new('RGB', image.size, (0, 0, 0)) new_pixels = new_image.load() # For each pixel in the original image, convert the RGB values to a gray value # and assign the corresponding pixel in the new image that value for R, G, and B. # Note that the RGB's range from 0 to 255, so their average does, too. for y in xrange(image.height): for x in xrange(image.width): red = pixels[x, y][0] green = pixels[x, y][1] blue = pixels[x, y][2] gray = (red + green + blue) / 3 new_pixels[x, y] = (gray, gray, gray) # Save the final image to the output file. new_image.save(args.output_image) # Display both images on screen, if appropriate. if args.show: image.show() new_image.show() if __name__ == '__main__': parser = argparse.ArgumentParser(description='Transforms a color image into a grayscale image.') parser.add_argument('input_image', help='The name of the image to carve') parser.add_argument('output_image', help='The name of the file in which to save the resulting image') parser.add_argument('--show', action='store_true', help='Displays both the original and the transformed image (in addition to saving the transformed image in the output_image file)') args = parser.parse_args() main(args)