Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Works out the YIQ values of a given RGB colour and suggests a pallet of similar colours with the same chrominance. This can be used on legacy TV platforms to reduce chroma crawl, where colours bleed into each other.
#!/usr/bin/env python
import sys
def rgb2Yiq(red, green, blue):
y = int((0.299 * red) + (0.587 * green) + (0.114 * blue))
i = int((0.596 * red) - (0.275 * green) - (0.321 * blue))
q = int((0.212 * red) - (0.528 * green) + (0.311 * blue))
return (y, i, q)
def constrain(n):
if n < 0:
return 0
elif n > 255:
return 255
else:
return n
def yiq2Rgb(y, i, q):
r = int(y + (0.956 * i) + (0.620 * q))
g = int(y - (0.272 * i) - (0.647 * q))
b = int(y - (1.108 * i) + (1.705 * q))
return (constrain(r), constrain(g), constrain(b))
def rgb2Hex(red, green, blue):
return "#{:02X}{:02X}{:02X}".format(red, green, blue)
def printPalette(change, y, i, q):
(r, g, b) = yiq2Rgb(y, i, q)
print "{}% YIQ: ( {} {} {} ) => RGB: ( {} {} {} ) | {}".format(change, y, i, q, r, g, b, rgb2Hex(r, g, b))
def main(args):
r = int(args[1])
g = int(args[2])
b = int(args[3])
(y, i, q) = rgb2Yiq(r, g, b)
(r2,g2,b2) = yiq2Rgb(y, i, q)
print "RGB: ( {} {} {} ) => YIQ: ( {} {} {} ) => RGB: ( {} {} {} )".format(r, g, b, y, i, q, r2, g2, b2)
printPalette(27, int(0.27 * 255), i, q)
printPalette(33, int(0.33 * 255), i, q)
printPalette(45, int(0.45 * 255), i, q)
printPalette(69, int(0.69 * 255), i, q)
printPalette(82, int(0.82 * 255), i, q)
if __name__ == '__main__':
if len(sys.argv) < 4:
print "usage: ", sys.argv[0], "RED BLUE GREEN"
print " RED, BLUE and GREEN are integers"
else:
main(sys.argv)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.