Ask Your Question

Revision history [back]

click to hide/show revision 1
initial version

opencv python k-means seperate all the colours into different images

following is the opencv python code to get clustered image. After clustering, how do I seperate each color into different images i.e one cluster should be in one image , and the others in seoerate images. Can some please help me as soon as possible? If there is a way to put all the colors in one image one after the other like in the form of a bar graph, that would be great too. Please help me as soon as possible.

import numpy as np
import cv2


cap = cv2.VideoCapture(1)
cap.set(3,160)
cap.set(4,120)

# Capture frame-by-frame
ret, frame1 = cap.read()
ret, frame2 = cap.read()
ret, frame3 = cap.read()
ret, frame4 = cap.read()
ret, frame5 = cap.read()
ret, frame = cap.read()


cv2.imshow("original",frame)
Z = frame.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 = 3
ret,label,center=cv2.kmeans(Z,K,criteria,10,cv2.KMEANS_RANDOM_CENTERS)

# Now convert back into uint8, and make original image
center = np.uint8(center)
res = center[label.flatten()]
res2 = res.reshape((frame.shape))




cv2.imshow("clustered",res2)
cv2.waitKey(0)
cv2.destroyAllWindows