Image histograms in OpenCV (python)

Zahid Parvez
3 min readJan 16

Image histograms are an extremely powerful tool, at a glance they can convey the contrast, brightness, light distribution, and color distribution in an image. They are useful or tasks such as image enhancement, thresholding, and color balance.

Example of a plotted histogram, plotted using https://www.sisik.eu/histo

To get the histogram using OpenCV, the calcHist() function can be used. The function takes the following arguments:

  • images: A list of images, all of which must have the same data type and dimensions. To calculate the histogram of a single image, wrap it in a list (i.e. “[image ariableName]”)
  • channels: A list of channels used to calculate the histograms. Use [0] for greyscale images or the first channel (in BGR — 0:Blue, 1:Green, 2:Red; in RGB — 0:Red, 1:Green, 2:Blue)
  • mask: An optional 8-bit array mask of the same size as the input image. This is used when generating the histogram for only a specific part of the image.
  • histSize: list of the number of bins for the histogram, typically 256 for images.
  • ranges: The minimum and maximum ranges for the histogram, typically set to [0, 256] for images.

The output of this function will be a n-dimensional array (n being the number of channels being calculated). This array can be plotted using matplotlib.

Show histogram for grayscale/single channel

The function below will take an image and channel (default = 0) and display the histogram for the input channel. If you want to make it display the histogram of the image as greyscale, you can use the cv2.cvtColor function to do so. Check the link to the Jupyter notebook at the bottom for an example.

def show1dHist(image,channel=0):
hist = cv2.calcHist([image],[channel],None,[256],[0,256])
plt.plot(hist)
plt.show()
Histogram a greyscale image

Show RGB histogram for an image

The function below will take an RGB image and display a histogram of the 3 different color channels. You can tweak this code to make the plot as you like:

def show3dHist(imageRGB):
channels = [0,1,2]
colors = ['r','g','b']

for c in channels:
hist = cv2.calcHist([imageRGB],[c],None,[256],[0,256])
plt.plot(hist,color = colors[c])

plt.show()

As you can see this histogram is essentially the same as the one plotted using a 3rd party tool, this validates that our code to show a color histogram is working.

If you would like to get a copy of the code used in this article, it can be found here on Github.

Zahid Parvez

I am an analyst with a passion for data, software, and integration. In my free time, I also like to dabble in design, photography, and philosophy.