Python 使用簇时如何忽略颜色或alpha
我正在尝试使用Pil和cluster查找图像的主色。我的问题是,我的图像有一个透明的背景,因为它们是.png,所以我总是以黑色作为主色。我想忽略第一种主色调,选择第二种主色调 有没有办法忽略alpha颜色,或者直接从结果中删除它? 我担心,如果背景只是图像中很小的一部分,我只需去除第一个最主要的颜色,有时就会去除实际的主要颜色 这是我的密码:Python 使用簇时如何忽略颜色或alpha,python,python-imaging-library,cluster-computing,Python,Python Imaging Library,Cluster Computing,我正在尝试使用Pil和cluster查找图像的主色。我的问题是,我的图像有一个透明的背景,因为它们是.png,所以我总是以黑色作为主色。我想忽略第一种主色调,选择第二种主色调 有没有办法忽略alpha颜色,或者直接从结果中删除它? 我担心,如果背景只是图像中很小的一部分,我只需去除第一个最主要的颜色,有时就会去除实际的主要颜色 这是我的密码: from PIL import Image import numpy import math import matplotlib.pyplot as pl
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()
以下是我当前代码的示例:
图片如下:
返回值:
您可以避免像这样将透明像素传递到分类器中,如果这是您的意思:
#!/usr/bin/env python3
from PIL import Image
import numpy as np
import math
import matplotlib.pyplot as plot
from sklearn.cluster import MiniBatchKMeans
# Open image
imgfile = Image.open("abra.png")
# Only pass through non-transparent pixels, i.e. those where A!=0 in the RGBA quad
na = np.array([f for f in imgfile.getdata() if f[3] !=0], np.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(na)
npbins = np.arange(0, cluster_count + 1)
histogram = np.histogram(clusters.labels_, bins=npbins)
labels = np.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 PIL/Pillow、图像处理、k-均值、聚类、忽略透明像素、考虑alpha、考虑透明度、忽略透明度