Black and White Filter

The good news is that most of the code we just made, we can recycle. In every single one of our filters, we want to get the size of the image, loop through every pixel, get the colors of each pixel, and set them to some new color. Taking a look back at our cyanify function, that’s every single line except for the line “red = 0”. Let’s just duplicate that function, change the name, and delete that one line

Which means that you’ll be starting with this as your template. The spot where we deleted “red = 0” is where we will put our new code.

def BlackandWhite(image):
    width, height = image.size
    for x in range(width):
        for y in range(height):
            red, green, blue = image.getpixel(x,y)
            
            image.putpixel((x, y), (red, green, blue))
    return image

When we see something that is a shade of gray, we are seeing an even mixture of every color. So if we want to translate a pixel in our image to a shade of gray, we would need to make sure that the red, green, and blue values are all equal to one another. However, we also want to make sure we don’t change the total brightness of the pixel. For example, if we have a pixel that has red = 90, green = 30, blue = 0, if we want to make a shade of gray, with the same overall brightness of that pixel, we need to make sure that all the numbers add up to the same total, 120. To do this in a program, we could take the average of the three numbers, and set the new red, green and blue values to that average, red = 40, green = 40, blue = 40.

On the right is an example of this function. Running this program will convert an image to its grayscale equivalent. Note that we are converting the average to an integer, we do this because sometimes dividing by 3 will give us a decimal

def BlackandWhite(image):
    width, height = image.size
    for x in range(width):
        for y in range(height):
            red, green, blue = image.getpixel(x,y)
            
avg = int((red + green + blue) / 3)
            red = green = blue = avg
            image.putpixel((x, y), (red, green, blue))
    return image