I am processing an image pixel by pixel and I need to get name of the color for each pixel. I have these main color names: yellow, magenta, cyan, red, green, blue, white, black. I also have RGB and CMYK numbers of each pixel. How would I approximate the color of the pixel to one of the above based on those numbers? It does not need to be precise, just a very general approximation. Is there any maths that I can do with RGB or CMYK to determine that? I would rather prefer a simple solution than a precise one.
2 Answers
Let's take this as a starting image:
Now, make a map of all the colours that we want to look for, bearing in mind that ImageMagick uses X11 colornames where green
is named lime
:
magick xc:black xc:white xc:red xc:lime xc:blue xc:cyan xc:magenta xc:yellow +append map.png
That makes this - which I have magnified because it is only 8 pixels wide and 1 pixel tall:
Now, we just ask imageMagick to map all the pixels in Paddington to whatever colour is nearest in the colours in our map:
magick paddington.png +dither -remap map.png result.png
Now we look at the distribution of pixels in the colormap of the result:
magick identify -verbose result.png | grep -A9 Histogram
Output
Histogram:
78839: ( 0, 0, 0) #000000 black
15057: ( 0, 0,255) #0000FF blue
1: ( 0,255, 0) #00FF00 lime
22422: ( 0,255,255) #00FFFF cyan
18103: (255, 0, 0) #FF0000 red
11: (255, 0,255) #FF00FF magenta
5809: (255,255, 0) #FFFF00 yellow
19758: (255,255,255) #FFFFFF white
And we can see there are 78839 pixels out of 400x400 that are black, and 15057 pixels that are blue... and so on.
Note that you can do all this with wand
which is a Python binding to ImageMagick.
While the other solution posted will work for KNOWN names, take a look at models and papers like this one to actually generalize and understand how to translate (even) unknown colors to useful names.
Edit: Even though this isn't what OP wanted, I ended up spending a couple of hours to wire it all up to work easily within Docker/VSCode. See here for a way to quickly get up and running with this repository.
I hope this helps someone!