Spaces:
Running
Running
aditink
commited on
Commit
·
a4ba88e
1
Parent(s):
4112803
reassigning colors
Browse files- colorbynumber/assign_colors.py +27 -0
- environment.yml +1 -0
colorbynumber/assign_colors.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from scipy.optimize import linear_sum_assignment
|
2 |
+
import numpy as np
|
3 |
+
|
4 |
+
def assign_colors(palette_a, palette_b, weights):
|
5 |
+
"""Given:
|
6 |
+
- color palette A generated by k-means,
|
7 |
+
- color palette B provided by the user and
|
8 |
+
- weight w for each color in A corresponding to "importance" of the color,
|
9 |
+
assigns each color in B to a color in A such that the sum of the squared
|
10 |
+
distances between the colors in A and B is minimized.
|
11 |
+
Returns a dictionary mapping each color in B to a color in A.
|
12 |
+
"""
|
13 |
+
# Create a cost matrix where the element at position (i, j) is the
|
14 |
+
# squared distance between color i in palette A and color j in palette B,
|
15 |
+
# multiplied by the weight of color i.
|
16 |
+
cost_matrix = np.zeros((len(palette_a), len(palette_b)))
|
17 |
+
for i, color_a in enumerate(palette_a):
|
18 |
+
for j, color_b in enumerate(palette_b):
|
19 |
+
cost_matrix[i, j] = weights[i] * np.sum((np.array(color_a) - np.array(color_b))**2)
|
20 |
+
|
21 |
+
# Use the linear_sum_assignment function to find the optimal assignment.
|
22 |
+
row_indices, col_indices = linear_sum_assignment(cost_matrix)
|
23 |
+
|
24 |
+
# Create a dictionary mapping each color in B to a color in A.
|
25 |
+
color_mapping = {tuple(palette_b[j]): tuple(palette_a[i]) for i, j in zip(row_indices, col_indices)}
|
26 |
+
|
27 |
+
return color_mapping
|
environment.yml
CHANGED
@@ -8,5 +8,6 @@ dependencies:
|
|
8 |
- opencv
|
9 |
- jupyterlab
|
10 |
- matplotlib
|
|
|
11 |
- pip:
|
12 |
- python-polylabel
|
|
|
8 |
- opencv
|
9 |
- jupyterlab
|
10 |
- matplotlib
|
11 |
+
- scipy
|
12 |
- pip:
|
13 |
- python-polylabel
|