Создание диапазона циклических чисел в Python для математики цветов
Я работаю над созданием цветового круга в Python. Я начинаю с генерации случайных цветов rgb, преобразовываю их в hsl и настраиваю s & l. Затем я хочу сравнить два цвета и выполнить операцию, основанную на том, насколько они похожи или различны. Цветовой круг HSL варьируется от 0 до 360. Я хочу знать, находится ли оттенок цвета 2 в пределах +-90 от оттенка цвета 1. Например, если оттенок цвета 1 равен 300, я хочу знать, находится ли оттенок цвета 2 в пределах +-90 от оттенка цвета 1. находится между 210 и 30 (не 390). Я застрял, пытаясь понять, как сказать Python об этом в операторе if.
# 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")
Какие-либо предложения? ТИА!
1 ответ
Я думаю, вам нужен оператор по модулю%
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")