Search code examples
imagemagicktransparencyminimagick

Determine image content using ImageMagick


Is it possible to easily determine whether or not an image has any actual content beyond just transparency using ImageMagick?

The back story is that I am cropping a image with unknown content, but a known area map (think game skins). The area I'm cropping for part of this will either contain something or it won't. If it contains something, I need to do something with it. If it doesn't, I need to scrap it and move on. Thanks!


Solution

  • I have a couple of ideas you could try, but I have not seen your images, so you will need to test them out.

    Firstly, you could count the number of colours in the image, like this:

    identify -format "%[k]" input.png
    

    If there is only transparency, the number of colours will be 1, if there are other colours in the image, it will be greater than one. This cannot differentiate between a pure single colour image and a purely transparent image though. That may, or may not, be a problem. I don't speak Ruby, but I believe you access k like this in Ruby:

    image["%[k]"]
    

    Secondly, you could calculate the mean pixel colour of the image, like this:

    identify -format "%[mean]" input.png
    

    That will be zero in the case of a fully transparent image. However it will also be zero for a fully black image, which may or may not be a problem.

    Both of these parameters can also be seen using

    identify -verbose input.png
    

    If you wanted a more robust test, for example to differentiate between a fully trasnparent image and a fully black image, you could use one of the tests above, and combine it with getting the value of a single pixel at top left of image to rule out the odd edge cases above, like this:

    convert black.png -format "%[pixel:p{0,0}]" info:
    black
    
    convert transparent.png -format "%[pixel:p{0,0}]" info:
    none
    

    Another option would be to calculate the histogram, like this and see the colours:

    convert input.png -format %c histogram:info:-