Opencv Python actual combat (external part) -- comparison of OpenCV, numpy and Matplotlib histograms

Hope Xiaohui 2021-10-14 05:02:27

OpenCV-Python actual combat ( Set pieces )——OpenCV、NumPy and Matplotlib Histogram comparison

Preface

stay 《OpenCV-Python actual combat (7)—— Histogram detail (️ Ten thousand words long text , Contains a large number of examples ️)》 in , We learned to use OpenCV Provided cv2.calcHist() Function to calculate the histogram . Besides ,NumPy and Matplotlib A similar function is also provided for creating histograms . For performance purposes , Let's compare these functions , Use OpenCVNumPy and Matplotlib Create histograms , Then, the execution time of each histogram calculation is measured and the results are drawn in the graph .

OpenCV、NumPy and Matplotlib Gray histogram comparison

Use timeit.default_timer Measure execution time , Because it will automatically provide the system platform and Python The best clock available on version , Import it first :

from timeit import default_timer as timer

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

start = timer()
# Program execution 
end = timer()
execution_time = start - end

in consideration of default_timer() The measured values 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 .
In order to calculate and compare histograms , We need to use the following function :

  1. OpenCV Provide cv2.calcHist() function
  2. NumPy Provided np.histogram() function
  3. Matplotlib Provided plt.hist() function

The code used to calculate the execution time of each of the above functions is as follows :

import numpy as np
import cv2
from matplotlib import pyplot as plt
from timeit import default_timer as timer
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')
image = cv2.imread('example.png')
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
# Calculation cv2.calcHist() execution time 
start = timer()
hist = cv2.calcHist([gray_image], [0], None, [256], [0, 256])
end = timer()
# multiply 1000 Convert units to milliseconds 
exec_time_calc_hist = (end - start) * 1000
# Calculation np.histogram() execution time 
start = timer()
hist_np, bin_np = np.histogram(gray_image.ravel(), 256, [0, 256])
end = timer()
exec_time_np_hist = (end - start) * 1000
# Calculation plt.hist() execution time 
start = timer()
# call plt.hist() Calculate the histogram 
(n, bins, patches) = plt.hist(gray_image.ravel(), 256, [0, 256])
end = timer()
exec_time_plt_hist = (end - start) * 1000
# Draw gray image 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.2f ms' % exec_time_calc_hist), 2, 'm')
show_hist_with_matplotlib_gray(hist_np, "grayscale histogram (Numpy)-" + str('% 6.2f ms' % exec_time_np_hist), 3, 'm')
show_hist_with_matplotlib_gray(n, "grayscale histogram (Matplotlib)-" + str('% 6.2f ms' % exec_time_plt_hist), 4, 'm')
plt.show()

OpenCV、NumPy and Matplotlib Gray histogram comparison

OpenCV、NumPy and Matplotlib Color histogram comparison

The method of comparing color histogram is similar to gray histogram :

import numpy as np
import cv2
from matplotlib import pyplot as plt
from timeit import default_timer as timer
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_rgb(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])
for (h, c) in zip(hist, color):
plt.plot(h, color=c)
plt.figure(figsize=(18, 6))
plt.suptitle("Comparing histogram (OpenCV, numpy, matplotlib)", fontsize=14, fontweight='bold')
image = cv2.imread('example.png')
# Calculation cv2.calcHist() execution time 
start = timer()
def hist_color_img(img):
histr = []
histr.append(cv2.calcHist([img], [0], None, [256], [0, 256]))
histr.append(cv2.calcHist([img], [1], None, [256], [0, 256]))
histr.append(cv2.calcHist([img], [2], None, [256], [0, 256]))
return histr
hist= hist_color_img(image)
end = timer()
exec_time_calc_hist = (end - start) * 1000
# Calculation np.histogram() execution time 
start = timer()
def hist_color_img_np(img):
histr = []
hist_np, bin_np = np.histogram(img[:,:,0].ravel(), 256, [0, 256])
histr.append(hist_np)
hist_np, bin_np = np.histogram(img[:,:,1].ravel(), 256, [0, 256])
histr.append(hist_np)
hist_np, bin_np = np.histogram(img[:,:,2].ravel(), 256, [0, 256])
histr.append(hist_np)
return histr
hist_np = hist_color_img_np(image)
end = timer()
exec_time_np_hist = (end - start) * 1000
# Calculation plt.hist execution time 
start = timer()
def hist_color_img_plt(img):
histr = []
(n, bins, patches) = plt.hist(image[:,:,0].ravel(), 256, [0, 256])
histr.append(n)
(n, bins, patches) = plt.hist(image[:,:,1].ravel(), 256, [0, 256])
histr.append(n)
(n, bins, patches) = plt.hist(image[:,:,2].ravel(), 256, [0, 256])
histr.append(n)
return histr
n = hist_color_img_plt(image)
end = timer()
exec_time_plt_hist = (end - start) * 1000
# Draw the image and its color histogram 
show_img_with_matplotlib(image, "color", 1)
show_hist_with_matplotlib_rgb(hist, "color histogram (OpenCV)-" + str('% 6.2f ms' % exec_time_calc_hist), 2, ['b', 'g', 'r'])
show_hist_with_matplotlib_rgb(hist_np, "color histogram (Numpy)-" + str('% 6.2f ms' % exec_time_np_hist), 3, ['b', 'g', 'r'])
show_hist_with_matplotlib_rgb(n, "color histogram (Matplotlib)-" + str('% 6.2f ms' % exec_time_plt_hist), 4, ['b', 'g', 'r'])
plt.show()

OpenCV、NumPy and Matplotlib Color histogram comparison
As can be seen from the above two examples ,cv2.calcHist() The execution speed ratio of np.histogram() and plt.hist() All quick . therefore , For performance reasons , When calculating the image histogram, you can use OpenCV function .

Related links

《OpenCV-Python actual combat (7)—— Histogram detail (️ Ten thousand words long text , Contains a large number of examples ️)》

Please bring the original link to reprint ,thank
Similar articles

2021-10-14