Oddify

This filter is going to take an image, and simplify it into only 8 colors, we will do this by setting each color value (r, g, b) to max if it’s above the halfway point (127) or to zero if it’s below.

Start by copying the code from the cyanify filter, change the name to oddify, and delete the line where we set “red = 0”

def oddify(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

We will need some if/else statements for this section of code, and while we can do the if statements in the way we did before, python has a neat shortcut that we can use to save some space on coding. Consider our red pixel. While we could set up an if statement in the following way…

if(red > 127):
    red = 255
else:
    red = 0

That is a lot of code to do something so simple. Luckily python gives us a way to squish simple if/else assignments like this in one line. The below code will function in exactly the same way as the if statement above, but it has the benefit of being nice and concise:

red = 255 if red > 127 else 0

In the following function, we will use this version of the if/else statement to set our pixel values. As a little piece of trivia, when we do if statements in this way, they are called a ternary operator

When we add the code to change the color of each color band, we get the following.

def oddify(image):
    width, height = image.size
    for x in range(width):
        for y in range(height):
            red, green, blue = image.getpixel(x, y)
            red = 255 if red > 127 else 0
            green = 255 if green > 127 else 0
            blue = 255 if blue > 127 else 0
            image.putpixel((x, y), (red, green, blue))
    return image