2
votes

I have a few (actually a couple thousand) jpg images that have a color space of gray, but the program that I want to use them for requires that they be in rgb. Is there some way to convert the jpg from monochrome to rgb and still have it look the same (i.e. basically using rgb values to make a grayscale image).

I have the images as 2D matrices in MATLAB, and I've tried to use imwrite to force the image to rgb by doing:

imwrite(image, 'rgb.jpg')

I thought this would work since the documentation for imwrite says that jpg's should be in rgb, but I still get a monochrome image.

1

1 Answers

3
votes

When you save the 2D matrix to a JPEG it is still going to be grayscale.

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

If you want the resulting image to be truecolor (i.e. RGB), you need to repeat the matrix in the third dimension 3 times to create 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