Histogram calculation
An image histogram is a graphical representation of the distribution of pixel intensities in an image. It shows how many pixels in the image have a certain intensity (colour or brightness) value.
Why calculate a histogram?
A histogram allows you to analyse illumination, adjust contrast, brightness of the image, highlight objects, balance colours and improve visual quality.
The histogram allows you to evaluate how bright or dark an image is:
If the pixels are "crowded together" on the left (low intensities), the image is too dark.
If pixels are crowded together on the right (high intensities), the image is over-lit.
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 the image into an array where each colour channel (red, green, blue) becomes a separate layer.
rgb_planes = channelview(Image_1);
Next, split the colour channels into separate variables
blue_channel = rgb_planes[3, :, :]
green_channel = rgb_planes[2, :, :]
red_channel = rgb_planes[1, :, :];
Visualise the individual channel
red_image = colorview(RGB, red_channel, zeros(size(red_channel)), zeros(size(red_channel)))
Calculating histograms
red_channel
In the cell above, we see an array of red channel intensities for each pixel in the image
First, we break the intensities into ranges. For example, for normalised data
[0, 1], which is what we have here.
we can use 256 equal intervals. Then we calculate how many pixels fall into each range.
Set the number of cells to 256
histSize = 256;
Set the range of values (0 to 1)
hist_range = 0:1/(histSize-1):1;
Let's start calculating histograms. StatsBase.Histogram
allows 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);
Visualisation
We visualise the calculated histograms to clearly assess the distribution of intensities
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 can be seen from the graph above, most of the pixels by intensity level are in the left part of the graph, which indicates that the image is darkened
Conclusion
In this example, pixel intensity histograms were calculated to estimate the brightness of the image