Last active
October 20, 2022 23:36
-
-
Save victormurcia/8b1ac78e152673d23230b221d199178a to your computer and use it in GitHub Desktop.
KMeans for color detection no mask
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| def KMeansImage(img, clusters): | |
| """ | |
| Args: | |
| path2img : (str) path to cropped player bounding box | |
| clusters : (int) how many clusters to use for KMEANS | |
| Returns: | |
| rgb_array : (tuple) Dominant colors in image in RGB format | |
| """ | |
| org_img = img.copy() | |
| #Convert image to HSV | |
| hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) | |
| #Convert image into a 1D array | |
| flat_img = np.reshape(hsv,(-1,3)) | |
| arrayLen = flat_img.shape | |
| rgb_array = [] | |
| #Do the clustering | |
| kmeans = KMeans(n_clusters = clusters, random_state=0, tol = 1e-4) | |
| kmeans.fit(flat_img) | |
| #Define the array with centroids | |
| dominant_colors = np.array(kmeans.cluster_centers_,dtype='uint') | |
| #Calculate percentages | |
| percentages = (np.unique(kmeans.labels_,return_counts=True)[1])/flat_img.shape[0] | |
| #Combine centroids representing dominant colors and percentages | |
| #associated with each centroid into an array | |
| pc = list(zip(percentages,dominant_colors)) | |
| pc = sorted(reversed(pc), reverse = True, key = lambda x: x[0]) | |
| i = 0 | |
| for i in range(clusters): | |
| #dummy_array = pc[i][1] | |
| rgb_array.append(pc[i][1]) | |
| i += 1 | |
| return rgb_array |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment