Skip to content

Instantly share code, notes, and snippets.

@avinash
Created March 10, 2020 04:29
Show Gist options
  • Save avinash/8f986a8f2a5c9749bef5b571405bf1ea to your computer and use it in GitHub Desktop.
Save avinash/8f986a8f2a5c9749bef5b571405bf1ea to your computer and use it in GitHub Desktop.
Generate a complementary colour using the HSLuv colour space
# Generate colours which work well together
# Reference
# https://www.kuon.ch/post/2020-03-08-hsluv/
# https://www.boronine.com/2012/03/26/Color-Spaces-for-Human-Beings/
# https://github.com/hsluv/hsluv-python
import hsluv
# Some simple constants
R, G, B = 0, 1, 2
L, U, V = 0, 1, 2
# The angle to shift the color to produce its complementary
COMPLEMENTARY = 180.0
# Some utility functions
def scale(rgb):
return [rgb[R]/100.0, rgb[G]/100.0, rgb[B]/100.0]
def descale(rgb):
return [round(rgb[R]*100.0, 1), round(rgb[G]*100.0, 1), round(rgb[B]*100.0, 1)]
# The function generates a complementary colour (with the same perceptual
# brightness and saturation) as the given RGB (from GIMP for example)
# NB: each component goes from 0.0 to 100.0 (GIMP style)
def generate_complementary(rgb_color):
print("rbg", rgb_color)
rgb_color = scale(rgb_color)
# The corresponding HSLuv
hsluv_color = hsluv.rgb_to_hsluv(rgb_color)
print("hsluv", hsluv_color)
# A complementary colour created by shifting the L component by 180 degrees
hsluv_color_complementary = hsluv_color[:]
if (hsluv_color_complementary[L] < COMPLEMENTARY):
hsluv_color_complementary[L] += COMPLEMENTARY
else:
hsluv_color_complementary[L] -= COMPLEMENTARY
print("hsluv complementary", hsluv_color_complementary)
# And converted to RGB
rgb_color_complementary = hsluv.hsluv_to_rgb(hsluv_color_complementary)
rgb_color_complementary = descale(rgb_color_complementary)
print("rgb complementary", rgb_color_complementary)
# From GIMP -- hsluv expects components from 0 to 1
generate_complementary([96.6,63.1,10.2])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment