Convert JPG image from grayscale to RGB using imagemagick

NotYanka picture NotYanka · Jan 19, 2016 · Viewed 12.6k times · Source

I am trying to convert gray scale images to RGB using the imagemagick command-line tools.

It is working fine for PNG images, using:

convert image.png -define png:color-type=2 result.png

(taken from an answer to "How to convert gray scale png image to RGB from comand line using image magick")

Although checking with identify -format %r result.png will still return DirectClass Gray, I can see it worked using gdalinfo as there are now 3 bands / channels listed:

gdalinfo [successfully converted PNG]:

Driver: PNG/Portable Network Graphics
Files: result.png
Size is 567, 479
Coordinate System is `'
Image Structure Metadata:
  INTERLEAVE=PIXEL
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0,  479.0)
Upper Right (  567.0,    0.0)
Lower Right (  567.0,  479.0)
Center      (  283.5,  239.5)
Band 1 Block=567x1 Type=Byte, ColorInterp=Red
Band 2 Block=567x1 Type=Byte, ColorInterp=Green
Band 3 Block=567x1 Type=Byte, ColorInterp=Blue

However, it seems the -define option is only working for PNG images.

My question: How can I achieve the same effect for JPG images?

When I try the above command for JPG, it does not work:

convert image.jpg -define jpg:color-type=2 result.jpg

gdalinfo [unsuccessfully converted JPG]:

Driver: JPEG/JPEG JFIF
Files: result.jpg
Size is 1500, 1061
Coordinate System is `'
Metadata:
  EXIF_ColorSpace=1
  EXIF_PixelYDimension=2480
  ...
  EXIF_YCbCrPositioning=1
  EXIF_YResolution=(300)
Corner Coordinates:
Upper Left  (    0.0,    0.0)
Lower Left  (    0.0, 1061.0)
Upper Right ( 1500.0,    0.0)
Lower Right ( 1500.0, 1061.0)
Center      (  750.0,  530.5)
Band 1 Block=1500x1 Type=Byte, ColorInterp=Gray
  Overviews: 750x531, 375x266, 188x133
  Image Structure Metadata:
    COMPRESSION=JPEG

Answer

Mark Setchell picture Mark Setchell · Jan 19, 2016

The PNG colour types do not apply to JPEG images, so you can't use the same technique. Try forcing the colorspace to sRGB, and/or setting the type to TrueColour so you don't get a palettised image:

convert input.jpg -colorspace sRGB -type truecolor result.jpg