【发布时间】:2021-06-13 20:18:21
【问题描述】:
我正在尝试使用 Pil 和集群找到图像的主色。我的问题是我的图像具有透明背景,因为它们是 .png,所以我总是将黑色作为主色。我想忽略第一个主色并选择第二个主色。
有没有办法忽略 alpha 颜色或将其从结果中删除? 恐怕通过仅删除第一个最主要的颜色,我有时会删除实际的主要颜色,以防背景只是图像的一小部分。
这是我的代码:
from PIL import Image
import numpy
import math
import matplotlib.pyplot as plot
from sklearn.cluster import MiniBatchKMeans
imgfile = Image.open("images/abra.png")
numarray = numpy.array(imgfile.getdata(), numpy.uint8)
X = []
Y = []
fig, axes = plot.subplots(nrows=5, ncols=2, figsize=(20,25))
xaxis = 0
yaxis = 0
cluster_count = 3
clusters = MiniBatchKMeans(n_clusters = cluster_count)
clusters.fit(numarray)
npbins = numpy.arange(0, cluster_count + 1)
histogram = numpy.histogram(clusters.labels_, bins=npbins)
labels = numpy.unique(clusters.labels_)
barlist = axes[xaxis, yaxis].bar(labels, histogram[0])
if(yaxis == 0):
yaxis = 1
else:
xaxis = xaxis + 1
yaxis = 0
for i in range(cluster_count):
barlist[i].set_color('#%02x%02x%02x' % (
math.ceil(clusters.cluster_centers_[i][0]),
math.ceil(clusters.cluster_centers_[i][1]),
math.ceil(clusters.cluster_centers_[i][2])))
plot.show()
这是我当前代码的示例:
给定的图片:
返回值:
【问题讨论】:
标签: python python-imaging-library cluster-computing