import numpy as np
import cv2
img = cv2.imread('papika.jpg')
Z = img.reshape((-1, 3))
# convert to np.float32
Z = np.float32(Z)
# define criteria, number of clusters(K) and apply kmeans()
criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0)
K = 5
ret, label, center = cv2.kmeans(Z, K, None, criteria, 10,
cv2.KMEANS_RANDOM_CENTERS)
center = np.uint8(center)
# redraw the image with pallete you made:
# res = center[label.flatten()]
# res2 = res.reshape((img.shape))
display_img = cv2.copyMakeBorder(
img,
0,
100,
0,
0,
borderType=cv2.BORDER_CONSTANT,
value=(255, 255, 255, 1))
for i, color in enumerate(center.tolist()):
r, g, b = color
color = (r, g, b)
OFFSET_X = 20
OFFSET_Y = 50
start_x = i * OFFSET_X
start_y = display_img.shape[0]
cv2.rectangle(
display_img, (start_x, start_y), (start_x + OFFSET_X - 1, start_y - OFFSET_Y),
color,
thickness=-1)
cv2.imshow('display_img', display_img)
cv2.waitKey(0)
cv2.destroyAllWindows()
this is a pretty shameless rip from opencv docs. im not really interested in ever reimplementing k-means by hand ever again after doing it in college. this wpc is a good intro to using opencv and machine learning
since a lot of you like to do this kind of stuff all from scratch in C, you might want to start at
opencv-python-tutroals.readthedocs.io/en/latest/py_tutorials/py_ml/py_kmeans/py_kmeans_understanding/py_kmeans_understanding.html#kmeans-clustering-understanding
which explains the implementation pretty well