Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I convert a color name to a 3 element RGB vector?

Tags:

colors

rgb

matlab

In many MATLAB plotting functions, you can specify the color as either a string or as a 3 element vector that directly lists the red, green, and blue values.

For instance, these two statements are equivalent:

plot(x, y, 'Color', 'r');
plot(x, y, 'Color', [1 0 0]);

There are 8 colors that can be specified by a string value: 'r','g','b','c','m','y','k','w'. Is there a MATLAB built-in function that converts these strings to an equivalent RGB vector?

like image 820
Marc Avatar asked Feb 07 '11 14:02

Marc


2 Answers

I found this general alternative on the MathWorks File Exchange which will even handle color strings other than the default 8 in MATLAB:

  • rgb.m by Ben Mitch

If you're only concerned with conversions for the default 8 color strings, here's a function I wrote myself that I use to convert back and forth between RGB triples and short color names (i.e. single characters):

function outColor = convert_color(inColor)

  charValues = 'rgbcmywk'.';  %#'
  rgbValues = [eye(3); 1-eye(3); 1 1 1; 0 0 0];
  assert(~isempty(inColor),'convert_color:badInputSize',...
         'Input argument must not be empty.');

  if ischar(inColor)  %# Input is a character string

    [isColor,colorIndex] = ismember(inColor(:),charValues);
    assert(all(isColor),'convert_color:badInputContents',...
           'String input can only contain the characters ''rgbcmywk''.');
    outColor = rgbValues(colorIndex,:);

  elseif isnumeric(inColor) || islogical(inColor)  %# Input is a numeric or
                                                   %#   logical array
    assert(size(inColor,2) == 3,'convert_color:badInputSize',...
           'Numeric input must be an N-by-3 matrix');
    inColor = double(inColor);           %# Convert input to type double
    scaleIndex = max(inColor,[],2) > 1;  %# Find rows with values > 1
    inColor(scaleIndex,:) = inColor(scaleIndex,:)./255;  %# Scale by 255
    [isColor,colorIndex] = ismember(inColor,rgbValues,'rows');
    assert(all(isColor),'convert_color:badInputContents',...
           'RGB input must define one of the colors ''rgbcmywk''.');
    outColor = charValues(colorIndex(:));

  else  %# Input is an invalid type

    error('convert_color:badInputType',...
          'Input must be a character or numeric array.');

  end

Note that this function allows you to input either a string of characters or an N-by-3 numeric or logical array (with RGB values from 0 to 1 or 0 to 255) and it returns the opposite color representation. It also uses the function ISMEMBER to do the conversions.

like image 62
gnovice Avatar answered Oct 24 '22 18:10

gnovice


I don't think there is a function for this in matlab. I suggest you use Marcs function, or this one-liner.

C = rem(floor((strfind('kbgcrmyw', C) - 1) * [0.25 0.5 1]), 2); 
like image 39
Ghaul Avatar answered Oct 24 '22 18:10

Ghaul