Calculation of the histogram
An image histogram is a graphical representation of the pixel intensity distribution in an image. It shows how many pixels of an image have a certain intensity value (color or brightness).
Why calculate the histogram?
The histogram allows you to analyze the illumination, adjust the contrast, brightness of the image, highlight objects, balance colors and improve the quality of visualization.
The histogram allows you to estimate how bright or dark the image is.:
If the pixels are "crowded" on the left (low intensity), the image is too dark.
If the pixels are "crowded" to the right (high intensity), the image is overexposed.
We connect the necessary packages for working with images
import Pkg
Pkg.add("Images")
Pkg.add("StatsBase")
Pkg.add("Plots")
using Images, StatsBase, Plots
Uploading an image
path_to_img_1 = "$(@__DIR__)/Cozy_Autumn_Beverage_Moment.jpeg";
Image_1 = load(path_to_img_1)
Data processing
channelview converts an image into an array where each color channel (red, green, and blue) becomes a separate layer.
rgb_planes = channelview(Image_1);
Next, we break down the color channels into separate variables
blue_channel = rgb_planes[3, :, :]
green_channel = rgb_planes[2, :, :]
red_channel = rgb_planes[1, :, :];
Visualize a separate channel
red_image = colorview(RGB, red_channel, zeros(size(red_channel)), zeros(size(red_channel)))
Calculation of histograms
red_channel
In the cell above, we see an array of intensity values of the red channel of the image for each pixel.
First, we break down the intensity into ranges. For example, for normalized data
[0, 1], which are represented
here, 256 equal intervals can be used. Then we calculate how many pixels fall into each range.
Set the number of cells to 256
histSize = 256;
Set the range of values (from 0 to 1)
hist_range = 0:1/(histSize-1):1;
Let's start calculating the histograms. StatsBase.Histogram allows you to calculate histograms
b_hist = fit(Histogram, blue_channel[:], hist_range)
r_hist = fit(Histogram, red_channel[:], hist_range)
g_hist = fit(Histogram, green_channel[:], hist_range);
Visualization
We visualize the calculated histograms for a visual assessment of the intensity distribution.
plot(r_hist.edges[1][1:end-1], r_hist.weights, color=:red, label="Red Channel")
plot!(b_hist.edges[1][1:end-1], b_hist.weights, color=:blue, label="blue Channel")
plot!(g_hist.edges[1][1:end-1], g_hist.weights, color=:green, label="green Channel")
As you can see from the graph above, most of the pixels in terms of intensity are located on the left side of the graph, which indicates that the image is darkened.
Conclusion
In this example, histograms of pixel intensities were calculated to estimate the brightness of the image.

