OpenCV的calcHist快于numpy 的 histogram 40倍

import cv2  # opencv读取的格式是BGR
import numpy as np
import matplotlib.pyplot as plt  # Matplotlib读取的格式是RGB
import time

def test1():
    img = cv2.imread('cat.jpg', 0)   #0 表示灰度图
    #OpenCV函数比np.histogram()快(大约40X)。所以考虑效率的时候坚持用OpenCV函数。
    time1= time.clock()
    for i in range(100):
        hist = cv2.calcHist([img], [0], None, [256], [0, 256])
    print(" cv2.calcHist= " + str(time.clock()-time1) )

    time2= time.clock()
    for i in range(100):
        hist2, bins2 = np.histogram(img.ravel(), 256, [0,256])
    print(" np.histogram= " + str(time.clock()-time2) )
    print(hist.shape)  #  (256, 1)

    # cv2.calcHist= 0.014924229225604869  sec
    # np.histogram= 0.649571970877664  sec
    #(256, 1)
    #请按任意键继续. .
    #=>  0.649571970877664 / 0.014924229225604869 = 43.52465786060301

if __name__ == "__main__":
    test1()

posted @ 2021-04-02 13:14  boyang987  阅读(102)  评论(0编辑  收藏  举报