微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

使用集群时如何忽略颜色或 alpha

如何解决使用集群时如何忽略颜色或 alpha

我正在尝试使用 Pil 和 cluster 找到图像的主色。我的问题是我的图像具有透明背景,因为它们是 .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()

这是我当前代码的示例:

给出的图像:

abra.png

返回值:

Returned values

解决方法

您可以避免像这样将透明像素传递到分类器中,如果这就是您的意思:

#!/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()

enter image description here

关键字:Python PIL/Pillow、图像处理、k-means、聚类、忽略透明像素、考虑 alpha、考虑透明度、忽略透明度。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。