问题描述
我正在使用Kmeans算法在图像中创建聚类,但我想显示图像的单独聚类.例如,如果图像的K = 3,则我想将每个单独的群集部分保存在不同的文件中.我想使用python来实现此代码.
I am using Kmeans algorithm for creating clusters in an image but I wanted to display seperate clusters of an image. Example if value of K=3 for an image then I wanted to save each seperated cluster portion in a different file. I want to implement this code using python.
我已经应用了KMeans聚类算法,但群集显示在同一图中.
I have applied KMeans clustering algorithm clusters are showing but in the same plot.
推荐答案
让我们从左边的paddington开始,并假设您已经用k-均值将他的像素聚类为右/秒图像上的3种颜色:
Let's start with paddington on the left, and assume you have k-means clustered him down to 3 colours on the right/second image:
现在,我们找到了独特的颜色,并对其进行迭代.在循环内部,我们使用np.where()
将当前颜色的所有像素设置为白色,将所有其他像素设置为黑色:
Now we find the unique colours, and iterate over them. Inside the loop, we use np.where()
to set all pixels of the current colour to white and all others to black:
#!/usr/bin/env python3
import cv2
import numpy as np
# Load kmeans output image
im = cv2.imread('kmeans.png')
# Get list of unique colours
uniquecols = np.unique(im.reshape(-1,3), axis=0)
# Iterate over unique colours
for i, c in enumerate(uniquecols):
filename = f"colour-{i}.png"
print(f"Processing colour {c} into file {filename}")
# Make output image white wherever it matches this colour, and black elsewhere
result = np.where(np.all(im==c,axis=2)[...,None], 255, 0)
cv2.imwrite(filename, result)
示例输出
Processing colour [48 38 35] into file colour-0.png
Processing colour [138 140 152] into file colour-1.png
Processing colour [208 154 90] into file colour-2.png
这三个图像是:
如果您希望使用备用输出,请按如下所示更改np.where()
行:
Change the np.where()
line as follows if you prefer the alternative output:
# Make output image white wherever it doesn't match this colour
result = np.where(np.all(im==c,axis=2)[...,None], c, 255)
关键字:图像,图像处理,k均值聚类,颜色减少,颜色减少,Python,OpenCV,颜色分离,独特的颜色,独特的颜色.
Keywords: Image, image processing, k-means clustering, colour reduction, color reduction, Python, OpenCV, color separation, unique colours, unique colors.
这篇关于使用pixel_labels,如何按颜色分离图像中的对象,这将在python中产生三幅图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!