Skip to content
Snippets Groups Projects
gtRandCmap.m 1.67 KiB
function cmap = gtRandCmap(maxval, bgcolor)
% GTRANDCMAP  Creates a random colourmap of 'maxval' random colours
%
%   cmap = gtRandCmap(maxval[, bgcolor])
%   ------------------------------------
%
%     INPUT:
%       maxval  = <uint>    Maximal value of the color map
%       bgcolor = <double>  RGB color code for background color {[0 0 0]}
%                 <string>  Can also be 'black' or 'white'
%
%     OUTPUT:
%       cmap    = <double>  Color map 2D matrix [maxval+1 by 3]
%                           (first line is background color)


    if ~exist('bgcolor', 'var') || isempty(bgcolor)
        bg = [0 0 0]; % black background
    elseif ischar(bgcolor)
        if strcmpi(bgcolor, 'black')
            bg = [0 0 0];
        elseif strcmpi(bgcolor, 'white')
            bg = [1 1 1];
        else
            gtError('gtRandCmap:wrong_background_color_value', ...
                ['Unsupported background color value: ' bgcolor]);
        end
    elseif (isfloat(bgcolor) && size(bgcolor, 1) == 1 && size(bgcolor, 2) == 3)
        if between(bgcolor, [0 0 0], [1 1 1])
            bg = bgcolor;
        else
            gtError('gtRandCmap:wrong_background_color_value', ...
                'Background RGB values should be set in [0 , 1]!');
        end
    else
        gtError('gtRandCmap:wrong_background_color_value', ...
            ['Unsupported background color value: ' bgcolor]);
    end

    maxval = max(maxval, 1);
    cmap = rand(uint64(maxval), 3);

    % Increase brightness of dim colours
    int = sum(cmap, 2);
    indx = int < 1;
    cmap(indx, :) = 2 * cmap(indx, :) ./ int(indx, [1 1 1]);
    cmap(cmap > 1) = 1;

    % Add background
    cmap = [bg; cmap];

end % end of function