Using pixel_labels, how to separate objects in an image by color, which will result in three images in python

最后都变了- 提交于 2020-02-08 10:00:27

问题


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.

I have applied KMeans clustering algorithm clusters are showing but in the same plot.


回答1:


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:

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)

Sample Output

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

And the three images are:


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)

Keywords: Image, image processing, k-means clustering, colour reduction, color reduction, Python, OpenCV, color separation, unique colours, unique colors.



来源:https://stackoverflow.com/questions/58658641/using-pixel-labels-how-to-separate-objects-in-an-image-by-color-which-will-res

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!