I’m a maker and love creating 8-bit art, mostly with wood. I have a new project in the works where I need an exact count of each pixel per a color. I started to manually count them before I stopped myself and thought, why don’t I just write a script to automate this!? Thus pixel-color-count.py was born!
Pixel Color Count
Given a valid image file, the Python script will iterate through each pixel in an image keeping a running tally of how many times the color of the pixel has appeared in the image.
Once the loop is done, the script will print to the console a list of each color and the number of times the color was present in the image.
Sample Output of pixel-color-count.py
Built With
Pillow
I used Pillow, a fork of PIL (Python Image Library), for the image manipulation. This is my second project using Pillow. It’s a really great library for programmatically editing or manipulating images.
with Image.open(args.image) as image:
color_count = {}
width, height = image.size
rgb_image = image.convert('RGB')
The main functionality from the Image
module I’m using is the getpixel
method.
rgb = rgb_image.getpixel((x, y))
webcolors
A second dependency for the project is more of a nice to have: webcolors. Given a color in RGB format, webcolors will return a human readable name for it if applicable.
name = webcolors.rgb_to_name(rgb)
webcolors.rgb_to_name
will throw a ValueError
is it cannot find a name for a RGB color. In my script, I fall back to displaying the color as a tuple.
What’s left to implement?
In my first iteration of the script, I started to implement an optional command line argument for ignored colors. The idea behind this is there may be some colors I don’t care to count therefore I wouldn’t want my output cluttered.
parser.add_argument('-i', '--ignore-color', type=tuple, help='Skip counting pixels of this color')
If the time permits, I’d love to go back and implement this feature. I hit a snag when I tried to use tuple
s as an argument type with argparse
.
UPDATE #1: The --ignore-color
command line option is partially implemented, but there’s no input validation. I basically accept the input as a string and use ast.literal_eval
to convert it to a tuple
.
Version 2 of the script, I plan on outputting a new version of the original image with a pixel legend and count per unique pixel color.
UPDATE #2: A version 2 of the script now exists that outputs an image featuring a legend with a color square matched with the color name and pixel count.
And, maybe for a version 3 turn it into a web accessible app.
UPDATE #3: A web version of the pixel color counter now exists. View the source for the project here.
For now, the script does just what I need and has saved me a lot of effort over counting the manual way!
pixel-color-count.py
Check the GitHub repo for new updates to the script. Here’s there first iteration: