Python是一种广泛使用的编程语言,被广泛应用于各种领域中,其中获取主色调也是其中之一。下面我们将介绍如何使用Python获取主色调。
导入所需的库
import numpy as np
import cv2
from sklearn.cluster import KMeans
加载图像
img = cv2.imread(‘test.jpg’)
调整图像大小并转换为一维数组
img = cv2.resize(img, (256, 256))
img_flat = np.reshape(img, (-1, 3))
KMeans聚类取主色调
kmeans = KMeans(n_clusters=3).fit(img_flat)
colors = kmeans.cluster_centers_
将主色调输出
print(‘主要颜色:’)
for color in colors:
print(‘#%02x%02x%02x’ % (int(color[2]), int(color[1]), int(color[0])))
我们使用Python的OpenCV库加载图像,并使用sklearn的KMeans算法进行聚类,以获取图像中的主色调。在这个例子中,我们选取三个主色调。输出结果中,将每个颜色的RGB值转换为十六进制格式,并输出。