3

I want to convert images to web-safe colors using MATLAB. Is there any predefined function for it? If not, what should be my first step to start off?

gnovice
  • 125,304
  • 15
  • 256
  • 359
ruchir patwa
  • 311
  • 1
  • 5
  • 13

2 Answers2

3

Look at the X = rgb2ind(RGB,MAP) syntax: http://www.mathworks.com/help/techdoc/ref/rgb2ind.html

http://en.wikipedia.org/wiki/Web_colors#Web-safe_colors appears to define the required MAP.

Ashish Uthama
  • 1,331
  • 1
  • 9
  • 14
3

Ashish has the right approach, but you may be finding it daunting to get all those values off of the web page and into a map that you can use. You have a couple of options for creating the map...

One option is to actually get the source for the page using the function URLREAD and parse out the numbers you need using the function REGEXP ("Did he just suggest parsing HTML with a regex?!" Yes, I did. What can I say? I'm a loner, Dottie. A rebel.):

mapURL = 'http://en.wikipedia.org/wiki/Web_colors#Web-safe_colors';
urlText = urlread(mapURL);
matchExpr = ['<td style="background: #\w{3};">' ...
             '(?:<u>\*)?(\w{3})(?:\*</u>)?</td>'];
colorID = regexp(urlText,matchExpr,'tokens');
colorID = char([colorID{:}]);
[~,webSafeMap] = ismember(colorID,'0369CF');
webSafeMap = (webSafeMap-1)./5;

However, after I did the above I realized that there is a nice regular structure to the resulting web-safe color map values. This means you could actually ignore all the above mess and generate the map yourself using the functions REPMAT and KRON:

colorValues = (0:0.2:1).';  %'
webSafeMap = [repmat(colorValues,36,1) ...
              kron(colorValues,ones(36,1)) ...
              repmat(kron(colorValues,ones(6,1)),6,1)];

And then you can easily recolor, say, an RGB image using the functions RGB2IND and IND2RGB. For example:

imageRGB = imread('peppers.png');  %# Load a built-in image
imageRGB = ind2rgb(rgb2ind(imageRGB,webSafeMap),webSafeMap);
imshow(imageRGB);

A web-safe version of peppers.png

Community
  • 1
  • 1
gnovice
  • 125,304
  • 15
  • 256
  • 359