Using PIL to leave only specific colors in an image.

By Samuel Muiruri | Dec. 27, 2018 | Python Scripts

Here's a step by step guide on using PIL to find the 3 most common colors in an image and create a grayscale image that highlights only these colors.


Start by importing PIL and returning a list of the RBG codes then you'll need to find the most common colours 

and from there get the top 3 from the result


 Okay now with this we can start creating the new image, I've put each functionality into a separate function so it's easier to explain and replace logic later on. Note that the task of finding the top colours using "pixel_index" is slow because it iterates over every pixel while creating a dictionary. It should be far more quicker if you create a new function with picked rbg codes you want to keep.

pixels_check will use the result of list of top colors and return True if the color is almost close to one in the top colors.


Finally the main function will get a string of the color name and create the new file. Remember to create a folder "colored" where your testing.

Now you can run this code and get your colourfest image

Here are some results from running this

Source Code: