Most dominant color in RGB image - OpenCV / NumPy / Python

后端 未结 3 1384
广开言路
广开言路 2020-12-14 04:05

I have a python image processing function, that uses tries to get the dominant color of an image. I make use of a function I found here https://github.com/tarikd/python-kmea

3条回答
  •  抹茶落季
    2020-12-14 04:40

    The equivalent code for cv2.calcHist() is to replace:

    (hist, _) = np.histogram(clt.labels_, bins=num_labels)  
    

    with

    dmin, dmax, _, _ = cv2.minMaxLoc(clt.labels_)
    
    if np.issubdtype(data.dtype, 'float'): dmax += np.finfo(data.dtype).eps
    else: dmax += 1
    
    hist = cv2.calcHist([clt.labels_], [0], None, [num_labels], [dmin, dmax]).flatten()
    

    Note that cv2.calcHist only accepts uint8 and float32 as element type.

    Update

    It seems like opencv's and numpy's binning differs from each other as the histograms differ if the number of bins doesn't map the value range:

    import numpy as np
    from matplotlib import pyplot as plt
    import cv2
    
    #data = np.random.normal(128, 1, (100, 100)).astype('float32')
    data = np.random.randint(0, 256, (100, 100), 'uint8')
    BINS = 20
    
    np_hist, _ = np.histogram(data, bins=BINS)
    
    dmin, dmax, _, _ = cv2.minMaxLoc(data)
    if np.issubdtype(data.dtype, 'float'): dmax += np.finfo(data.dtype).eps
    else: dmax += 1
    
    cv_hist = cv2.calcHist([data], [0], None, [BINS], [dmin, dmax]).flatten()
    
    plt.plot(np_hist, '-', label='numpy')
    plt.plot(cv_hist, '-', label='opencv')
    plt.gcf().set_size_inches(15, 7)
    plt.legend()
    plt.show()
    

提交回复
热议问题