有没有办法根据颜色对图像进行聚类并通过使用 for 循环来可视化?

Is there a way to cluster an image based on colors and visualize that by using a for loop for example?

我正在尝试编写以下图像分类代码: https://www.thepythoncode.com/article/kmeans-for-image-segmentation-opencv-python

但我的问题是;有没有一种方法可以编写一个循环,以便对于您使用的每个集群,您都会得到一个新图像,使图像的这一部分变黑?

我正在尝试这个:

for i in range(0,k):
    cluster = i
    masked_img[labels == cluster] = [0, 0, 0]
    masked_img[i] = masked_img[i].reshape(image.shape)
    plt.figure()
    plt.imshow(masked_img[i])
    plt.show()

使用我最初加载的图像和 k=5 个簇,但我想要的是循环给我 5 个不同的图像,并显示 5 个单独的簇。我不知道如何解决这个问题,希望有人能解决!

在你的方法中,我认为如果你只是将 labels == cluster 更改为 labels != cluster,它应该有效。

然而,Python/OpenCV中还有另一种方式。

输入:

import cv2
import numpy as np

# read input and convert to range 0-1
image = cv2.imread('lake.png')
h, w, c = image.shape

# reshape to 1D array
image_2d = image.reshape(h*w, c).astype(np.float32)

# set number of colors
numcolors = 3
numiters = 10
epsilon = 1
attempts = 10

# do kmeans processing
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, numiters, epsilon)
ret, labels, centers = cv2.kmeans(image_2d, numcolors, None, criteria, attempts, cv2.KMEANS_RANDOM_CENTERS)

# reconstitute 2D image of results
centers = np.uint8(centers)
newimage = centers[labels.flatten()]
newimage = newimage.reshape(image.shape)
cv2.imwrite("lake_kmeans.png", newimage)
cv2.imshow('new image', newimage)
cv2.waitKey(0)

k = 0
for center in centers:
    # select center color and create mask
    #print(center)
    layer = newimage.copy()
    mask = cv2.inRange(layer, center, center)

    # apply mask to layer 
    layer[mask == 0] = [0,0,0]
    cv2.imshow('layer', layer)
    cv2.waitKey(0)


    # save kmeans clustered image and layer 
    cv2.imwrite("lake_layer{0}.png".format(k), layer)
    k = k + 1

k-均值结果:

层数: