Image histograms in OpenCV (python)

Zahid Parvez
3 min readJan 16, 2023

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…

--

--

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.