Convert grayscale to RGB

조회 수: 16 (최근 30일)
Naz
Naz 2012년 8월 19일
댓글: mohd akmal masud 2017년 12월 4일
I wish to convert a grayscale image to RGB where I would have color-to-black scale instead of white-to-black scale. Let's say I have a specific color given by [r g b] components. I want the image to present the shades of this color, not the shades of gray. My pO2values will range from 1 to 128, so I use jet(128) to create a gamma of 128 colors from blue all the way to red. Then, I determine what rgb components represent that color. For example, if my pO2value is 60, it will correspond to some green color specified by [r g b] components. Now, I want my grayscale image to be 'greenscale', that is green-to-black gradient instead of original white-to-black gradient.
  • generating r g b is equivalent of me selecting a color pixel using your demo
  • don't see cat() in your script
im=zeros(512,512,3);
im(:,:,1)=I; %where I is 512x512 uint8 grayscale image
im(:,:,2)=I;
im(:,:,3)=I;
% I create a desired color using values from jet spectrum
c = 128;
pO2value=60;
map = jet(c);
pO2value=double(pO2value);
r = ceil(map(pO2value,1)*128);
g = ceil(map(pO2value,2)*128);
b = ceil(map(pO2value,3)*128);
% here's what I got from Image Analyst's demo code
hsv = rgb2hsv(im);
hueImage = hsv(:, :, 1);
selectedPixelRGB = [r g b];
hsvOfThisPixel = rgb2hsv(selectedPixelRGB);
% Make the hue plane of the hsv image this same hue
hsv(:, :, 1) = hsvOfThisPixel(1);
hueImage2 = hsv(:, :, 1);
% Convert back to rgb space.
singleHueRGBImage = hsv2rgb(hsv);
imshow(singleHueRGBImage);
However, I get an error:
??? Attempted to access r(:,2); index out of bounds because size(r)=[1,1,1].
Error in ==> rgb2hsv at 74 g = r(:,2); b = r(:,3); r = r(:,1);
Here is an example of what I am trying to do:
  댓글 수: 6
Naz
Naz 2012년 8월 19일
편집: Naz 2012년 8월 19일
Exactly! which I still did not figure out how to do. What I am trying to do is creating an image of solid color and scale the intensity across the image using my grayscale image.
c = 128;
map = jet(c);
pO2value=double(109); % 109 is an arbitrary number out of 1:128
r = ceil(map(pO2value,1)*c);
g = ceil(map(pO2value,2)*c);
b = ceil(map(pO2value,3)*c);
R=r*ones(size(I));
G=g*ones(size(I));
B=b*ones(size(I));
rgbImage = cat(3, R.*I/255, G.*I/255, B.*I/255);
imshow(rgbImage);
Not working...
Image Analyst
Image Analyst 2012년 8월 19일
편집: Image Analyst 2012년 8월 19일
If my two lines of code do exactly what you want, then why didn't you use them? Your code picks a color of (128, 12, 0). If you want to use that mixed color, then you're back to adapting my code. But you have to do it the way I said, with rgb2hsv and hsv2rgb, not the way you did it.
See my second answer. I adapted it for you since it seems like you are having trouble doing it.

댓글을 달려면 로그인하십시오.

채택된 답변

Image Analyst
Image Analyst 2012년 8월 19일
Try it like this if you want to pick some color out of the jet colormap:
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 20;
% Create a jet colormap
c = 128;
map = jet(c);
pO2value=double(109); % 109 is an arbitrary number out of 1:128
r = ceil(map(pO2value,1)*c)
g = ceil(map(pO2value,2)*c)
b = ceil(map(pO2value,3)*c)
% Now let's do it to a gray scale image.
% Read in a standard MATLAB gray scale demo image.
grayImage = imread('cameraman.tif');
handleToFigure2 = figure;
subplot(2,2,1);
imshow(grayImage);
title('Gray Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Convert the gray image into RGB so we can get it into hsv space.
rgbImage = cat(3, grayImage, grayImage, grayImage);
hsv = rgb2hsv(rgbImage);
% Make the hue plane of the hsv image this same hue
hsvOfThisPixel = rgb2hsv([r g b])
hsv(:, :, 1) = hsvOfThisPixel(1);
% Make the saturation 1 so we'll see color.
% Originally it was zero which meant that the image would be gray.
hsv(:, :, 2) = 1;
% Convert back to rgb space.
singleHueRGBImage = uint8(255*hsv2rgb(hsv));
% Display the new, single hue color image.
subplot(2, 2, 2);
imshow(singleHueRGBImage);
title('New, Single Hue Color Image', 'FontSize', fontSize);
message = sprintf('Done with demo.');
uiwait(msgbox(message));
  댓글 수: 1
Naz
Naz 2012년 8월 19일
Oh, yeah... This is what I need. Thank you very much Image Analyst, great answer.

댓글을 달려면 로그인하십시오.

추가 답변 (1개)

Image Analyst
Image Analyst 2012년 8월 19일
편집: Image Analyst 2012년 8월 19일
This is pretty easy. Just compute the HSV image. Then assign the hue channel to the desired hue. The whole hue channel is just that one single number for every pixel in the hue channel so that the entire image is just that one hue. Then convert from hsv color space back to rgb color space. If you need help, just copy, paste, and run this demo that I whipped up in about 5 minutes. The first part of the demo does it for a color image (you pick the color there), and the second part repeats it for a gray scale image.:
clc; % Clear the command window.
close all; % Close all figures (except those of imtool.)
imtool close all; % Close all imtool figures.
clear; % Erase all existing variables.
workspace; % Make sure the workspace panel is showing.
format longg;
format compact;
fontSize = 14;
% Change the current folder to the folder of this m-file.
if(~isdeployed)
cd(fileparts(which(mfilename)));
end
% Check that user has the Image Processing Toolbox installed.
hasIPT = license('test', 'image_toolbox');
if ~hasIPT
% User does not have the toolbox installed.
message = sprintf('Sorry, but you do not seem to have the Image Processing Toolbox.\nDo you want to try to continue anyway?');
reply = questdlg(message, 'Toolbox missing', 'Yes', 'No', 'Yes');
if strcmpi(reply, 'No')
% User said No, so exit.
return;
end
end
% Read in a standard MATLAB color demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'peppers.png';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
if ~exist(fullFileName, 'file')
% Didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
rgbImage = imread(fullFileName);
% Get the dimensions of the image. numberOfColorBands should be = 3.
[rows columns numberOfColorBands] = size(rgbImage);
% Display the original color image.
handleToFigure = figure();
subplot(2, 2, 1);
imshow(rgbImage, []);
title('Original Color Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
uiwait(msgbox('Pick a color that you would like to make the image into.'));
[x y] = ginput(1)
% Plot cross hairs at that point.
hold on;
plot(x, y, 'w+', 'MarkerSize', 50);
% Convert the image into hsv space.
hsv = rgb2hsv(rgbImage);
row = int32(y);
column = int32(x);
selectedPixelRGB = rgbImage(row, column, :)
hsvOfThisPixel = rgb2hsv(selectedPixelRGB)
% Make the hue plane of the hsv image this same hue
hsv(:, :, 1) = hsvOfThisPixel(1);
% Convert back to rgb space.
singleHueRGBImage = hsv2rgb(hsv);
% Just for fun, show the red, green, and blue channels.
% Extract the individual red, green, and blue color channels.
redChannel = singleHueRGBImage(:, :, 1);
greenChannel = singleHueRGBImage(:, :, 2);
blueChannel = singleHueRGBImage(:, :, 3);
subplot(4, 3, 7);
imshow(redChannel);
title('Red Channel Image', 'FontSize', fontSize);
subplot(4, 3, 8);
imshow(greenChannel);
title('Green Channel Image', 'FontSize', fontSize);
subplot(4, 3, 9);
imshow(blueChannel);
title('Blue Channel Image', 'FontSize', fontSize);
% Just for fun, show the hue, saturation, and value channels.
% Extract the individual hue, saturation, and value channels.
hueChannel = hsv(:, :, 1);
saturationChannel = hsv(:, :, 2);
valueChannel = hsv(:, :, 3);
subplot(4, 3, 10);
imshow(hueChannel);
title('New, Uniform Hue Channel Image', 'FontSize', fontSize);
subplot(4, 3, 11);
imshow(saturationChannel, []);
title('Saturation Channel Image', 'FontSize', fontSize);
subplot(4, 3, 12);
imshow(valueChannel, []);
title('Value Channel Image', 'FontSize', fontSize);
% Display the new, single hue color image.
subplot(2, 2, 2);
imshow(singleHueRGBImage);
title('New, Single Hue Color Image', 'FontSize', fontSize);
message = sprintf('Done with demo.\n\nFor the pixel at x = %d, y = %d,', column, row);
message = sprintf('%s\nthe (R, G, B) of the pixel = (%d, %d, %d), and', ...
message, selectedPixelRGB(1), selectedPixelRGB(2), selectedPixelRGB(3));
message = sprintf('%s\nthe Hue of the pixel = %f', message, hsvOfThisPixel(1));
uiwait(msgbox(message));
% See if they want to do it for a grayscale image.
promptMessage = sprintf('Do you want to Continue processing a gray scale image,\nor Cancel to abort processing?');
titleBarCaption = 'Continue?';
button = questdlg(promptMessage, titleBarCaption, 'Continue', 'Quit', 'Continue');
if strcmp(button, 'Quit')
return;
end
% Now let's do it to a gray scale image.
% Read in a standard MATLAB gray scale demo image.
folder = fullfile(matlabroot, '\toolbox\images\imdemos');
baseFileName = 'cameraman.tif';
% Get the full filename, with path prepended.
fullFileName = fullfile(folder, baseFileName);
% Check if file exists.
if ~exist(fullFileName, 'file')
% File doesn't exist -- didn't find it there. Check the search path for it.
fullFileName = baseFileName; % No path this time.
if ~exist(fullFileName, 'file')
% Still didn't find it. Alert user.
errorMessage = sprintf('Error: %s does not exist in the search path folders.', fullFileName);
uiwait(warndlg(errorMessage));
return;
end
end
grayImage = imread(fullFileName);
handleToFigure2 = figure;
subplot(2,2,1);
imshow(grayImage);
title('Gray Image', 'FontSize', fontSize);
% Enlarge figure to full screen.
set(gcf, 'units','normalized','outerposition',[0 0 1 1]);
% Convert the gray image into RGB so we can get it into hsv space.
rgbImage = cat(3, grayImage, grayImage, grayImage);
hsv = rgb2hsv(rgbImage);
% Make the hue plane of the hsv image this same hue
hsv(:, :, 1) = hsvOfThisPixel(1);
% Make the saturation 1 so we'll see color.
% Originally it was zero which meant that the image would be gray.
hsv(:, :, 2) = 1;
% Convert back to rgb space.
singleHueRGBImage = uint8(255*hsv2rgb(hsv));
% Display the new, single hue color image.
subplot(2, 2, 2);
imshow(singleHueRGBImage);
title('New, Single Hue Color Image', 'FontSize', fontSize);
message = sprintf('Done with demo.');
uiwait(msgbox(message));
% Close the figure.
% close(handleToFigure); % Close all figures (except those of imtool.)
% close(handleToFigure2); % Close all figures (except those of imtool.)
  댓글 수: 1
mohd akmal masud
mohd akmal masud 2017년 12월 4일
Dear Image Analyst
How about change grayscale to rgb for image dicom?

댓글을 달려면 로그인하십시오.

카테고리

Help CenterFile Exchange에서 Convert Image Type에 대해 자세히 알아보기

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by