Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
118 changes: 118 additions & 0 deletions ev3dev/sensor/lego.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,6 +261,124 @@ def rgb(self):
min(int((green * 255) / self.green_max), 255),
min(int((blue * 255) / self.blue_max), 255))

@property
def lab(self):
"""
Return colors in Lab color space
"""
RGB = [0, 0, 0]
XYZ = [0, 0, 0]

for (num, value) in enumerate(self.rgb):
if value > 0.04045:
value = pow(((value + 0.055) / 1.055), 2.4)
else:
value = value / 12.92

RGB[num] = value * 100.0

# http://www.brucelindbloom.com/index.html?Eqn_RGB_XYZ_Matrix.html
# sRGB
# 0.4124564 0.3575761 0.1804375
# 0.2126729 0.7151522 0.0721750
# 0.0193339 0.1191920 0.9503041
X = (RGB[0] * 0.4124564) + (RGB[1] * 0.3575761) + (RGB[2] * 0.1804375)
Y = (RGB[0] * 0.2126729) + (RGB[1] * 0.7151522) + (RGB[2] * 0.0721750)
Z = (RGB[0] * 0.0193339) + (RGB[1] * 0.1191920) + (RGB[2] * 0.9503041)

XYZ[0] = X / 95.047 # ref_X = 95.047
XYZ[1] = Y / 100.0 # ref_Y = 100.000
XYZ[2] = Z / 108.883 # ref_Z = 108.883

for (num, value) in enumerate(XYZ):
if value > 0.008856:
value = pow(value, (1.0 / 3.0))
else:
value = (7.787 * value) + (16 / 116.0)

XYZ[num] = value

L = (116.0 * XYZ[1]) - 16
a = 500.0 * (XYZ[0] - XYZ[1])
b = 200.0 * (XYZ[1] - XYZ[2])

L = round(L, 4)
a = round(a, 4)
b = round(b, 4)

return (L, a, b)

@property
def hsv(self):
"""
HSV: Hue, Saturation, Value
H: position in the spectrum
S: color saturation ("purity")
V: color brightness
"""
(r, g, b) = self.rgb
maxc = max(r, g, b)
minc = min(r, g, b)
v = maxc

if minc == maxc:
return 0.0, 0.0, v

s = (maxc-minc) / maxc
rc = (maxc-r) / (maxc-minc)
gc = (maxc-g) / (maxc-minc)
bc = (maxc-b) / (maxc-minc)

if r == maxc:
h = bc-gc
elif g == maxc:
h = 2.0+rc-bc
else:
h = 4.0+gc-rc

h = (h/6.0) % 1.0

return (h, s, v)

@property
def hls(self):
"""
HLS: Hue, Luminance, Saturation
H: position in the spectrum
L: color lightness
S: color saturation
"""
(r, g, b) = self.rgb
maxc = max(r, g, b)
minc = min(r, g, b)
l = (minc+maxc)/2.0

if minc == maxc:
return 0.0, l, 0.0

if l <= 0.5:
s = (maxc-minc) / (maxc+minc)
else:
if 2.0-maxc-minc == 0:
s = 0
else:
s = (maxc-minc) / (2.0-maxc-minc)

rc = (maxc-r) / (maxc-minc)
gc = (maxc-g) / (maxc-minc)
bc = (maxc-b) / (maxc-minc)

if r == maxc:
h = bc-gc
elif g == maxc:
h = 2.0+rc-bc
else:
h = 4.0+gc-rc

h = (h/6.0) % 1.0

return (h, l, s)

@property
def red(self):
"""
Expand Down