Search code examples
imageimagemagick-convert

Count how many pixels with a specific color in an image?


I want to loop through a folder of images and output to console how many pixels are #333212, how many are #332211 etc. Is this possible in PHP? I found a package that manipulates images but not one that can detect colors of each pixel. Does such a tool or function exist in the PHP library?

EDIT: Doesn't have to be in PHP, the less packages I have to install the better.


Solution

  • You can do this quite easily with ImageMagick, like this. Say we want to count the red pixels...

    # First create a little test strip with black, white, red, green and blue parts
    convert -size 50x50 xc:black xc:white xc:red xc:lime xc:blue +append out.png
    

    enter image description here

    Now convert anything non-red to black so that only red pixels remain

    convert out.png -fill black +opaque red n.png
    

    enter image description here

    Now count the red pixels by cloning the resulting picture and making the clone fully black (by setting everything to zero), and running a comparison to count how many pixels are not black

    convert n.png                    \
        \( +clone -evaluate set 0 \) \
        -metric AE -compare          \
        -format "%[distortion]" info:
    2500
    

    And 2500 looks like 50px by 50px to me :-)

    Note

    The AE is the Absolute Error, i.e. a simple count of the number of differing pixels. The -format "%[distortion]" info: part causes ImageMagick to output the count (%distortion) as a number (info:) rather than as an image.

    Obviously, you replace red with "#333212" for your problem.

    You can also do all that in one visit, like this:

    convert input.png               \
       -fill black +opaque red      \
       \( +clone -evaluate set 0 \) \
       -metric AE -compare          \
       -format "%[distortion]" info: