image histogram in matlab

To plot the histogram of an image in MATLAB, you can use the imhist function. Here's an example code snippet:

main.m
% Read an image
img = imread('your_image.png');

% Convert image to grayscale if necessary
if size(img, 3) == 3
    gray_img = rgb2gray(img);
else
    gray_img = img;
end

% Compute the histogram
counts = imhist(gray_img);

% Plot the histogram
bar(counts);
xlim([0 255]);
title('Grayscale Image Histogram');
xlabel('Gray Level');
ylabel('Pixel Count');
354 chars
20 lines

In this code, we first read an image and convert it to grayscale if necessary. Then we use the imhist function to compute the histogram counts for the grayscale image. Finally, we plot the histogram using the bar function and set the x-axis limits, title, and axis labels using the xlim, title, xlabel, and ylabel functions, respectively.

gistlibby LogSnag