Convert RGB to Grayscale in ImageMagick command-line

前端 未结 7 1044
孤街浪徒
孤街浪徒 2020-12-23 16:16

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/#grays

相关标签:
7条回答
  • 2020-12-23 16:28

    A few ways to that in Imagemagick command line are:

    convert test.png -grayscale average gray_average.png
    
    or
    
    convert test.png -colorspace OHTA -channel r -separate +channel gray_average.png
    
    or
    
    convert test.png -intensity average -colorspace gray gray_average.png
    
    or
    
    convert test.png -colorspace HSI -channel blue -separate +channel gray_average.png
    


    See

    https://imagemagick.org/script/command-line-options.php#grayscale https://imagemagick.org/script/command-line-options.php#intensity https://imagemagick.org/script/command-line-options.php#colorspace

    0 讨论(0)
  • 2020-12-23 16:33

    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
    
    0 讨论(0)
  • 2020-12-23 16:33

    I use convert mostly to convert colour pictures of documents into grey-scale pdf documents in order to perform OCR. My best results are using Rec709Luminance. So I recommend

    convert colourpicture.png -grayscale Rec709Luminance greyscalepicture.png
    

    Short command, nice outputs.

    0 讨论(0)
  • 2020-12-23 16:35

    Seems like you are taking the red channel to do that, on convert test.png -colorspace OHTA -channel r -separate +channel gray_average.png i prefer the green channel (i heard that way works on tv sice ancient days, maybe the best)

    0 讨论(0)
  • 2020-12-23 16:47

    To batch convert images in Fish shell:

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

    0 讨论(0)
  • 2020-12-23 16:52

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

    0 讨论(0)
提交回复
热议问题