MIT 6.100L Introduction to CS and Programming Using Python, Fall 2022 · Problem set 5, 1) Colorblindness Filters — filter · Dr. Ana Bell · CC BY-NC-SA 4.0 · MIT publishes no solution for this set; the worked solution is ours
Write filter(pixels_list, color), which simulates colorblindness: it applies a colorblindness transformation to every pixel in a list of RGB pixels and returns the list of transformed pixels.
The human eye contains two types of photoreceptive (light sensitive) cells: rods and cones. Rods are responsible for vision in low light environments, such as at night, and cones are responsible for color vision. There are three types of cones, each responsible for a particular color, that is, red, green and blue. The red, green and blue cones all work together allowing you to see the whole spectrum of colors. For example, when the red and blue cones are stimulated in a certain way, you will see the color purple.
The condition known as colorblindness typically manifests as a deficiency in one of these types of cones; for example, protanopia is a lack of sensitivity to red light. The objective of this part is to create filters to simulate these differences. We can replicate the effects of colorblindness with a matrix multiplication between a colorblindness transformation matrix and the RGB values of a particular pixel, which are represented as a vector with 3 entries. You do not need to know anything about matrix multiplication.
filter takes in a list of pixels in RGB form, such as [(0,0,0),(255,255,255),(38,29,58)...], as well as a color: 'red', 'blue', 'green', or 'none'. The purpose of this function is to apply a transformation to the pixels in the input list that simulates impairment in the cones of the input color. Return the list of transformed pixels.
make_matrix function supplies a matrix representing the appropriate transformation depending on the input string: for example, make_matrix('red') returns the matrix representing a red deficiency in one's vision.matrix_multiply(matrix1, matrix2). The transformation matrix must be the first argument and the RGB pixel vector the second, or else the resulting image will be incorrect.matrix_multiply returns a list of floats, and the pixels must be tuples of ints. Convert each value with round() or int(); either is accepted.print(matrix_multiply(make_matrix('none'), (38, 29, 58))) # [38.0, 29.0, 58.0] print(filter([(0, 0, 0), (255, 255, 255), (38, 29, 58)], 'none')) # [(0, 0, 0), (255, 255, 255), (38, 29, 58)] print(filter([(180, 160, 80), (120, 10, 240)], 'red')) # [(171, 171, 99), (72, 71, 184)]
Adapted for the browser: Pillow and numpy are not available, so the image arrives as its list of pixels and MIT's img_to_pix and pix_to_img, which only open and save image files, are left out; matrix_multiply is a pure-Python version of MIT's numpy helper with the same name, arguments and result; and the tests compare pixel values where MIT graded the filtered image_15.png by eye.