Histograms in Image Processing using MATLAB without built-in Function

NeuralNinja
2 min readMar 4, 2023

--

The distribution of pixel values in an image can be examined using histograms, a common tool in image processing. In this tutorial, we’ll look at how to use MATLAB to make an image’s histogram.

The “imread” function has to be employed to read the image first. Then, we can use the size function to calculate the image’s row and column counts. The number of pixels associated with each pixel value must be counted to construct a histogram.

To do this, we need to create an empty array of 256 items, which corresponds to the possible range of pixel values between 0 and 255. After that, we can traverse through each pixel in the image using a nested for loop. The element of the histogram array corresponding to the current pixel’s value is increased by one in the loop when we extract its pixel value.

Using the bar function in MATLAB, we can draw the histogram after counting the number of pixels associated with each pixel value. The plot’s y-axis displays the number of pixels associated with each pixel value, while the x-axis displays the pixel values, ranging from 0 to 255. A visual representation of the distribution of pixel values in the image is given by the resulting histogram.

The characteristics of an image, such as its brightness, contrast, and color balance, can be examined using histograms. To divide an image into various segments or regions based on their pixel values, they can also be utilized for image segmentation.

The analysis of the distribution of pixel values in an image is done using histograms, which are a crucial tool in image processing. Histogram creation and manipulation tools in MATLAB are robust and may be applied to a variety of image processing tasks.

The following code can be used to calculate histogram of image in MATLAB without using the MATLAB built-in function.

% Read the gray image from the specified directory

original_img=imread(‘’);

% Get the number of rows and columns in the image

[r, c]=size(original_img);

% Create an empty array called histogram_img with 256 elements

% This represents the possible range of pixel values from 0 to 255

histogram_img=zeros(1,256);

% Loop through each pixel in the image

for i=1:r

for j=1:c

% Extract the pixel value of the current pixel

x=original_img(i,j);

% Increment the element of histogram_img that corresponds to the pixel value by one

histogram_img(x+1)=histogram_img(x+1)+1;

end

end

Using the bar function in MATLAB, we can draw the histogram after counting the number of pixels associated with each pixel value. The histogram plotting code is provided below:

% Plot the histogram using the bar function
bar(0:255,histogram_img);
% Add title and axis labels to the plot
title(‘Histogram of Image’);
xlabel(‘Pixel Value’);
ylabel(‘Number of Pixels’);

--

--

No responses yet