function hist3d = MAP_hist3d(im)
%
% MAP_hist3d - produces the non-zero R,G,B histogram bins
% On input:
%     im (mxnx3 color image): input image
% On output:
%     hist3d (kx4 array): histogram bins
%          column 1: R-value
%          column 2: G-value
%          column 3: B-value
%          column 4: number of pixels with that R,G,B
% Call:
%     h3 = MAP_hist3d(DUC_team);
% Author:
%     T. Henderson
%     UU
%     SpringFeb 2007
%

[num_rows,num_cols,num_planes] = size(im);
hist3d = [-1,-1,-1,0];
num_rgb = 1;
for r = 1:num_rows
    for c = 1:num_cols
        r_index = floor(double(im(r,c,1)))+1;
        g_index = floor(double(im(r,c,2)))+1;
        b_index = floor(double(im(r,c,3)))+1;
        index = find((hist3d(:,1)==r_index)...
            &(hist3d(:,2)==g_index)...
            &(hist3d(:,3)==b_index));
        if isempty(index)
            num_rgb = num_rgb+1;
            hist3d = [hist3d; r_index,g_index,b_index,1];
        else
            hist3d(index,4) = hist3d(index,4)+1;
        end
    end
end

[vals,indexes] = sort(hist3d(:,4),'descend');
hist3d = hist3d(indexes,:);
hist3d = hist3d(1:end-1,:);
hist3d(:,1) = hist3d(:,1)-1;
hist3d(:,2) = hist3d(:,2)-1;
hist3d(:,3) = hist3d(:,3)-1;
