Color Similarity

Color similarity measures how closely two colors match based on human perception. Colorium provides similarity scoring from 0.0 to 1.0, making it easy to determine color relationships.

Understanding Similarity

Similarity scores are derived from Delta E (color distance) mapped to a 0-1 scale:

ScoreDescriptionDelta E Range
1.0Identical0
0.9 - 1.0Very similar0 - 1
0.7 - 0.9Similar1 - 3
0.5 - 0.7Moderately similar3 - 6
0.3 - 0.5Different6 - 10
0.1 - 0.3Very different10 - 20
0.0 - 0.1Completely different20+

Basic Usage

Calculating Similarity

1
2
3
4
5
6
7
8
from colorium import Color

color1 = Color(100, 150, 200)
color2 = Color(120, 130, 180)

# Calculate similarity (0.0 to 1.0)
similarity = color1.similarity(color2)
print(f"Similarity: {similarity:.2f}")

Checking Similarity

1
2
3
4
5
6
7
8
9
10
from colorium import Color

color1 = Color(100, 150, 200)
color2 = Color(120, 130, 180)

# Check if colors are similar
if color1.is_similar_to(color2, threshold=0.8):
    print("Colors are very similar!")
else:
    print("Colors are quite different")

Similarity Methods

Using Different Distance Algorithms

1
2
3
4
5
6
7
8
9
10
11
12
13
from colorium import Color

color1 = Color(100, 150, 200)
color2 = Color(120, 130, 180)

# Different methods
cie76 = color1.similarity(color2, "cie76")
cie94 = color1.similarity(color2, "cie94")
cie2000 = color1.similarity(color2, "cie2000")

print(f"CIE76 similarity: {cie76:.2f}")
print(f"CIE94 similarity: {cie94:.2f}")
print(f"CIE2000 similarity: {cie2000:.2f}")

Custom Thresholds

1
2
3
4
5
6
7
8
9
10
from colorium import Color

color1 = Color(100, 150, 200)
color2 = Color(120, 130, 180)

# Different thresholds
print(f"Strict (0.9): {color1.is_similar_to(color2, threshold=0.9)}")
print(f"Medium (0.7): {color1.is_similar_to(color2, threshold=0.7)}")
print(f"Loose (0.5): {color1.is_similar_to(color2, threshold=0.5)}")
print(f"Very loose (0.3): {color1.is_similar_to(color2, threshold=0.3)}")

Practical Examples

Color Grouping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from colorium import Color

def group_similar_colors(colors, threshold=0.7):
    """Group colors by similarity"""
    groups = []

    for color in colors:
        found = False
        for group in groups:
            # Check if color is similar to group representative
            if color.is_similar_to(group[0], threshold):
                group.append(color)
                found = True
                break

        if not found:
            groups.append([color])

    return groups

# Sample colors
colors = [
    Color(255, 0, 0),     # Red
    Color(254, 5, 0),     # Similar red
    Color(250, 50, 0),    # Orange-red
    Color(0, 0, 255),     # Blue
    Color(5, 0, 254),     # Similar blue
    Color(0, 0, 200),     # Darker blue
    Color(0, 255, 0),     # Green
]

# Group similar colors
groups = group_similar_colors(colors, threshold=0.8)

for i, group in enumerate(groups):
    print(f"Group {i+1}:")
    for color in group:
        print(f"  {color.to_hex_string()}")

Finding Most Similar Color

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
from colorium import Color

def find_most_similar(target, palette):
    """Find the most similar color in a palette"""
    best_color = None
    best_similarity = -1

    for color in palette:
        similarity = target.similarity(color)
        if similarity > best_similarity:
            best_similarity = similarity
            best_color = color

    return best_color, best_similarity

# Create palette
palette = [
    Color(255, 0, 0),     # Red
    Color(0, 255, 0),     # Green
    Color(0, 0, 255),     # Blue
    Color(255, 255, 0),   # Yellow
    Color(255, 0, 255),   # Magenta
    Color(0, 255, 255)    # Cyan
]

# Find most similar
target = Color(200, 50, 50)
best, similarity = find_most_similar(target, palette)

print(f"Target: {target.to_hex_string()}")
print(f"Best match: {best.to_hex_string()}")
print(f"Similarity: {similarity:.2f}")

Color Filtering

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from colorium import Color

def filter_similar_colors(colors, target, threshold=0.6):
    """Filter colors similar to target"""
    return [
        color for color in colors
        if color.is_similar_to(target, threshold)
    ]

# Sample colors
colors = [
    Color(255, 0, 0),
    Color(254, 10, 0),
    Color(250, 100, 0),
    Color(200, 50, 50),
    Color(100, 150, 200),
    Color(0, 0, 255)
]

target = Color(255, 0, 0)
similar = filter_similar_colors(colors, target)

print("Colors similar to red:")
for color in similar:
    print(f"  {color.to_hex_string()}")

Similarity Classification

Color Categories

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
from colorium import Color

class ColorSimilarityClassifier:
    def __init__(self):
        self.categories = {}

    def add_category(self, name, colors):
        """Add a category with representative colors"""
        self.categories[name] = colors

    def classify(self, color, threshold=0.6):
        """Classify a color into a category"""
        best_category = None
        best_similarity = -1

        for category_name, colors in self.categories.items():
            for category_color in colors:
                similarity = color.similarity(category_color)
                if similarity > best_similarity and similarity >= threshold:
                    best_similarity = similarity
                    best_category = category_name

        return best_category, best_similarity

# Create classifier
classifier = ColorSimilarityClassifier()

# Add categories
classifier.add_category("warm", [
    Color(255, 0, 0),     # Red
    Color(255, 165, 0),   # Orange
    Color(255, 255, 0)    # Yellow
])

classifier.add_category("cool", [
    Color(0, 0, 255),     # Blue
    Color(0, 255, 255),   # Cyan
    Color(128, 0, 128)    # Purple
])

classifier.add_category("neutral", [
    Color(128, 128, 128), # Gray
    Color(255, 255, 255), # White
    Color(0, 0, 0)        # Black
])

# Classify a color
color = Color(100, 150, 200)
category, similarity = classifier.classify(color)

print(f"Color: {color.to_hex_string()}")
print(f"Category: {category or 'Unknown'}")
print(f"Similarity: {similarity:.2f}")

Advanced Similarity

Color Distance Visualization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
from colorium import Color

def visualize_similarity_network(colors, threshold=0.5):
    """Visualize color similarity network"""
    print("Similarity Network:")

    for i, color1 in enumerate(colors):
        connections = []
        for j, color2 in enumerate(colors):
            if i != j:
                sim = color1.similarity(color2)
                if sim >= threshold:
                    connections.append((j, sim))

        if connections:
            print(f"{color1.to_hex_string()} →")
            for j, sim in connections:
                print(f"  → {colors[j].to_hex_string()} ({sim:.2f})")

# Example
colors = [
    Color(255, 0, 0),
    Color(254, 10, 0),
    Color(250, 50, 0),
    Color(0, 0, 255),
    Color(0, 10, 254),
    Color(0, 50, 250)
]

visualize_similarity_network(colors)

Similarity Matrix

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
from colorium import Color

def similarity_matrix(colors):
    """Generate similarity matrix for colors"""
    n = len(colors)
    matrix = []

    for i in range(n):
        row = []
        for j in range(n):
            if i == j:
                row.append(1.0)
            else:
                row.append(round(colors[i].similarity(colors[j]), 2))
        matrix.append(row)

    return matrix

def print_matrix(matrix, colors):
    """Print similarity matrix"""
    # Header
    print("    ", end="")
    for color in colors:
        print(f"{color.to_hex_string()[:6]}", end=" ")
    print()

    # Rows
    for i, row in enumerate(matrix):
        print(f"{colors[i].to_hex_string()[:6]}", end=" ")
        for value in row:
            print(f"{value:5.2f}", end=" ")
        print()

# Usage
colors = [
    Color(255, 0, 0),
    Color(254, 10, 0),
    Color(250, 50, 0),
    Color(0, 0, 255)
]

matrix = similarity_matrix(colors)
print_matrix(matrix, colors)

Similarity Threshold Mapping

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from colorium import Color

def map_similarity_thresholds(colors):
    """Map similarity thresholds for color pairs"""
    results = {}

    for i in range(len(colors)):
        for j in range(i + 1, len(colors)):
            color1 = colors[i]
            color2 = colors[j]

            sim = color1.similarity(color2)

            if sim >= 0.8:
                level = "Very similar"
            elif sim >= 0.6:
                level = "Similar"
            elif sim >= 0.4:
                level = "Moderately similar"
            elif sim >= 0.2:
                level = "Different"
            else:
                level = "Very different"

            key = f"{color1.to_hex_string()}{color2.to_hex_string()}"
            results[key] = {
                'similarity': sim,
                'level': level
            }

    return results

# Usage
colors = [
    Color(255, 0, 0),
    Color(255, 100, 100),
    Color(200, 0, 0),
    Color(0, 0, 255)
]

mapping = map_similarity_thresholds(colors)
for pair, info in mapping.items():
    print(f"{pair}:")
    print(f"  Similarity: {info['similarity']:.2f}")
    print(f"  Level: {info['level']}")

Best Practices

Choosing Threshold Values

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
from colorium import Color

def get_recommended_threshold(use_case):
    """Get recommended threshold for different use cases"""
    thresholds = {
        'exact_match': 0.95,
        'color_matching': 0.85,
        'general_use': 0.70,
        'rough_grouping': 0.50,
        'broad_categories': 0.30
    }
    return thresholds.get(use_case, 0.70)

# Examples
print(f"Exact match: {get_recommended_threshold('exact_match')}")
print(f"Color matching: {get_recommended_threshold('color_matching')}")
print(f"General use: {get_recommended_threshold('general_use')}")

Performance Optimization

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
from colorium import Color
from functools import lru_cache

class SimilarityCache:
    def __init__(self):
        self.cache = {}

    def get_similarity(self, color1, color2, method="cie2000"):
        # Create normalized key (colors are sorted to make symmetric)
        key = (
            (color1.red, color1.green, color1.blue),
            (color2.red, color2.green, color2.blue),
            method
        )

        # Sort colors for consistent key
        if key[0] > key[1]:
            key = (key[1], key[0], key[2])

        if key not in self.cache:
            self.cache[key] = color1.similarity(color2, method)

        return self.cache[key]

# Usage
cache = SimilarityCache()
color1 = Color(100, 150, 200)
color2 = Color(120, 130, 180)

# First call calculates
sim1 = cache.get_similarity(color1, color2)

# Second call uses cache
sim2 = cache.get_similarity(color1, color2)

Next Steps


Previous: Color Distance Next: Named Colors →

On this page
21 sections