Created
January 9, 2020 06:44
-
-
Save nedaresa/56460f5f2ddfd4c7aaa10c4e08518d5c to your computer and use it in GitHub Desktop.
This function detects dominant color from an image
This file contains 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
### Neda Jabbari | |
### Jan 8, 2020 | |
### The get_dominant_color function detects dominant color from an image using a dictionary of basic colors, | |
### k-means clustering and eucledian distance. | |
def get_dominant_color(image, k, image_processing_size): | |
""" | |
Read and prepare image in RGB color space. | |
Perform kmeans clustering to get color clusters. | |
Detect dominant color based on the euclidean distance between the clusters and the basic colors. | |
Return the basic color associated with the min euclidean distance. | |
""" | |
#Define basic colors in RGB colorspace | |
basiccolors = {'red':[255,0,0], | |
'blue':[0,0,255], | |
'yellow':[255,255,0], | |
'purple':[128,0,128], | |
'dark orange':[255,140,0]} | |
mincolors =[] | |
#read image in BGR space | |
image = cv2.imread(image) | |
#convert color space from BGR to RGB | |
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) | |
#resize the image to reduce computation time | |
image = cv2.resize(image, image_processing_size, interpolation = cv2.INTER_AREA) | |
#reshape array to perform clustering | |
image = image.reshape((image.shape[0] * image.shape[1], 3)) | |
#make an instant from the KMeans class | |
kmeans = KMeans(n_clusters = k) | |
#fit kmeans | |
kmeans.fit(image) | |
#Get color cluster centers | |
rgbs = kmeans.cluster_centers_.astype(int) | |
#Calculate the eucledian distance | |
for rgb in rgbs: | |
cluster_dist= {} | |
for c,r in basiccolors.items(): | |
dist = distance.euclidean(rgb, r) | |
cluster_dist[c] = dist | |
for k,v in cluster_dist.items(): | |
if v == min(list(cluster_dist.values())): | |
mincolors.append((k, v)) | |
#get the pair with minimum distance | |
color = min(mincolors, key=lambda x:x[1])[0] | |
return color |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment