Linux – Convert grayscale image into alpha channel image in unix shell

command lineimage editingimagemagicklinuxUbuntu

I have a gray-scale image. I want to convert it into an transparent PNG, such that the black pixels (in the original image) become fully opaque, the white pixels become fully transparent, a 50% grey pixel would become 50% transparent, and so on for all the shades in between.

How can I achieve this?

(Yes, I know that this is almost the same question as Converting grayscale shades into alpha channel, but I want to know how to do this using only command line tools – e.g. ImageMagick or NetPBM.)

Here is a sample result from the above-mentioned question. This sample is a result which I would like to achieve using only command-line tools.

Sample

If you open this PNG in a viewer that support transparency, you'll see what I mean.

Best Answer

Ooookay. After plenty of googling, and reading for more of the ImageMagick manual than I actually care for, here's the answer. Given that you have a grayscale image called source.png, here are my commands.

To make the make the black pixels transparent and keeps the white pixels as they are, run this command:

 convert source.png -alpha copy -fx '#fff' result.png

To instead make the white pixels transparent while keeping the black as-is, use:

 convert source.png -alpha copy -channel alpha -negate +channel -fx '#000' result.png

Let's explain that last command a bit more thoroughly:

  • convert – Is the ImageMagic command (one of several)
  • source.png – The greyscale source image.
  • -alpha copy – Copy contents of the previous file into the alpha channel.
  • -channel alpha – Specify that following operators only should affect the alpha channel.
  • -negate – Invert the alpha channel (will, because of the previous -chanel alpha not affect any other part of the image).
  • +channel – Specify that following operators only should should affect the color channels, and no longer modify the alpha channel. (This is the default, and therefore we need not provide it in the first, simpler example.)
  • -fx '#000' – Replace color channel contents with black pixels. (Because of +channel the alpha channel will not be affected).

It is quite important to include that final -fx option, otherwise all semi-transparent pixels in generated image will retain colors. (Since these pixels are half-transparent, it might not be obvious, but the end result is not what one expect.)

I found the list of ImageMagick options quite useful.

Related Question