python - 多幅图像中的主色
问题描述
我正在尝试找到一种算法来使用 python 找到多个图像的平均主色。我发现了一种算法,可以使用 KMeans 聚类提取单个图像的主色。然后将集群输入直方图函数,最后用 matplot 库绘制。
我对 python 和一般编码相当陌生,我找不到将多个集群数据合并为一个或合并多个直方图的方法 最聪明的解决方案是什么?
我试图在一个例子中找到什么。假设您有两张图像,第一张是 50% 青色和 50% 黄色,第二张是 50% 青色和 50% 红色 – 我想要一个组合和加权输出,例如:50% 青色、25% 红色和 25 % 黄色。
到目前为止,这是我的代码
import cv2
import glob
import numpy as np
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
def find_histogram(clt):
"""
create a histogram with k clusters
:param: clt
:return:hist
"""
numLabels = np.arange(0, len(np.unique(clt.labels_)) + 1)
(hist, _) = np.histogram(clt.labels_, bins=numLabels)
hist = hist.astype("float")
hist /= hist.sum()
return hist
def plot_colors2(hist, centroids):
bar = np.zeros((50, 300, 3), dtype="uint8")
startX = 0
for (percent, color) in zip(hist, centroids):
# plot the relative percentage of each cluster
endX = startX + (percent * 300)
cv2.rectangle(bar, (int(startX), 0), (int(endX), 180), color.astype("uint8").tolist(), -1)
startX = endX
return bar
images = [cv2.imread(file) for file in glob.glob("pics/*.jpg")]
for image in images:
imageRGB = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)
imageReshape = imageRGB.reshape((imageRGB.shape[0] *
imageRGB.shape[1],3)) #represent as row*column,channel number
cluster = KMeans(n_clusters=3) #cluster number
cluster.fit(imageReshape)
print(cluster)
histogram = find_histogram(cluster)
#print("histogram", histogram)
bar = plot_colors2(histogram, cluster.cluster_centers_)
plt.axis("off")
plt.imshow(bar)
plt.show()
解决方案
推荐阅读
- sockets - 自 Vista 发布以来,Microsoft 是否修复了 WSAPOLL?
- c# - 如何在 c# 中通过 LDAP SSL 从 Active Directory 的林中获取域
- r - 向量化滞后操作
- javascript - Passport JS localstrategy 允许使用电子邮件和用户名登录
- python - 如何在 Windows 上使用带有 mysql xampp 的“export-laravel-5-migrations _grt”插件
- javascript - Photoshop js脚本裁剪到选择,复制图层名称,并将图层名称粘贴到导出对话框中
- flutter - Flutter 升级 in_app_purchase 插件问题
- php - 根据子数组的值将第二级子数组移动到第一级多维数组的顶部
- javascript - 必填字段的错误放置问题
- google-chrome - Chrome 91 抱怨 QuillJS 中的内部调用