기계는 거짓말하지 않는다

Python colorsys 모듈을 이용한 일정한 분포의 색상 생성 함수 본문

Python

Python colorsys 모듈을 이용한 일정한 분포의 색상 생성 함수

KillinTime 2025. 1. 21. 22:47

Python에서 colorsys 모듈을 이용하여 지정된 개수만큼의 색상을

일정하게 분포된 색상 팔레트를 생성하는 간단한 함수이다.

import colorsys
def generate_colors(num_classes: int, alpha=1):
"""
list of tuple: (R, G, B, A) 0~255
"""
colors = []
for i in range(num_classes):
hue = i / num_classes
# S=1.0, V=1.0
rgb = colorsys.hsv_to_rgb(hue, 1.0, 1.0)
# # RGB 0~255
# r, g, b = [int(x * 255) for x in rgb]
# RGB 0~1
r, g, b = [x for x in rgb]
# alpha
a = alpha # 128 # 50%
colors.append((r, g, b, a))
return colors
Comments