Python Codes

Getting Adjacent Colors – Python Code

Adjacent colors are obtained by rotating 30 and 360 degrees of any given color from the color wheel.

adjacent-colors

Below is the Python code to achieve the same. The input supplied is Hex value of color and output is the list of two adjacent colors (Hex value).

# Import colorsys
import colorsys

# Module to convert rgb to hex
def rgb_to_hex(rgb):
    return '#%02X%02X%02X' % (rgb)

# Module to convert hex to rgb
def hex_to_rgb(value):
    value = value.lstrip('#')
    return tuple(int(value[i:i+2], 16) for i in (0, 2 ,4))

# This module gets the adjacent colors.
# They can be obtained by rotating the color by 30 and 360
# degrees.
def get_adjacent(color):
    # List to hold two colors
    adjacent_colors = []

    # Get the RGB
    (r, g, b) = hex_to_rgb(color)

    # Set the degree
    d = 30/360

    # Values has to be between 0 to 1
    r = r / 255.0
    g = g / 255.0
    b = b / 255.0

    # Convert to HLS using colorsys
    h, l, s = colorsys.rgb_to_hls(r, g, b)

    # Rotate the color
    h = [(h+d) % 1 for d in (-d, d)]

    # For both the colors, convert back to RGB and
    # load to list
    for hi in h:
        r, g, b = colorsys.hls_to_rgb(hi, l, s)
        r = r * 255.0
        g = g * 255.0
        b = b * 255.0
        hex_val = rgb_to_hex((r,g,b))

        adjacent_colors.append(hex_val)

    # Print the list
    print(adjacent_colors)

# Supply the input with required hex value.
get_adjacent("#FF0000")
Advertisements

Let me Know What you Think!

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s