使用imagemagick将灰度的JPG图像转换为RGB格式

18

我正在尝试使用imagemagick命令行工具将灰度图像转换为RGB。

对于PNG图像,以下命令可以正常运行:

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

(取自回答“如何使用ImageMagick在命令行中将灰度png图像转换为RGB”)

虽然使用identify -format %r result.png仍会返回DirectClass Gray,但我可以看到它已经成功通过gdalinfo进行了转换,因为现在列出了3个波段/通道:

gdalinfo [成功转换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

然而,似乎 -define 选项 只适用于PNG图像。

我的问题:我如何在JPG图像中实现相同的效果?

当我尝试对JPG使用上述命令时,它不起作用:

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

gdalinfo [未能成功转换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
2个回答

19

PNG颜色类型不适用于JPEG图像,因此您无法使用相同的技术。尝试强制将颜色空间设置为sRGB,和/或将类型设置为TrueColour,以便您不会得到一个调色板图像:

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

3
非常感谢你的快速回复。 记录一下:convert input.jpg -type truecolor result.jpg 运行良好。虽然添加 -colorspace sRGB 也产生了相同的结果,但单独使用并不能完成任务。 - NotYanka
无法处理PNG文件,我尝试了-colorspace sRGB -type truecoloralpha,但我的图像是8位的,我不想将其转换为PNG24。 - Shayan
@Shayan 如果你有问题,请像往常一样发布一个带有图片的问题来询问。 - Mark Setchell
根据ImageMagick论坛上的这篇帖子,您还需要使用-define colorspace:auto-grayscale=off。我想灰度检测是在保存时应用的,之前的任何转换都不会强制执行颜色空间。@Shayan - Alexis Wilke
使用PNG格式时,需要指定前缀“PNG24:”以将图像从灰度8位转换为彩色24位。 - fmw42

1

ImageMagick无法处理png文件,但ffmpeg可以。

使用以下命令可以在test.png文件中进行转换:

ffmpeg -loglevel warning -i ${file} -sws_flags "lanczos+accurate_rnd+full_chroma_int+full_chroma_inp+bitexact" -y -pix_fmt rgb8 test.png

输出文件的深度为8位(也适用于rgba → rgb)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接