# Author: Arah J. Leonard # Copyright 01AUG09 # Original source: http://www.insanit.net/computer-programming/red-green-blue-to-red-yellow-blue-part-2/ # Distributed under the LGPL - http://www.gnu.org/copyleft/lesser.html # ALSO distributed under the The MIT License from the Open Source Initiative (OSI) - http://www.opensource.org/licenses/mit-license.php # You may use EITHER of these licenses to work with / distribute this source code. # Enjoy! # Convert a red-green-blue system to a red-yellow-blue system. def rgb2ryb(r, g, b): t = type(r) # Remove the whiteness from the color. w = float(min(r, g, b)) r = float(r) - w g = float(g) - w b = float(b) - w mg = max(r, g, b) # Get the yellow out of the red+green. y = min(r, g) r -= y g -= y # If this unfortunate conversion combines blue and green, then cut each in half to preserve the value's maximum range. if b and g: b /= 2.0 g /= 2.0 # Redistribute the remaining green. y += g b += g # Normalize to values. my = max(r, y, b) if my: n = mg / my r *= n y *= n b *= n # Add the white back in. r += w y += w b += w # And return back the ryb typed accordingly. return t(r), t(y), t(b) # Convert a red-yellow-blue system to a red-green-blue system. def ryb2rgb(r, y, b): t = type(r) # Remove the whiteness from the color. w = float(min(r, y, b)) r = float(r) - w y = float(y) - w b = float(b) - w my = max(r, y, b) # Get the green out of the yellow and blue g = min(y, b) y -= g b -= g if b and g: b *= 2.0 g *= 2.0 # Redistribute the remaining yellow. r += y g += y # Normalize to values. mg = max(r, g, b) if mg: n = my / mg r *= n g *= n b *= n # Add the white back in. r += w g += w b += w # And return back the ryb typed accordingly. return t(r), t(g), t(b) # Return the complementary color values for a given color. You must also give it the upper limit of the color values, typically 255 for GUIs, 1.0 for OpenGL. def complimentary(r, g, b, limit=255): return limit - r, limit - g, limit - b # Debugging test code. Not intended to be used as an application. if __name__=="__main__": red = (255, 0, 0) green = (0, 255, 0) blue = (0, 0, 255) cyan = (0, 255, 255) magenta = (255, 0, 255) yellow = (255, 255, 0) black = (0, 0, 0) white = (255, 255, 255) orange = (255, 128, 0) darkgreen = (0, 128, 0) tests = [red, green, blue, cyan, magenta, yellow, black, white, orange, darkgreen, (255, 128, 64), (255, 64, 128), (64, 255, 128), (128, 255, 64), (64, 128, 255), (128, 64, 255)] for test in tests: ryb = rgb2ryb(test[0], test[1], test[2]) rgb = ryb2rgb(ryb[0], ryb[1], ryb[2]) cryb = complimentary(ryb[0], ryb[1], ryb[2]) crgb = ryb2rgb(cryb[0], cryb[1], cryb[2]) print test, "rgb2ryb", ryb, "ryb2rgb", rgb print "complimentary rgb", complimentary(rgb[0], rgb[1], rgb[2]) print "complimentary ryb", cryb, "to rgb", crgb print