MATLAB: How to plot the frequencies of colors present in an image

histogramMATLAB

Given an RGB image I want to keep a count of each unique color index to make a frequency vs color index plot of the image.

Best Answer

Trying to plot a histogram of color indices of a large image will quickly deplete memory due to the large number of bins that will be empty. Since there is no interest in the empty bins only the colors that actually occur in the image should be counted.
The code below reads in an RGB image, converts the RGB matrices to a single index matrix, finds and counts the unique entries, and plots the resulting counts vs. the indices.
%Read in RGB image file.
I = imread('onion.png');
% %Change RGB matrices to a single matrix of color indices.
Color_ind=double(I(:,:,1)).*256^2+double(I(:,:,2).*256)+double(I(:,:,3));
%Find the unique elements in the color index matrix and find the length
%of the resultant vector.
unique_ind=unique(Color_ind);
unique_indLen=length(unique_ind);
%Pre-allocate space for the vector that will hold the number of entries
%for each unique color
color_count=zeros(unique_indLen,1);
%Count the number of each occurrence of each unique color index in the
%original matrix.
for i = 1:unique_indLen
color_count(i)=length(find(unique_ind(i)==Color_ind));
end
%Plot the results.
bar(unique_ind,color_count)