Search code examples
image-processingcolorsimagemagickpixel

Image Magick / Detect colors contained on a image


What would be the simple process that would gives an array of the colors contained in an image ?


Solution

  • ImageMagick's "convert" command can generate a histogram.

    $ convert image.png -define histogram:unique-colors=true -format %c histogram:info:-
    
    19557: (  0,  0,  0) #000000 gray(0,0,0)
     1727: (  1,  1,  1) #010101 gray(1,1,1)
     2868: (  2,  2,  2) #020202 gray(2,2,2)
     2066: (  3,  3,  3) #030303 gray(3,3,3)
     1525: (  4,  4,  4) #040404 gray(4,4,4)
       .
       .
       .
    

    Depending on your language of choice and how you want the colors represented, you could go lots of directions from here. Here's a quick Ruby example though:

    out = `convert /tmp/lbp_desert1.png \
                   -define histogram:unique-colors=true \
                   -format %c histogram:info:- \
           | sed -e 's/.*: (//' \
           | sed -e 's/).*//'`
    
    out.split("\n")
        .map{ |row| row.split(",").map(&:to_i) }
    
    
    # => [[0, 0, 0], [1, 1, 1], [2, 2, 2], [3, 3, 3], [4, 4, 4] .....