MATLAB: create a color map with three colors

I am trying to create a colormap in MATLAB, given three colors: high extreme, zero and low. My thought process was to loop from high extreme to the middle and store each step up to 3xN (the first column is R, the second is G, and the third is B). Therefore, I use:

%fade from high to zero oldRed=high(1); oldGreen=high(2); oldBlue=high(3); newRed=mid(1); newGreen=mid(2); newBlue=mid(3); currentRed=oldRed; currentGreen=oldGreen; currentBlue=oldBlue; for x=1:steps currentRed=oldRed+((x*(newRed-oldRed))/(steps-1)); currentGreen=oldGreen+((x*(newRed-oldRed))/(steps-1)); currentBlue=oldBlue+((x*(newRed-oldRed))/(steps-1)); cmap=[cmap;[currentRed currentGreen currentBlue]]; end 

Then I would do the same as from zero to a low limit. However, my code does not give me any useful matrix. Can anyone help me, how should I approach this?

+4
source share
3 answers

You can use linear interpolation to expand the color.

  nCol = 256; % number of colors for the resulting map cmap = zeros( nCol, 3 ); % pre-allocate xi = linspace( 0, 1, nCols ); for ci=1:3 % for each channel cmap(:,ci) = interp1( [0 .5 1], [low(ci) mid(ci) high(ci)], xi )'; end 
+5
source

Inspired by @Shai's answer, here is a small twist on his solution (which I prefer - it is more flexible and avoids using a for loop).

The cmap form you want is an nx3 array. Next, you say that you have three colors that you want to represent with three β€œbreakpoints” on your curve. It screams "interpolation"!

 % set the "breakpoints" for the color curve: lowValue = 0; midValue = 128; highValue = 255; % pick "any" three colors to correspond to the breakpoints: lowColor = [255 0 0]; midColor = [40 40 40]; highColor = [0 255 255]; % create the colormap: myMap = interp1( [lowValue midValue highValue], ... [lowColor; midColor; highColor]/255, ... linspace(lowValue, highValue, 256)); 

This provides a 256-color card that runs smoothly from lowColor with the lowest value (index 1 in the color palette) to highColor with the highest value (index 255 in the color palette).

I believe that this is exactly what you are looking for. And "look ma, don't loop!".

+3
source

I would use linspace:

 cmap=[linspace(oldRed,newRed,steps)' ... linspace(oldGreen,newGreen,steps)' ... linspace(oldBlue,newBlue,steps)']; 

And then, in order to do the same for your next step and combine them:

 cmap_full = [cmap;cmap2]; 
+1
source

Source: https://habr.com/ru/post/1487913/


All Articles