Last active
September 8, 2016 06:31
-
-
Save joejulian/970fcd5ecf3b792bc78a6d6ebc59a55f to your computer and use it in GitHub Desktop.
Groovy source for rgb to hsv conversion since groovy doesn't have a properly working modulo operator.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def rgbToHSV(red, green, blue) { | |
float r = red / 255f | |
float g = green / 255f | |
float b = blue / 255f | |
float max = [r, g, b].max() | |
float min = [r, g, b].min() | |
float delta = max - min | |
def hue = 0 | |
def saturation = 0 | |
if (max == min) { | |
hue = 0 | |
} else if (max == r) { | |
def h1 = (g - b) / delta / 6 | |
def h2 = h1.asType(int) | |
if (h1 < 0) { | |
hue = (360 * (1 + h1 - h2)).round() | |
} else { | |
hue = (360 * (h1 - h2)).round() | |
} | |
log.trace("rgbToHSV: red max=${max} min=${min} delta=${delta} h1=${h1} h2=${h2} hue=${hue}") | |
} else if (max == g) { | |
hue = 60 * ((b - r) / delta + 2) | |
log.trace("rgbToHSV: green hue=${hue}") | |
} else { | |
hue = 60 * ((r - g) / (max - min) + 4) | |
log.trace("rgbToHSV: blue hue=${hue}") | |
} | |
if (max == 0) { | |
saturation = 0 | |
} else { | |
saturation = delta / max * 100 | |
} | |
def value = max * 100 | |
return [ | |
"red": red.asType(int), | |
"green": green.asType(int), | |
"blue": blue.asType(int), | |
"hue": hue.asType(int), | |
"saturation": saturation.asType(int), | |
"value": value.asType(int), | |
] | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment