Spaces:
Running
Running
Upload app.py with huggingface_hub
Browse files
app.py
CHANGED
|
@@ -15,6 +15,9 @@ def extract_colors(img, num_colors):
|
|
| 15 |
# Remove any grayscale or alpha if present
|
| 16 |
if data.shape[1] == 4:
|
| 17 |
data = data[:, :3]
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
# Fit KMeans
|
| 20 |
kmeans = KMeans(n_clusters=num_colors, random_state=42)
|
|
@@ -23,16 +26,20 @@ def extract_colors(img, num_colors):
|
|
| 23 |
# Get cluster centers
|
| 24 |
colors = kmeans.cluster_centers_.round().astype(int)
|
| 25 |
|
|
|
|
|
|
|
|
|
|
|
|
|
| 26 |
# Convert to hex
|
| 27 |
hex_colors = ['#' + ''.join(f'{c:02x}' for c in color) for color in colors]
|
| 28 |
|
| 29 |
# Generate HTML for palette
|
| 30 |
html = '<div style="text-align: center;"><h2>Color Palette</h2><div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">'
|
| 31 |
-
for hex_color in hex_colors:
|
| 32 |
html += f'''
|
| 33 |
<div style="display: flex; flex-direction: column; align-items: center; gap: 5px;">
|
| 34 |
<div style="background-color: {hex_color}; width: 80px; height: 80px; border: 2px solid #333; border-radius: 10px;"></div>
|
| 35 |
-
<span style="font-size: 12px; font-weight: bold;">{hex_color}</span>
|
| 36 |
</div>
|
| 37 |
'''
|
| 38 |
html += '</div></div>'
|
|
|
|
| 15 |
# Remove any grayscale or alpha if present
|
| 16 |
if data.shape[1] == 4:
|
| 17 |
data = data[:, :3]
|
| 18 |
+
elif data.shape[1] == 1:
|
| 19 |
+
# If grayscale, replicate to RGB
|
| 20 |
+
data = np.repeat(data, 3, axis=1)
|
| 21 |
|
| 22 |
# Fit KMeans
|
| 23 |
kmeans = KMeans(n_clusters=num_colors, random_state=42)
|
|
|
|
| 26 |
# Get cluster centers
|
| 27 |
colors = kmeans.cluster_centers_.round().astype(int)
|
| 28 |
|
| 29 |
+
# Calculate percentages
|
| 30 |
+
labels = kmeans.labels_
|
| 31 |
+
percentages = [(np.sum(labels == i) / len(labels)) * 100 for i in range(num_colors)]
|
| 32 |
+
|
| 33 |
# Convert to hex
|
| 34 |
hex_colors = ['#' + ''.join(f'{c:02x}' for c in color) for color in colors]
|
| 35 |
|
| 36 |
# Generate HTML for palette
|
| 37 |
html = '<div style="text-align: center;"><h2>Color Palette</h2><div style="display: flex; flex-wrap: wrap; justify-content: center; gap: 10px;">'
|
| 38 |
+
for hex_color, percent in zip(hex_colors, percentages):
|
| 39 |
html += f'''
|
| 40 |
<div style="display: flex; flex-direction: column; align-items: center; gap: 5px;">
|
| 41 |
<div style="background-color: {hex_color}; width: 80px; height: 80px; border: 2px solid #333; border-radius: 10px;"></div>
|
| 42 |
+
<span style="font-size: 12px; font-weight: bold;">{hex_color} ({percent:.1f}%)</span>
|
| 43 |
</div>
|
| 44 |
'''
|
| 45 |
html += '</div></div>'
|