How to plot color channels Histogram of an Image in Python using OpenCV
In this very short blog, we will see how we can plot all 3 color channels histogram (red, green, blue) of an Image in Python using OpenCV.
Read the full article with source code here — https://machinelearningprojects.net/plot-color-channels-histogram/
Let’s do it…
Step 1 — Importing required packages for plotting Color Channels Histogram.
import matplotlib.pyplot as plt
Step 2 — Let’s read and visualize the image.
imgpath = "test.tiff"
img = cv2.imread(imgpath)
Step 3 — Convert the channels from BGR to RGB.
img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)
Step 4 — Finally let’s get the Color Channels Histograms…
Syntax: cv2.calcHist(images, channels, mask, histSize, ranges[, hist[, accumulate]])
red_hist = cv2.calcHist([img], , None, , [0, 255])
green_hist = cv2.calcHist([img], , None, , [0, 255])
blue_hist = cv2.calcHist([img], , None, , [0, 255])
You can read more about Histogram Calculation here.
Step 5 — Let's plot these color channels histograms.
plt.subplot(4, 1, 1)
plt.subplot(4, 1, 2)
plt.subplot(4, 1, 3)
plt.subplot(4, 1, 4)
- We have created a canvas with 4 rows and 1 column.
- In the first row, we have plotted the image with x and y bars removed using xticks() and yticks().
- In the second row, we have plotted the histogram for the red channel. We have set the limit of the histogram from 0–255 (which is the actual range of the red channel values that every pixel can take).
- We have done a similar thing for green and blue channels also.
- In the second last line, we have used plt.tight_layout() just to provide some spacings between the plots.
NOTE: From this, we can infer that the major portion of the image is RED.
Do let me know if there’s any query regarding Color Channels Histogram by contacting me on email or LinkedIn.
For further code explanation and source code visit here — https://machinelearningprojects.net/plot-color-channels-histogram/
So this is all for this blog folks, thanks for reading it and I hope you are taking something with you after reading this and till the next time 👋…
Read my previous post: HOW TO PERFORM BLURRINGS LIKE SIMPLE BLUR, BOX BLUR, GAUSSIAN BLUR, AND MEDIAN BLUR