image-processingcolorsrgbcmyk

How do I (very approximately) generalize the name of the color based in it's CMYK or RGB numbers?


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.


Solution

  • Let's take this as a starting image:

    enter image description here

    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:

    enter image description here

    Now, we just ask imageMagick to map all the pixels in the original image to whatever colour is nearest in the colours in our map:

    magick artistic-swirl.jpg +dither -remap map.png result.png
    

    enter image description here

    Now we look at the distribution of pixels in the colormap of the result:

    magick identify -verbose result.png | grep -A9 Histogram
    

    Output

     Histogram:
          5063: (0,0,0) #000000 black
         40831: (0,0,255) #0000FF blue
          2831: (0,255,0) #00FF00 lime
         44027: (0,255,255) #00FFFF cyan
         61648: (255,0,0) #FF0000 red
         29828: (255,0,255) #FF00FF magenta
         38729: (255,255,0) #FFFF00 yellow
         27043: (255,255,255) #FFFFFF white
    

    And we can see there are 5063 pixels that are black, and 40831 pixels that are blue... and so on.

    Note that you can do all this with wand which is a Python binding to ImageMagick.