“This is the 26th day of my participation in the Gwen Challenge in November. Check out the details: The Last Gwen Challenge in 2021.”

preface

The cv2.calchist () function provided by OpenCV can be used to calculate the histogram. In addition, NumPy and Matplotlib also provide similar functions for creating histograms. To improve performance, we compared these functions, created histograms using OpenCV, NumPy, and Matplotlib, and then measured the execution time of each histogram calculation and plotted the results on a graph, comparing the different efficiency of histogram calculation in different libraries.

OpenCV, NumPy and Matplotlib gray histogram comparison

Default_timer measures execution time with timeit.default_timer, as it automatically provides the best clock available on the system platform and Python version. To measure execution time with timeit.default_timer, first import it:

from timeit import default_timer as timer
Copy the code

The execution time of the program can be calculated using the following methods:

start = timer()
# program execution
end = timer()
execution_time = start - end
Copy the code

Consider that the default_timer() measurements may be affected by other programs running at the same time. Therefore, the best way to get accurate timing is to repeat several times and use the best time. When possible, we can also use other methods to measure more precise times, such as repeating multiple times to take an average, or other methods that are more effective in avoiding exceptions. Here, for simplicity, we repeat several times and use the best time.

To calculate and compare histograms, we need to use the following functions:

  1. OpenCVprovidecv2.calcHist()function
  2. NumPyTo provide thenp.histogram()function
  3. MatplotlibTo provide theplt.hist()function

The code used to calculate the execution time of each of the above functions is shown below. First, import the required libraries:

import numpy as np
import cv2
from matplotlib import pyplot as plt
from timeit import default_timer as timer
Copy the code

Then write a visual function that displays the results in the same graph for better comparison:

def show_img_with_matplotlib(color_img, title, pos) :
    img_RGB = color_img[:, :, ::-1]

    ax = plt.subplot(1.4, pos)
    plt.imshow(img_RGB)
    plt.title(title)
    plt.axis('off')

def show_hist_with_matplotlib_gray(hist, title, pos, color) :
    ax = plt.subplot(1.4, pos)
    plt.title(title)
    plt.xlabel("bins")
    plt.ylabel("number of pixels")
    plt.xlim([0.256])
    plt.plot(hist, color=color)

plt.figure(figsize=(18.6))
plt.suptitle("Comparing histogram (OpenCV, numpy, matplotlib)", fontsize=14, fontweight='bold')
Copy the code

Next, the most critical part of the program, using the method of calculating the histogram in different libraries, and obtain the program runtime:

image = cv2.imread('example.png') gray_image = cv2.cvtColor(image, Start = timer() hist = cv2.calcHist([gray_image], [0], None, [256], [0, Exec_time_calc_hist = (end-start) * 1000 # exec_time_calc_hist = (end-start) * 1000 #  hist_np, bin_np = np.histogram(gray_image.ravel(), 256, [0, = 256]) end the timer () exec_time_np_hist = (end - start) * 1000 # calculation PLT in hist () execution time start = the timer () # call PLT. Hist () histogram computation (n, bins, patches) = plt.hist(gray_image.ravel(), 256, [0, 256]) end = timer() exec_time_plt_hist = (end - start) * 1000Copy the code

Finally, we draw the grayscale map and its histogram:

how_img_with_matplotlib(cv2.cvtColor(gray_image, cv2.COLOR_GRAY2BGR), "gray".1)
show_hist_with_matplotlib_gray(hist, "grayscale histogram (OpenCV)-" + str('% 6.2 f ms' % exec_time_calc_hist), 2.'m')
show_hist_with_matplotlib_gray(hist_np, "grayscale histogram (Numpy)-" + str('% 6.2 f ms' % exec_time_np_hist), 3.'m')
show_hist_with_matplotlib_gray(n, "grayscale histogram (Matplotlib)-" + str('% 6.2 f ms' % exec_time_plt_hist), 4.'m')

plt.show()
Copy the code

As can be seen from the above examples, cv2.calchist () is faster than BOTH NP.histogram () and plt.hist(). Therefore, for performance reasons, OpenCV functions can be used when calculating image histograms.