# 14-python opencv 获取程序执行时间

• 获取系统时钟数
• 获取系统时钟频率

## 实现过程

### 初始时间

# time start
t1 = cv2.getTickCount()

### 结束时间

# time end
t2 = cv2.getTickCount()

### 计算执行秒数

t = (t2-t1)/cv2.getTickFrequency()
print t

## 源代码

# created by Huang Lu
# 2016/8/26 17:35
# Department of EE, Tsinghua Univ.

import cv2
import numpy as np

# get the hist graph of a gray image
def HistGraphGray(image, color):
hist= cv2.calcHist([image], [0], None, [256], [0.0,255.0])
histGraph = np.zeros([256,256,3], np.uint8)
m = max(hist)
hist = hist * 220 / m
for h in range(256):
n = int(hist[h])
cv2.line(histGraph,(h,255), (h,255-n), color)
return histGraph;

# get the hist graph of a color image
def HistGraphColor(image):
histGraph = np.zeros([256,256,3], np.uint8)
colorBlue = [255, 0, 0]
colorGreen = [0, 255, 0]
colorRed = [0, 0, 255]
b, g, r = cv2.split(image)
bhist = cv2.calcHist([b], [0], None, [256], [0.0,255.0])
ghist = cv2.calcHist([g], [0], None, [256], [0.0,255.0])
rhist = cv2.calcHist([r], [0], None, [256], [0.0,255.0])
bm = max(bhist)
gm = max(ghist)
rm = max(rhist)
bhist = bhist * 220 / bm
rhist = rhist * 220 / rm
ghist = ghist * 220 / gm
for h in range(256):
bn = int(bhist[h])
gn = int(ghist[h])
rn = int(rhist[h])
if h != 0:
cv2.line(histGraph,(h-1,255-bStart), (h,255-bn), colorBlue)
cv2.line(histGraph,(h-1,255-gStart), (h,255-gn), colorGreen)
cv2.line(histGraph,(h-1,255-rStart), (h,255-rn), colorRed)
bStart = bn
gStart = gn
rStart = rn
return histGraph

# main fuction
if __name__ == '__main__':
# time start
t1 = cv2.getTickCount()

# test for a gray image
color = [255, 255, 255]
histGraph1 = HistGraphGray(img1, color)
cv2.imshow("Hist Gray", histGraph1)

# test for a color image
# first tset for three channels
colorRed = [0, 0, 255]
colorGreen = [0, 255, 0]
colorBlue = [255, 0, 0]
b, g, r = cv2.split(img2)
# blue channel
bhistGraph = HistGraphGray(b, colorBlue)
cv2.imshow("Hist Blue", bhistGraph)
# green channel
ghistGraph = HistGraphGray(g, colorGreen)
cv2.imshow("Hist Green", ghistGraph)
# red channel
rhistGraph = HistGraphGray(r, colorRed)
cv2.imshow("Hist Red", rhistGraph)
# get three channels together
histGraph2 = HistGraphColor(img2)
cv2.imshow("Hist Color", histGraph2)

# time end
t2 = cv2.getTickCount()
t = (t2-t1)/cv2.getTickFrequency()
print t

cv2.waitKey(0)
cv2.destroyAllWindows()

## 参考

#### OpenCV统计时间

2016-04-11 23:08:36

#### 【opencv】获取程序运行时间

2016-01-26 12:01:17

#### python获取代码运行时间

2017-05-26 11:47:53

#### opencv 提取视频信息（提取每帧 VS 按照时间提取）

2017-08-27 21:23:45

#### Python获取代码运行时间的几种方法

2018-03-23 23:23:25

#### 几种Python执行时间的计算方法

2018-06-04 11:06:18

#### pythonOpenCV之安装和第一个程序

2017-10-28 11:34:22

#### Python中使用OpenCV最基本的程序

2017-01-04 15:19:15

#### OpenCV实践之路——画出时钟并动态同步系统时间

2016-02-28 23:25:41

#### <C++>获取并显示当前时间

2015-04-01 11:07:29