Matt Sephton
Matt Sephton

Reputation: 4122

Convert a greyscale image to 1-bit black/white with definable threshold, maintaining transparency?

How can I convert a greyscale image to 1-bit black/white with definable threshold, but maintaining existing transparency/alpha?

Existing questions miss out the transparency part of my question.

Also, I need to do this on the command-line in macOS. ImageMagick's convert is one option, but not the only option.

Sample image: greyscale image

Required behaviour:

  1. pixels below a definable threshold are coloured black
  2. pixels above a definable threshold are coloured white
  3. transparent pixels remain untouched

I prepared this "goal" image manually:

goial

What I have tried:

  1. $ convert -threshold 50% in.png out.png

    • everything over threshold becomes white
    • everything below the threshold becomes transparent!
  2. $ convert -white-threshold 50% in.png out.png

    • everything over threshold becomes white
    • everything below the threshold becomes transparent!
  3. $ convert -black-threshold 50% in.png out.png

    • everything over a different threshold becomes white
    • nothing becomes black!
  4. $ convert +dither -monochrome in.png out.png

    • dithering disabled
    • 1-bit conversion locked to 50% but performs as expected
    • but: transparent pixels are turned black!
  5. $ convert -depth 1 -colors 3 -alpha set in.png out.png

    • almost there
    • but: threshold not definable!

Any thoughts appreciated!

Image Ref: http://www.studentshow.com/gallery/6097929/Pyramid-Module-Value-Grayscale

Upvotes: 4

Views: 2814

Answers (1)

fmw42
fmw42

Reputation: 53081

This works for me on IM 6.9.11.34 Q16 Mac OSX Sierra.

enter image description here

convert in.png -colorspace gray -channel rgb -threshold 50% +channel out.png

(In the above, you specify that the threshold should be applied only to the rgb channels and not the alpha via -channel rgb. After the threshold, I turn on all the channels again)

enter image description here

Upvotes: 6

Related Questions