Search code examples
image-processingimagemagickimagemagick-convert

Show only all non-black, non-white pixels with Imagemagick


I have a (greyscale) image that is almost entirely, but not quite, bitonal. I'd like to see all the pixels that aren't exactly black or white.

How can I do this with Imagemagick?


[I figured out one way, I'll still accept the best other method!]


Solution

  • ImageMagick has a more or less reverse version of "-opaque" if you start it with a plus "+" instead of a dash "-". This command will change all pure white and pure black pixels to white, and all other pixels to red...

    magick bw_img.png -colorspace rgb ^
      -fill white -opaque black -fill red +opaque white result.png
    

    After setting the colorspace, the first "-opaque" operation will fill every pure black pixel with white. All the white pixels are, of course, already white.

    Then change the fill color to red, and the "+opaque" operation will fill every pixel that is not pure white with red.

    That is in Windows syntax. For "nix systems, that continued-line caret "^" should be changed to a backslash "\" or just turn the command into a single line.

    For ImageMagick v6 change "magick" to "convert".

    Edited to Add...

    Your solution using "-transparent" is effective, and may be the best answer for some workflows. Keep in mind there is a similar option with a plus "+" you can use with the "-transparent" operator. Just as an example, this will create a totally transparent version of an input image...

    magick logo: -background none -transparent red +transparent red result.png
    

    First it changes every pure red pixel to transparent, then it turns everything that is not pure red to transparent.