Skip to content

Instantly share code, notes, and snippets.

@andrisgauracs
Created January 10, 2019 22:56
Show Gist options
  • Select an option

  • Save andrisgauracs/ed33911ccfd10757608b6d4ea40e1bbc to your computer and use it in GitHub Desktop.

Select an option

Save andrisgauracs/ed33911ccfd10757608b6d4ea40e1bbc to your computer and use it in GitHub Desktop.
# Courtesy of https://www.pyimagesearch.com/2014/05/26/opencv-python-k-means-color-clustering/
def plot_colors(hist, centroids):
# initialize the bar chart representing the relative frequency
# of each of the colors
bar = np.zeros((50, 300, 3), dtype="uint8")
startX = 0
# Sort the centroids to form a gradient color look
centroids = sorted(centroids, key=lambda x: sum(x))
# loop over the percentage of each cluster and the color of
# each cluster
for (percent, color) in zip(hist, centroids[offset:]):
# plot the relative percentage of each cluster
# endX = startX + (percent * 300)
# Instead of plotting the relative percentage,
# we will make a n=clusters number of color rectangles
# we will also seperate them by a margin
new_length = 300 - margin * (clusters - 1)
endX = startX + new_length/clusters
cv2.rectangle(bar, (int(startX), 0), (int(endX), 50),
color.astype("uint8").tolist(), -1)
cv2.rectangle(bar, (int(endX), 0), (int(endX + margin), 50),
(255, 255, 255), -1)
startX = endX + margin
# return the bar chart
return bar
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment