Comparing OpenCV, NumPy, and Matplotlib histograms

We have already seen that OpenCV provides the cv2.calcHist() function to calculate histograms. Additionally, NumPy and Matplotlib offer similar functions for the creation of histograms. In the comparing_opencv_numpy_mpl_hist.py script, we are comparing these functions for performance purposes. In this sense, we are going to see how to create histograms with OpenCV, NumPy, and Matplotlib, and then measure the execution time for each one and plot the results in a figure. 

With the purpose of measuring the execution time, we are using timeit.default_timer because it provides the best clock available on your platform and version of Python automatically. In this way, we import it at the beginning of the script:

from timeit import default_timer as timer

The way we use the timer is summarized here:

start = timer()
# ...
end = timer()
execution_time = start - end
It should be taken into account that default_timer() measurements can be affected by other programs running on the same machine at the same time. Therefore, the best approach to performing accurate timing is to repeat it several times and take the best time.

In order to calculate the histograms, we are going to use the following functions:

Hence, the code for calculating the execution for each of the aforementioned functions is provided as follows:

start = timer()
# Calculate the histogram calling cv2.calcHist()
hist = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
end = timer()
exec_time_calc_hist = (end - start) * 1000

start = timer()
# Calculate the histogram calling np.histogram():
hist_np, bins_np = np.histogram(gray_image.ravel(), 256, [0, 256])
end = timer()
exec_time_np_hist = (end - start) * 1000

start = timer()
# Calculate the histogram calling plt.hist():
(n, bins, patches) = plt.hist(gray_image.ravel(), 256, [0, 256])
end = timer()
exec_time_plt_hist = (end - start) * 1000

We multiply the value to get milliseconds (rather than seconds). The output for the comparing_opencv_numpy_mpl_hist.py script can be seen in the following screenshot:

As can be seen, cv2.calcHist() is faster than both np.histogram() and plt.hist(). Therefore, for performance purposes, you can use the OpenCV function.