creek
The AI Image Editor of 2030git clone https://github.com/maydayv7/creek
models/color.py (3278B)
1"""
2Color
3Original file: https://colab.research.google.com/drive/1o7cMSAesuuaxFQsteQL4ViwL_qNeTWbm
4"""
5
6import cv2
7import numpy as np
8import matplotlib.pyplot as plt
9import matplotlib.colors as mcolors
10from sklearn.cluster import KMeans
11from google.colab import files
12from PIL import Image
13import io
14
15
16def get_dominant_colors(image, k=5):
17 """
18 Extracts dominant colors using KMeans.
19 Expects a PIL Image or Numpy array (RGB).
20 """
21 if isinstance(image, Image.Image):
22 image = np.array(image)
23
24 img_small = cv2.resize(image, (150, 150), interpolation=cv2.INTER_AREA)
25
26 pixels = img_small.reshape((-1, 3))
27
28 kmeans = KMeans(n_clusters=k, n_init="auto", random_state=42)
29 kmeans.fit(pixels)
30
31 colors = kmeans.cluster_centers_.astype(int)
32
33 return sorted(colors.tolist(), key=lambda x: sum(x))
34
35
36def classify_mood(rgb_colors):
37 """
38 Classifies mood based on HSV values using Matplotlib colors.
39 """
40 norm_colors = np.array(rgb_colors) / 255.0
41
42 hsv_stats = mcolors.rgb_to_hsv(norm_colors)
43
44 avg_sat = np.mean(hsv_stats[:, 1])
45 avg_val = np.mean(hsv_stats[:, 2])
46
47 if avg_sat < 0.15 and avg_val > 0.65:
48 return "Minimalist"
49 if avg_val < 0.35:
50 return "Dark/Moody"
51 if avg_sat < 0.45 and avg_val > 0.75:
52 return "Pastel"
53 if avg_sat > 0.65 and avg_val > 0.5:
54 return "Neon"
55
56 earthy_votes = sum(1 for h, s, v in hsv_stats if (0.02 <= h <= 0.42) and s < 0.8)
57 if earthy_votes >= 3:
58 return "Earthy"
59
60 warm_votes = sum(1 for h, s, v in hsv_stats if h < 0.17 or h > 0.83)
61 return "Warm" if warm_votes >= 3 else "Cool"
62
63
64def rgb_to_hex(rgb):
65 return "#{:02x}{:02x}{:02x}".format(rgb[0], rgb[1], rgb[2])
66
67
68# Runner
69
70
71def analyze_uploaded_image():
72 print("Please upload an image file...")
73 uploaded = files.upload()
74
75 for fn in uploaded.keys():
76 print(f"\nProcessing {fn}...")
77
78 image_data = uploaded[fn]
79 image = Image.open(io.BytesIO(image_data)).convert("RGB")
80
81 colors = get_dominant_colors(image)
82 if colors is None:
83 print("Error processing image.")
84 continue
85
86 mood = classify_mood(colors)
87 hex_colors = [rgb_to_hex(c) for c in colors]
88
89 print(f"Detected Mood: {mood}")
90 print("Extracted Palette:")
91 print("-" * 30)
92 for i, h in enumerate(hex_colors):
93 print(f"Color {i+1}: {h}")
94 print("-" * 30)
95
96 fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10, 4))
97
98 ax1.imshow(image)
99 ax1.axis("off")
100 ax1.set_title(f"Mood: {mood}", fontweight="bold")
101
102 y_pos = np.arange(len(colors))
103 ax2.barh(y_pos, [1] * len(colors), color=hex_colors)
104 ax2.invert_yaxis()
105 ax2.axis("off")
106
107 for i, h in enumerate(hex_colors):
108 brightness = sum(colors[i]) / 3
109 text_col = "black" if brightness > 128 else "white"
110 ax2.text(
111 0.5,
112 i,
113 f"{h}",
114 ha="center",
115 va="center",
116 color=text_col,
117 fontweight="bold",
118 fontsize=12,
119 )
120
121 plt.tight_layout()
122 plt.show()
123
124
125if __name__ == "__main__":
126 analyze_uploaded_image()