Now let’s go ahead and start programming our first filter. This filter will go through every pixel in an image, setting every red value to zero, but keep the green and blue values the same. The end result will make it look like everything is cyan-shifted.
Start by defining a function, called cyanify. Make sure to declare this function before the line “name = openfiledialog”. This function will take a variable called “image” as a parameter, which will be the image that we edit.
def cyanify(image):
The image class keeps track of where each individual pixel is located with a set of x and y coordinates. If you’re unfamiliar, the x position corresponds to how far over from the left a pixel is, and the y position is how far down it is from the top. So if we have a pixel at the location x = 20, y = 40, that corresponds to a pixel that’s 20 pixels from the right and 40 from the top.
The handy thing about this system is we can use them to loop through every row and column fairly easily. Code the lines on the right. If you have an image that’s 40 wide by 20 tall, this will loop through every x value between 0 and 40, and every height between 0 and 20.
def cyanify(image):
width, height = image.size
for x in range(width):
for y in range(height):
Now that we have the body of our loop, let’s go ahead and code what we want to do to each pixel. First, get the red, green, and blue values of the pixel at the current spot with the image.getpixel() function, which takes the coordinates of the pixel to change. Then, change the red value to zero. Once that is done, you can replace the pixel there with the new red, green and blue values with the image.putpixel() function, which takes a set of numbers for the location, and a set of numbers representing the three color values. End your function with the line “return image”, making sure that it is indented only once. This will give back the complete image only once it has run through every pixel.
def cyanify(image):
width, height = image.size
for x in range(width):
for y in range(height):
red, green, blue = image.getpixel(x, y)
red = 0
image.putpixel((x, y), (red, green, blue))
return image
Now that we have our function defined, we can call it right before we display our image, like on the right
name = filedialog.askopenfilename()
img = Image.open(name)
img = img.convert("RGB")
img = cyanify(img)
img.show()
Running this program should produce a result like the one to the left, where the original image now looks cyan-shifted