summaryrefslogtreecommitdiffstats
path: root/color.py
blob: 84ece9d53a092c308b614e6a8d4180718bf00093 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
"""Color vector library containing HSV and RGB."""
from __future__ import division, unicode_literals
import colorsys
import math

class Vector(object):
    """N-dimensional vector class."""
    def __init__(self, *components):
        """Create a vector from its components."""
        self.components = components

    def __add__(self, other):
        """Add two vectors."""
        return self.__class__(
            *map(lambda (x, y): x + y, zip(self.components, other.components))
        )

    def __sub__(self, other):
        """Subtract two vectors."""
        return self.__class__(
            *map(lambda (x, y): x - y, zip(self.components, other.components))
        )

    def __mul__(self, other):
        """Multiply a vector by a constant."""
        return self.__class__(*map(lambda x: x * other, self.components))

    def __rmul__(self, other):
        """Multiply a constant by a vector."""
        return self * other

    def __abs__(self):
        """Return the 2-norm of the vector."""
        return math.sqrt(sum(map(lambda x: x * x, self.components)))

    def __truediv__(self, scalar):
        """Return self * 1 / scalar."""
        return self * (1 / scalar)


class HSV(Vector):
    """HSV 3-vector."""
    def __init__(self, hue, saturation, value):
        """Initialize with hue, saturation, and value."""
        super(HSV, self).__init__(hue, saturation, value)

    def to_RGB(self):
        """Convert to an RGB vector."""
        return RGB(*colorsys.hsv_to_rgb(*self.components))

    def h(self):
        """Return hue."""
        return self.components[0]

    def s(self):
        """Return saturation."""
        return self.components[1]

    def v(self):
        """Return value."""
        return self.components[2]


class RGB(Vector):
    """RGB 3-vector."""
    def __init__(self, r, g, b):
        """Initialize with red green and blue."""
        super(RGB, self).__init__(r, g, b)

    def to_HSV(self):
        """Convert to HSV vector."""
        return HSV(*colorsys.rgb_to_hsv(*self.components))

    def r(self):
        """Return red value."""
        return self.components[0]

    def g(self):
        """Return green value."""
        return self.components[1]

    def b(self):
        """Return blue value."""
        return self.components[2]

red = RGB(1, 0, 0)
green = RGB(0, 1, 0)
blue = RGB(0, 0, 1)
cyan = RGB(0, 1, 1)
magenta = RGB(1, 0, 1)
yellow = RGB(1, 1, 0)
white = RGB(1, 1, 1)
black = RGB(0, 0, 0)