我有一个 python 图像处理函数,它试图获取图像的主色。我使用了在这里找到的函数 https://github.com/tarikd/python-kmeans-dominant-colors/blob/master/utils.py
它有效,但不幸的是我不太明白它的作用,我了解到 np.histogram
相当慢,我应该使用 cv2.calcHist
因为它比这个快 40 倍: https:/ /docs.opencv.org/trunk/d1/db7/tutorial_py_histogram_begins.html
我想了解我必须如何更新代码才能使用 cv2.calcHist
或更好,我必须输入哪些值。
我的功能
def centroid_histogram(clt):
# grab the number of different clusters and create a histogram
# based on the number of pixels assigned to each cluster
num_labels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=num_labels)
# normalize the histogram, such that it sums to one
hist = hist.astype("float")
hist /= hist.sum()
# return the histogram
return hist
pprint
的 clt
是这个,不确定这是否有帮助
KMeans(algorithm='auto', copy_x=True, init='k-means++', max_iter=300,
n_clusters=1, n_init=10, n_jobs=1, precompute_distances='auto',
random_state=None, tol=0.0001, verbose=0)
我的代码可以在这里找到: https ://github.com/primus852/python-movie-barcode
我是一个非常初学者,所以非常感谢任何帮助。
按要求:
样本图像
最主要的颜色:
rgb(22,28,37)
直方图的计算时间:
0.021515369415283203s
原文由 PrimuS 发布,翻译遵循 CC BY-SA 4.0 许可协议
可以建议使用
np.unique
和np.bincount
获得最主要颜色的两种方法。此外,在链接页面中,它讨论了bincount
作为更快的替代方案,因此这可能是可行的方法。方法#1
方法#2
验证和计时
1000 x 1000
密集范围内的彩色图像[0,9)
以获得可重现的结果 -进一步提振
利用
multi-core
和numexpr
大数据模块 进一步提升 -时间 -