Reputation: 4333
Matlab stores the image as a 3-dimensional array. The first two dimensions correspond to the numbers on the axis of the above picture. Each pixel is represented by three entries in the third dimension of the image. Each of the three layers represents the intensity of red, green, and blue in the array of pixels. We can extract out the independent red-green-blue components of the image by:
redChannel = rgbImage(:, :, 1);
greenChannel = rgbImage(:, :, 2);
blueChannel = rgbImage(:, :, 3);
For example original image is:
If you display red green and blue channels you get these grayscaled images:
If you concatenate one of these channels with two black matrices (zero matrices) you get colored image. Let us concatenate each channel with black image matrices for remaining channels:
blackImage = uint8(zeros(rows, columns));
newRedChannel = cat(3, redChannel, blackImage, blackImage);
newGreenChannel = cat(3, blackImage, greenChannel, blackImage);
newBlueChannel = cat(3, blackImage, blackImage, blueChannel);
It outputs the following images:
Why does it work this way? Why individual channels for each color have to be concatenated with zero matrices (black images) for remaining channels in order for it be be colored when displaying? And why individual channels of colors are actually just grayscaled images if displayed individually?
Upvotes: 3
Views: 2350
Reputation: 45752
In MATLAB, greyscale images are represented as 2D matrices. Colour images as 3D matrices. A red image is still a colour image hence it still has to be a 3D image. Since is it a purely red image and thus has no other colours, the green and blue channels should be empty hence matrices of zeros.
Note also that when we say greyscale, we are really referring to an indexed image. So you can make this a colour image by applying a colourmap. If you were to apply a colourmap that ranges from black to red, then your 2D matrix would display as your red image above. The question is, how would MATLAB know what colourmap to apply? Yes, this does take up less space than a colour image. But it increases the complexity of your code.
On the other, ask yourself what you would expect an image to look like if you set two of the colour channels to zero? The only logical answer is exactly the separate colour channel images you have created above.
If you like, try an rephrase your question to "how else could MATLAB have implemented this?". In other words, if your red channel was a 2D image, how would MATLAB know it is a red channel and not a green channel or a greyscale image? Challenge yourself to think of a more practical way to represent these data. I think this exercise will convince you of the merit's of MATLAB's design choice in this matter.
Also it is worth noting that many file formats, e.g. .bmp, work the same way.
Upvotes: 8