diff -r 26c8c43dd774 Lib/colorsys.py --- a/Lib/colorsys.py Fri Mar 16 22:51:00 2012 -0400 +++ b/Lib/colorsys.py Fri Mar 16 21:10:01 2012 -0700 @@ -33,17 +33,26 @@ # 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 provide results which are +# compatible with similar functions in Matlab. +# +# Ref: +# http://www.mathworks.com/help/toolbox/images/ref/ntsc2rgb.html +# http://www.mathworks.com/help/toolbox/images/ref/rgb2ntsc.html 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 + y = 0.299*r + 0.587*g + 0.114*b + i = 0.596*r - 0.274*g - 0.322*b + q = 0.211*r - 0.523*g + 0.312*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.956*i + 0.621*q + g = y - 0.272*i - 0.647*q + b = y - 1.106*i + 1.703*q + if r < 0.0: r = 0.0 if g < 0.0: diff -r 26c8c43dd774 Lib/test/test_colorsys.py --- a/Lib/test/test_colorsys.py Fri Mar 16 22:51:00 2012 -0400 +++ b/Lib/test/test_colorsys.py Fri Mar 16 21:10:01 2012 -0700 @@ -8,12 +8,43 @@ class ColorsysTest(unittest.TestCase): - def assertTripleEqual(self, tr1, tr2): + def assertTripleEqual(self, tr1, tr2, places=7): self.assertEqual(len(tr1), 3) self.assertEqual(len(tr2), 3) - self.assertAlmostEqual(tr1[0], tr2[0]) - self.assertAlmostEqual(tr1[1], tr2[1]) - self.assertAlmostEqual(tr1[2], tr2[2]) + self.assertAlmostEqual(tr1[0], tr2[0], places) + self.assertAlmostEqual(tr1[1], tr2[1], places) + self.assertAlmostEqual(tr1[2], tr2[2], places) + + def test_rgb_to_yiq(self): + self.assertTripleEqual((0.0, 0.0, 0.0), + colorsys.rgb_to_yiq(0.0, 0.0, 0.0)) + self.assertTripleEqual((0.0747, 0.1490, 0.0529), + colorsys.rgb_to_yiq(0.25, 0.0, 0.0), 3) + self.assertTripleEqual((0.1468, -0.0686, -0.1307), + colorsys.rgb_to_yiq(0.0, 0.25, 0.0), 3) + self.assertTripleEqual((0.0285, -0.0804, 0.0779), + colorsys.rgb_to_yiq(0.0, 0.0, 0.25), 3) + + def test_yiq_to_rgb(self): + self.assertTripleEqual((0.0, 0.0, 0.0), + colorsys.yiq_to_rgb(0.0, 0.0, 0.0)) + self.assertTripleEqual((0.25, 0.0, 0.0), + colorsys.yiq_to_rgb(0.0747, 0.1490, 0.0529), 3) + self.assertTripleEqual((0.0, 0.25, 0.0), + colorsys.yiq_to_rgb(0.1468, -0.0686, -0.1307), 3) + self.assertTripleEqual((0.0, 0.0, 0.25), + colorsys.yiq_to_rgb(0.0285, -0.0804, 0.0779), 3) + + 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)), + 2 + ) def test_hsv_roundtrip(self): for r in frange(0.0, 1.0, 0.2):