bpo-42452: Improve colorsys.rgb_to_hls code (GH-23306)

Cache repeated sum and difference to make code slightly faster and easier to read.
This commit is contained in:
Julien Jerphanion 2020-11-28 07:11:19 +00:00 committed by GitHub
parent 44ca05afc8
commit f9195318a8
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 7 deletions

View File

@ -75,17 +75,18 @@ def yiq_to_rgb(y, i, q):
def rgb_to_hls(r, g, b): def rgb_to_hls(r, g, b):
maxc = max(r, g, b) maxc = max(r, g, b)
minc = min(r, g, b) minc = min(r, g, b)
# XXX Can optimize (maxc+minc) and (maxc-minc) sumc = (maxc+minc)
l = (minc+maxc)/2.0 rangec = (maxc-minc)
l = sumc/2.0
if minc == maxc: if minc == maxc:
return 0.0, l, 0.0 return 0.0, l, 0.0
if l <= 0.5: if l <= 0.5:
s = (maxc-minc) / (maxc+minc) s = rangec / sumc
else: else:
s = (maxc-minc) / (2.0-maxc-minc) s = rangec / (2.0-sumc)
rc = (maxc-r) / (maxc-minc) rc = (maxc-r) / rangec
gc = (maxc-g) / (maxc-minc) gc = (maxc-g) / rangec
bc = (maxc-b) / (maxc-minc) bc = (maxc-b) / rangec
if r == maxc: if r == maxc:
h = bc-gc h = bc-gc
elif g == maxc: elif g == maxc: