diff -r 2ec323dadca2 Lib/colorsys.py --- a/Lib/colorsys.py Sun Aug 04 15:48:29 2013 -0400 +++ b/Lib/colorsys.py Mon Aug 05 01:16:51 2013 +0300 @@ -33,17 +33,21 @@ # YIQ: used by composite video signals (linear combinations of RGB) # Y: perceived grey level (0.0 == black, 1.0 == white) # I, Q: color components +# +# There are a great many versions of the constants used in these formulae. +# The ones in this library uses constants from the FCC version of NTSC. def rgb_to_yiq(r, g, b): y = 0.30*r + 0.59*g + 0.11*b - i = 0.60*r - 0.28*g - 0.32*b - q = 0.21*r - 0.52*g + 0.31*b + i = 0.5990*r - 0.2773*g - 0.3217*b + q = 0.2130*r - 0.5251*g + 0.3121*b return (y, i, q) def yiq_to_rgb(y, i, q): - r = y + 0.948262*i + 0.624013*q - g = y - 0.276066*i - 0.639810*q - b = y - 1.105450*i + 1.729860*q + r = y + 0.94688221709007*i + 0.62355658198614*q + g = y - 0.27478764629898*i - 0.63569107918738*q + b = y - 1.108545034642032*i + 1.709006928406467*q + if r < 0.0: r = 0.0 if g < 0.0: diff -r 2ec323dadca2 Lib/test/test_colorsys.py --- a/Lib/test/test_colorsys.py Sun Aug 04 15:48:29 2013 -0400 +++ b/Lib/test/test_colorsys.py Mon Aug 05 01:16:51 2013 +0300 @@ -69,6 +69,33 @@ self.assertTripleEqual(hls, colorsys.rgb_to_hls(*rgb)) self.assertTripleEqual(rgb, colorsys.hls_to_rgb(*hls)) + def test_yiq_roundtrip(self): + for r in frange(0.0, 1.0, 0.2): + for g in frange(0.0, 1.0, 0.2): + for b in frange(0.0, 1.0, 0.2): + rgb = (r, g, b) + self.assertTripleEqual( + rgb, + colorsys.yiq_to_rgb(*colorsys.rgb_to_yiq(*rgb)) + ) + + def test_yiq_values(self): + values = [ + # rgb, yiq + ((0.0, 0.0, 0.0), (0.0, 0.0, 0.0)), # black + ((0.0, 0.0, 1.0), (0.11, -0.3217, 0.3121)), # blue + ((0.0, 1.0, 0.0), (0.59, -0.2773, -0.5251)), # green + ((0.0, 1.0, 1.0), (0.7, -0.599, -0.213)), # cyan + ((1.0, 0.0, 0.0), (0.3, 0.599, 0.213)), # red + ((1.0, 0.0, 1.0), (0.41, 0.2773, 0.5251)), # purple + ((1.0, 1.0, 0.0), (0.89, 0.3217, -0.3121)), # yellow + ((1.0, 1.0, 1.0), (1.0, 0.0, 0.0)), # white + ((0.5, 0.5, 0.5), (0.5, 0.0, 0.0)), # grey + ] + for (rgb, yiq) in values: + self.assertTripleEqual(yiq, colorsys.rgb_to_yiq(*rgb)) + self.assertTripleEqual(rgb, colorsys.yiq_to_rgb(*yiq)) + def test_main(): test.support.run_unittest(ColorsysTest)