Convert RGB to Grayscale in ImageMagick command-li

2019-03-09 00:47发布

问题:

How do I convert a RGB image (3 channels) to a grayscale one, using the (r+g+b)/3 method? I look through an examples page: http://www.imagemagick.org/Usage/color_mods/#grayscale but the desired method:

convert test.png -fx '(r+g+b)/3' gray_fx_average.png

gave me a wrong result - the resulted image has still 3 channels.

You can check this by running a command: identify -format "%[colorspace] <== %f\n" *.png.

回答1:

convert <img_in> -set colorspace Gray -separate -average <img_out> gives the best result for any image for me.



回答2:

Using the (r+g+b)/3 method will apply the effects of grayscale, but the image will remain in sRGB (which is the expected behavior for this method). You'll need to specify the desired colorspace along with the -fx command.

convert test.png -fx '(r+g+b)/3' -colorspace Gray gray_fx_average.png

Verify with identify -format "%[colorspace] <== %f\n" gray_fx_average.png

Gray <== gray_fx_average.png


回答3:

To batch convert images in Fish shell:

for file in *.jpg; convert -colorspace Gray $file $file; end;