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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…