The adi0308/Colour-Extract model remains the most suitable lightweight option for this task, as it directly outputs HEX codes that can be mapped to your 20-color list. Here's a streamlined approach:
Solution Overview
- Model:
adi0308/Colour-Extract (KMeans-based color extraction)[[5]]
- Output: HEX codes for dominant colors + closest-to-white color[[5]]
- Mapping: Convert HEX to RGB, then match to predefined color terms
Implementation
from transformers import pipeline
from PIL import Image
# Load the color extraction pipeline
color_extraction = pipeline("color-extraction")
# Define your 20-color mapping (example)
color_map = {
"red": (255, 0, 0),
"blue": (0, 0, 255),
"green": (0, 128, 0),
# ... add all 20 colors
}
def hex_to_rgb(hex_code):
return tuple(int(hex_code.lstrip('#')[i:i+2], 16) for i in (0, 2, 4))
def get_closest_color(hex_code, color_map):
rgb = hex_to_rgb(hex_code)
return min(color_map.items(), key=lambda x: sum(abs(a - b) for a, b in zip(x[[1]], rgb)))
# Process image
image = Image.open("image.jpg")
colors, center_hex = color_extraction(image)
center_color = get_closest_color(center_hex, color_map)
print(f"Center color: {center_color}")
Key Advantages
- No Training Required: Uses pre-trained KMeans clustering[[5]]
- Lightweight: Minimal computational overhead compared to vision transformers[[3]][[4]]
- Focus on Center: The
closest_to_white output prioritizes central regions[[5]]
Limitations
- Context-Awareness: Requires manual mapping for skin/object-specific terms (e.g.,
#8B4513 → "chocolate" vs. "brown")[[2]][[6]]
- Color Ambiguity: Overlapping RGB values may require threshold adjustments in
get_closest_color
This approach leverages existing infrastructure while accommodating your fixed color list through post-processing.