summaryrefslogtreecommitdiffstats
path: root/color.py
diff options
context:
space:
mode:
Diffstat (limited to 'color.py')
-rw-r--r--color.py84
1 files changed, 84 insertions, 0 deletions
diff --git a/color.py b/color.py
new file mode 100644
index 0000000..c8cb3cb
--- /dev/null
+++ b/color.py
@@ -0,0 +1,84 @@
+"""Color vector library containing HSV and RGB."""
+from __future__ import division
+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 Vector(
+ *map(lambda x, y: x + y, zip(self.components, other.components))
+ )
+
+ def __sub__(self, other):
+ """Subtract two vectors."""
+ return Vector(
+ *map(lambda x, y: x - y, zip(self.components, other.components))
+ )
+
+ def __mul__(self, other):
+ """Multiply a vector by a constant."""
+ return Vector(*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 __div__(self, scalar):
+ """Return self * 1 / scalar."""
+ return self * (1 / scalar)
+
+
+def HSV(Vector):
+ """HSV 3-vector."""
+ def __init__(self, hue, saturation, value):
+ """Initialize with hue, saturation, and value."""
+ super().__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]
+
+
+def RGB(Vector):
+ """RGB 3-vector."""
+ def __init__(self, r, g, b):
+ """Initialize with red green and blue."""
+ super().__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]