How can I convert RGB image to single channel grey image, and save it using python?

Question is simple. I have lots of 3-channel RGB images. (Their colors are already grey, but you know, RGB format.) What I want is converting them to grey-scale image with 1-channel.

I tried opencv to do it. But after I save it with png format, it ruined. I think structure of png file is the reason...

Anyway, is there any nice way to do this? Recommendation for 1-channel image format will also be really appreciated.

1 answer

  • answered 2019-01-11 10:07 Mark Setchell

    If you have a few dozen images, a quick way to convert them all to single-channel, greyscale images that OpenCV can read is with ImageMagick in the Terminal - it is included in most Linux distros and is available for macOS and Windows. So, to make a single channel 8-bit PGM version of all PNGs in the current directory:

    magick mogrify -format PGM -colorspace gray -depth 8 *.png
    

    If you have many hundreds or thousands of images, use GNU Parallel as well to get all your CPU cores running in parallel:

    parallel -X magick mogrify -format PGM -colorspace gray -depth 8 ::: *.png
    

    HOWEVER, I would not advise you do that because there are many other things you need to think about:

    • if your images contain important meta-data, you need to choose a format that retains it, which is not PGM

    • if your images contain floating point pixel data, you should maybe use TIFF format

    • if your purpose is to save disk space (which seems silly in this age of nearly free storage), you should consider a compressible format

    • if your purpose is to save RAM, there may be no need at all to do any of this as you can just convert your images to single-channel on load, e.g. OpenCV imread(...cv2.IMREAD_GRAYSCALE)

    So, you need to be clearer as to your data and your purposes. Note also that many people claim to want to save "memory" and they could mean disk or RAM.

    Bear in mind also that PNG can save 8 or 16-bit images, colour or greyscale and with or without a palette (depending on the number of colours) that subsequent applications may or may not be able to handle.