MATLAB: Plotting RGB histograms of images WITHOUT using the built-in function”imhist()”

matlab functionrgb histogramsurgent

Hi all,
Basically, I am required to create my own function that functions the same way as the built-in function "imhist" and find and display the RGB histogram channels of an image as well as a histogram that displays the frequency count for all channels – red, green and blue channels – ALL IN ONE FIGURE.
This is my codes in the file where I call out the function
grayImage = imread('image1.jpg');
[counts, grayLevels] = im_histogram(grayImage)
figure(); imshow([counts, grayLevels]);
And this is what I have for my function file codes so far…
function [counts, grayLevels] = im_histogram(grayImage)
[rows, columns, numberOfColorChannels] = size(grayImage);
counts = zeros(1, 256);
for col = 1 : columns
for row = 1 : rows
% Get the gray level.
grayLevel = grayImage(row, col);
% Add 1 because graylevel zero goes into index 1 and so on.
counts(grayLevel+ 1) = counts(grayLevel+1) + 1;
end
end
%Split into RGB Channels
Red = image(:,:,1);
Green = image(:,:,2);
Blue = image(:,:,3);
% Plot the histogram.
grayLevels = 0 : 255;
bar(grayLevels, counts, 'BarWidth', 1, 'FaceColor', 'red');
bar(grayLevels, counts, 'BarWidth', 1, 'FaceColor', 'green');
bar(grayLevels, counts, 'BarWidth', 1, 'FaceColor', 'blue');
xlabel('Gray Level', 'FontSize', 20);
ylabel('Pixel Count', 'FontSize', 20);
title('Histogram', 'FontSize', 20);
grid on;
end
However, in the function file, when I write the codes,
bar(grayLevels, counts, 'BarWidth', 1, 'FaceColor', 'green');
bar(grayLevels, counts, 'BarWidth', 1, 'FaceColor', 'blue');
an error pops out.
I am unsure how to display the all RGB histograms in one figure in the the function file. PLEASE HELP!!!

Best Answer

See my attached demo.