OpenCV-Python實戰(番外篇)——OpenCV、NumPy和Matplotlib直方圖比較
- 前言
- OpenCV、NumPy和Matplotlib灰度直方圖比較
- OpenCV、NumPy和Matplotlib顏色直方圖比較
- 相關鏈接
前言
在《OpenCV-Python實戰(7)——直方圖詳解(??萬字長文,含大量示例??)》中,我們學習了使用 OpenCV 提供的 cv2.calcHist() 函式來計算直方圖,此外,NumPy 和 Matplotlib 同樣也為創建直方圖提供了類似的函式,出于提高性能目的,我們來比較這些函式,使用 OpenCV、NumPy 和 Matplotlib 創建直方圖,然后測量每個直方圖計算的執行時間并將結果繪制在圖形中,
OpenCV、NumPy和Matplotlib灰度直方圖比較
使用 timeit.default_timer 測量執行時間,因為它會自動提供系統平臺和 Python 版本上可用的最佳時鐘,首先將其匯入:
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
# 繪制灰度圖及其直方圖
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和Matplotlib顏色直方圖比較
對比顏色直方圖的方法與灰度直方圖類似:
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')
# 計算 cv2.calcHist() 執行時間
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
# 計算 np.histogram() 執行時間
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
# 計算 plt.hist 執行時間
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
# 繪制影像及其顏色直方圖
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()

由上面兩個實體可以看出,cv2.calcHist() 的執行速度比 np.histogram() 和 plt.hist() 都快,因此,出于性能考慮,在計算影像直方圖時可以使用 OpenCV 函式,
相關鏈接
《OpenCV-Python實戰(7)——直方圖詳解(??萬字長文,含大量示例??)》
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/304587.html
標籤:其他
上一篇:搞懂快速排序,包會!!!
下一篇:Python中的流程控制陳述句
