简体   繁体   中英

How to generate dark shades of hex color codes in python

I am generating random different colors and generating like them below :

 import random
 import numpy as np

 random_number = np.random.randint(0,16777215)
 hex_number = str(hex(random_number))
 hex_number ='#'+ hex_number[2:]

But this generates mostly lighter shades and not dark ones. How can I modify this to generate darker shades.Any help is appreciated.

As the comments suggest, probably trying a different colour space is a better idea. For instance, you can use the HSV colour space and some functions provided by matplotlib .

import numpy as np
from matplotlib.colors import hsv_to_rgb, to_hex

def rand_col(min_v=0.5, max_v=1.0):
    hsv = np.concatenate([np.random.rand(2), np.random.uniform(min_v, max_v, size=1)])
    return to_hex(hsv_to_rgb(hdv))

If you lower the min_v parameter, you can get darker colours.

You can use below logic to darken a hex color(using hue, lightness, saturation (HLS) representation):

import numpy as np
from colormap import rgb2hex, rgb2hls, hls2rgb
# pip install colormap
# pip install easydev

def hex_to_rgb(hex):
     hex = hex.lstrip('#')
     hlen = len(hex)
     return tuple(int(hex[i:i+hlen//3], 16) for i in range(0, hlen, hlen//3))

def adjust_color_lightness(r, g, b, factor):
    h, l, s = rgb2hls(r / 255.0, g / 255.0, b / 255.0)
    l = max(min(l * factor, 1.0), 0.0)
    r, g, b = hls2rgb(h, l, s)
    return rgb2hex(int(r * 255), int(g * 255), int(b * 255))

def darken_color(r, g, b, factor=0.1):
    return adjust_color_lightness(r, g, b, 1 - factor)

random_number = np.random.randint(0,16777215)
hex_number = str(hex(random_number))
hex_number ='#'+ hex_number[2:]

r, g, b = hex_to_rgb(hex_number) # hex to rgb format
print(darken_color(r, g, b))

In the above, you can set factor parameter as per you requirement to adjust color lightness/darkness.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM