Created
December 27, 2022 05:22
-
-
Save AnthonyVadala/44ab70516900c225b5c85f3ce2b7ac2f to your computer and use it in GitHub Desktop.
Python script that accepts a user inputted path/image, analyzes the colors used, creates a copy of the original image with circles showing the three most cominant colors in the image, and saves it as the original file name appended with "_primarycolors.png"
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
import cv2 | |
import numpy as np | |
from sklearn.cluster import KMeans | |
# function to draw small circles at the bottom right corner of the image | |
def draw_circles(image, colors): | |
height, width, _ = image.shape | |
circle_radius = int(min(height, width) * 0.05) # radius of the circles is 5% of the minimum of height and width | |
for i, color in enumerate(colors): | |
center_x = int(width * 0.9) | |
center_y = int(height * 0.9) - i * (circle_radius // 2) | |
if center_x - circle_radius >= 0 and center_x + circle_radius < width and center_y - circle_radius >= 0 and center_y + circle_radius < height: # check if the center of the circle is within the bounds of the image | |
cv2.circle(image, (center_x, center_y), circle_radius, color, -1) # draw the circle with the given color | |
# function to get the dominant colors of the image | |
def get_dominant_colors(image, k=3): | |
image = image.reshape((image.shape[0] * image.shape[1], 3)) # flatten the image into a list of pixels | |
clt = KMeans(n_clusters=k, n_init=10) # create a KMeans object with k clusters and n_init=10 | |
clt.fit(image) # fit the model to the pixels | |
return clt.cluster_centers_ # return the center of each cluster as the dominant colors | |
# read the image file | |
image_path = input("Enter the path to the image file: ") | |
try: | |
image = cv2.imread(image_path) | |
except: | |
print("Error: Invalid image file") | |
exit() | |
# get the dominant colors of the image | |
colors = get_dominant_colors(image) | |
# draw the circles with the dominant colors | |
draw_circles(image, colors) | |
# save the modified image | |
output_path = image_path.split('.')[0] + "_primarycolors.png" # create the output path by adding "_primarycolors.png" to the original image path | |
cv2.imwrite(output_path, image) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment