OpenCV、NumPy和Matplotlib直方图比较
前言
使用 OpenCV
提供的 cv2.calcHist()
函数可以用来计算直方图。此外,NumPy
和 Matplotlib
同样也为创建直方图提供了类似的函数。出于提高性能目的,我们来比较这些函数,使用 OpenCV
、NumPy
和 Matplotlib
创建直方图,然后测量每个直方图计算的执行时间并将结果绘制在图形中,比较不同库中计算直方图的不同效率。
OpenCV、NumPy和Matplotlib灰度直方图比较
使用 timeit.default_timer
测量执行时间,因为它会自动提供系统平台和 Python
版本上可用的最佳时钟,为了使用 timeit.default_timer
测量执行时间,首先需要将其导入:
from timeit import default_timer as timer 复制代码
可以使用以下方法计算程序的执行时间:
start = timer() # 程序执行 end = timer() execution_time = start - end 复制代码
考虑到 default_timer()
测量值可能会受到同时运行的其他程序的影响。因此,获取准确计时的最佳方法是重复数次并使用最佳时间。当让,我们也可以采用其他方法来测量更加精确的时间,例如多次重复运行取平均值,或者其他更加有效避免异常的方法,在这里为了简单起见,我们重复数次并使用最佳时间。
而为了计算和比较直方图,我们需要使用以下函数:
OpenCV
提供cv2.calcHist()
函数NumPy
提供的np.histogram()
函数Matplotlib
提供的plt.hist()
函数
用于计算上述每个函数的执行时间的代码如下所示。首先,导入所需库:
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) # 计算 cv2.calcHist() 执行时间 start = timer() hist = cv2.calcHist([gray_image], [0], None, [256], [0, 256]) end = timer() # 乘以1000将单位转换为毫秒 exec_time_calc_hist = (end - start) * 1000 # 计算 np.histogram() 执行时间 start = timer() hist_np, bin_np = np.histogram(gray_image.ravel(), 256, [0, 256]) end = timer() exec_time_np_hist = (end - start) * 1000 # 计算 plt.hist() 执行时间 start = timer() # 调用 plt.hist() 计算直方图 (n, bins, patches) = plt.hist(gray_image.ravel(), 256, [0, 256]) end = timer() exec_time_plt_hist = (end - start) * 1000 复制代码
最后,我们绘制灰度图及其直方图:
伪原创工具 SEO网站优化 https://www.237it.com/
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() 复制代码
由上面实例可以看出,cv2.calcHist()
的执行速度比 np.histogram()
和 plt.hist()
都快。因此,出于性能考虑,在计算图像直方图时可以使用 OpenCV
函数。
作者:盼小辉丶
链接:https://juejin.cn/post/7034682215833272334