Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
600 views
in Technique[技术] by (71.8m points)

opencv - Using pixel_labels, how to separate objects in an image by color, which will result in three images in 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:

enter image description here enter image description here

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:

enter image description here

enter image description here

enter image description here


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)

enter image description here

enter image description here

enter image description here

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...