【问题标题】:How to ignore a color or alpha when using clusters使用集群时如何忽略颜色或 alpha
【发布时间】: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


    【解决方案1】:

    你可以避免像这样将透明像素传递给分类器,如果你是这个意思的话:

    #!/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-means、聚类、忽略透明像素、关注 alpha、关注透明度、忽略透明度。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-09-23
      • 2019-03-27
      • 1970-01-01
      • 2020-03-09
      • 1970-01-01
      • 2016-07-26
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多