Home > Blockchain >  Creating Circular Number Range in Python for Color Math
Creating Circular Number Range in Python for Color Math

Time:09-22

I'm working on creating a color wheel in Python. I start by generating random rgb colors and convert them to hsl and adjust the s & l. Then, I want to compare two colors and do an operation based on how similar or different they are. The HSL color wheel goes from 0 to 360. I want to know if the hue of color 2 is within -90 of the hue of color 1. For example, if color 1's hue is 300, I want to know if color 2's hue is between 210 and 30 (not 390). I am stuck trying to figure out how to tell Python this in an if statement.

# generate random rgb colors 

import random
no_of_colors= 23 
rgb_colors =["#" ''.join([random.choice('0123456789ABCDEF') for i in range(6)])
       for j in range(no_of_colors)]

# and then I convert them to hsl:

from  hsluv import hex_to_hsluv, hsluv_to_hex

hsl_colors = list()
for i in rgb_colors:
    col = hex_to_hsluv(i)
    hsl_colors.append(col)

# then I list them so they're mutable

hsl_colors = [list(elem) for elem in hsl_colors]

# then I change the s & l so that only hue is changing

# adjust s & l 
for i in hsl_colors:
    i[1] = 75

for i in hsl_colors:
    i[2] = 75

# I would do this above part again and make a hsl_colors2 
# list the same way so I have two lists of colors to compare. 
# This is where I am stuck. 

if hsl_colors2[0] > (hsl_colors[0]-90) or hsl_colors2[0] < (hsl_colors[0] 90):
                print(hsl_colors[j][0])
else:
                print("not within range")

# obviously this doesn't work, and needs to be informed of 
# the circular range. I've tried variations of this below 
# unsuccessfully. I've tried looking up examples and haven't 
# found anything useful. 

if hsl_colors2[0] > (hsl_colors[0]-90) or hsl_colors2[0] < (hsl_colors[0] 90):
                if hsl_colors[0] 90 > 360:
                     hsl_colors[0] 90 / 360
                     print(hsl_colors[0] 90 / 360)

else:
                print("not within range")


Any suggestions? TIA!

CodePudding user response:

I think you need the modulo operator %

a = (hsl_colors[0] - 90) % 360
b = (hsl_colors[0]   90) % 360
x = hsl_colors2[0]

if (a < x < b) or (b < a < x) or (x < b < a):
    print("within range")
else:
    print("not within range")
  • Related