将灰度 JPEG 转换为 RGB JPEG

Convert a grayscale JPEG to an RGB JPEG

我有几张(实际上是几千张)颜色为灰色 space 的 jpg 图像,但我要使用它们的程序要求它们为 rgb。有什么方法可以将 jpg 从单色转换为 rgb 并且看起来仍然一样(即基本上使用 rgb 值来制作灰度图像)。

我在 MATLAB 中将图像作为二维矩阵,我尝试使用 imwrite 通过执行以下操作强制图像为 rgb:

imwrite(image, 'rgb.jpg')

我认为这可行,因为 imwrite 的文档说 jpg 应该是 rgb,但我仍然得到单色图像。

当您将 2D 矩阵保存为 JPEG 时,它仍然是灰度的。

imwrite(rand(100), 'test.jpg');

info = imfinfo('test.jpg');

%          FileSize: 6286
%            Format: 'jpg'
%             Width: 100
%            Height: 100
%          BitDepth: 8
%         ColorType: 'grayscale'    <---- Grayscale
%   NumberOfSamples: 1              <---- Number of Channels
%      CodingMethod: 'Huffman'
%     CodingProcess: 'Sequential'

size(imread('test.jpg'))
%   100   100

如果你想要得到的图像是真彩色的(即RGB),你需要在三维空间重复矩阵3次来创建separate red, green, and blue channels. We repeat the same value for all channels because any grayscale value can be represented by equal weights of red, green, and blue. You can accomplish this using repmat

imwrite(repmat(im, [1 1 3]), 'rgb.jpg')

info = imfinfo('rgb.jpg');

%          FileSize: 6660
%            Format: 'jpg'
%             Width: 100
%            Height: 100
%          BitDepth: 24
%         ColorType: 'truecolor'      <---- True Color (RGB)
%   NumberOfSamples: 3                <---- Number of Channels
%      CodingMethod: 'Huffman'
%     CodingProcess: 'Sequential'


size(imread('rgb.jpg'))
%   100   100   3