PPM Module
- We’ve already done some image manipulation
- But it was per-pixel so it was possible to read treat the PPM file as a 1-dimensional list
- Today we are going to do more complicated image manipulation that requires pixel operations using neighboring pixels
- This requires a 2D list, or matrix, of pixel data
- You know how to read PPM files and how to create matrices
- But to save you some time, you can use a module I created that does that for you - import ppm image = ppm.read_image("glorious_image.ppm") pixel = image[0][0]
- The read_imagefunction returns a 2D list of pixels
- Each pixel is represented with a list of three integers, for the red, green, and blue channels - import ppm image = ppm.read_image("glorious_image.ppm") pixel = image[0][0] red = pixel[0] green = pixel[1] blue = pixel[2]
Modifying Images
- If you want to do something for every pixel in the image, need to use nested loops to iterate over all combinations of row and column values - import ppm image = ppm.read_image("glorious_image.ppm") for row in ppm: for col in ppm: pixel = image[row][col][1] = 0 pixel = image[row][col][2] = 0
Writing Images
- Writing a 2D list of pixels to a PPM file is as easy as reading - import ppm ppm.write_image("boring_image.ppm", image)
- Just specify the file name and the 2D list of pixels
- Warning: the ppm module does no imput verification, you must specify a 2D list of lists containing 3 integers, anything else will cause it to fail in unclear ways 
Copying Images
- Sometimes you need to create a new image, without modifying the old one
- Be careful, you can not copy a list with an assignment statement due to aliasing - image = ppm.read_image("glorious_image.ppm") image_copy = image # DANGER! This is an alias, not a copy
- To actually copy an image, you need to create a new 2D list - image = ppm.read_image("glorious_image.ppm") num_rows = len(image) num_cols = len(image[0]) new_image = [] for row in range(num_rows): new_row = [] for col in range(num_cols): pixel = image[row][col] new_pixel = [pixel[0], pixel[1], pixel[2]] new_row.append(new_pixel) new_image.append(new_row)