Using Search & Recolor API with HEX Color Codes via Webcolors
📝 Overview
The Stability AI Search & Recolor API is a powerful tool for localized image editing. However, a technical limitation exists: the prompt parameter (which defines the target color) currently only accepts natural language strings (e.g., "ruby red", "navy blue", "forest green") rather than technical HEX or RGB values.
This article outlines a Python-based "Workaround" that translates precise hex codes into the nearest recognized CSS3 color names to ensure API compatibility.
🚩 The Challenge: Hex vs. Natural Language
Most design systems and UI tools provide colors in Hexadecimal format (e.g., #778071). If you pass #778071 directly into the Stability AI prompt field, the AI may interpret the string literally as a series of numbers or fail to produce the specific hue intended.
To bridge this gap, we must map 16.7 million possible hex combinations into the 147 standard CSS3 named colors that AI models understand most reliably.
⚙️ The Solution: Nearest-Neighbor Mapping
The provided solution uses a "Nearest-Neighbor" search algorithm. Since an exact match for a custom hex code rarely exists in the CSS3 library, the code treats colors as coordinates in a 3D space.
How it Works:
-
3D Coordinate Mapping: It treats Red, Green, and Blue as $X, Y,$ and $Z$ axes.
-
Euclidean Distance: It calculates the straight-line distance between your input color and every named color in the
webcolorslibrary using the formula:$$d^2 = (R_2 - R_1)^2 + (G_2 - G_1)^2 + (B_2 - B_1)^2$$ -
The "Winner": The named color with the smallest mathematical distance is selected as the prompt for the API.
🚀 Implementation
The following Python script integrates the translation logic directly into the Stability AI request pipeline.
⚠️ Limitations & Considerations
-
Precision Loss: Because there are only 147 CSS3 names, a very specific "Dusty Rose" might be simplified to "RosyBrown" or "Pink."
-
Perceptual Accuracy: This math uses "Euclidean Distance," which is mathematically perfect but doesn't always account for how humans perceive brightness. For 99% of recoloring tasks, however, this is the industry-standard approach.
✅ Conclusion
By using this mapping workaround, developers can allow users to pick colors via a standard hex-code UI while maintaining high reliability and "predictable" results from the Stability AI Search & Recolor endpoint.