Matplotlib Histogram

Matplotlib can be used to create histograms. A histogram shows the frequency on the vertical axis and the horizontal axis is another dimension. Usually it has bins, where every bin has a minimum and maximum value. Each bin also has a frequency between x and infinite.

Related course
Data Visualization with Python and Matplotlib

Matplotlib histogram example
Below we show the most minimal Matplotlib histogram:

import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
 
x = [21,22,23,4,5,6,77,8,9,10,31,32,33,34,35,36,37,18,49,50,100]
num_bins = 5
n, bins, patches = plt.hist(x, num_bins, facecolor='blue', alpha=0.5)
plt.show()

Output:

minimal_hist
Python histogram

A complete matplotlib python histogram
Many things can be added to a histogram such as a fit line, labels and so on. The code below creates a more advanced histogram.

#!/usr/bin/env python
 
import numpy as np
import matplotlib.mlab as mlab
import matplotlib.pyplot as plt
 
 
# example data
mu = 100 # mean of distribution
sigma = 15 # standard deviation of distribution
x = mu + sigma * np.random.randn(10000)
 
num_bins = 20
# the histogram of the data
n, bins, patches = plt.hist(x, num_bins, normed=1, facecolor='blue', alpha=0.5)
 
# add a 'best fit' line
y = mlab.normpdf(bins, mu, sigma)
plt.plot(bins, y, 'r--')
plt.xlabel('Smarts')
plt.ylabel('Probability')
plt.title(r'Histogram of IQ: $\mu=100$, $\sigma=15$')
 
# Tweak spacing to prevent clipping of ylabel
plt.subplots_adjust(left=0.15)
plt.show()

Output:

python_histogram
python_histogram

Image histogram

A histogram is collected counts of data organized into a set of bins. Every bin shows the frequency. OpenCV can generate histograms for both color and gray scale images. You may want to use histograms for computer vision tasks.

Related course
Computer vision with Python
Introduction to Computer Vision Master OpenCV in Python

Histogram example
Given an image we can generate a histogram for the blue, green and red values.

Histogram_Calculation
Histogram Calculation

We use the function cv.CalcHist(image, channel, mask, histSize, range)

Parameters:

  • image:  should be in brackets,  the source image of type uint8 or float32
  • channel:  the color channel to select. for grayscale use [0]. color image has blue, green and red channels
  • mask:  None if you want a histogram of the full image, otherwise a region.
  • histSize:  the number of bins
  • range:  color range:

Histogram for a color image:

# draw histogram in python. 
import cv2
import numpy as np
 
img = cv2.imread('image.jpg')
h = np.zeros((300,256,3))
 
bins = np.arange(256).reshape(256,1)
color = [ (255,0,0),(0,255,0),(0,0,255) ]
 
for ch, col in enumerate(color):
    hist_item = cv2.calcHist([img],[ch],None,[256],[0,255])
    cv2.normalize(hist_item,hist_item,0,255,cv2.NORM_MINMAX)
    hist=np.int32(np.around(hist_item))
    pts = np.column_stack((bins,hist))
    cv2.polylines(h,[pts],False,col)
 
h=np.flipud(h)
 
cv2.imshow('colorhist',h)
cv2.waitKey(0)