"""Color vector library containing HSV and RGB.""" from __future__ import division, unicode_literals import colorsys import math class Vector(object): __slots__ = ('x', 'y', 'z') """3-dimensional vector class.""" def __init__(self, x=0, y=0, z=0): """Create a vector from its components.""" self.x = x self.y = y self.z = z def __add__(self, other): """Add two vectors.""" return self.__class__(self.x + other.x, self.y + other.y, self.z + other.z) def __sub__(self, other): """Subtract two vectors.""" return self.__class__(self.x - other.x, self.y - other.y, self.z - other.z) def __mul__(self, scalar): """Multiply a vector by a constant.""" return self.__class__(self.x * scalar, self.y * scalar, self.z * scalar) def __rmul__(self, scalar): """Multiply a constant by a vector.""" return self * scalar def __abs__(self): """Return the 2-norm of the vector.""" return math.sqrt(self.x * self.x + self.y * self.y + self.z * self.z) def __truediv__(self, scalar): """Return self * 1 / scalar.""" return self * (1 / scalar) def __eq__(self, other): return self.x == other.x and self.y == other.y and self.z == other.z def unit(self): return self / abs(self) def rot2d(self, theta): costheta = math.cos(theta) sintheta = math.sin(theta) new_x = self.x * costheta - self.y * sintheta new_y = self.x * sintheta + self.y * costheta return self.__class__(new_x, new_y) @property def components(self): return (self.x, self.y, self.z) 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.x, self.y, self.z)) def h(self): """Return hue.""" return self.x def s(self): """Return saturation.""" return self.y def v(self): """Return value.""" return self.z 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.x, self.y, self.z)) def r(self): """Return red value.""" return self.x def g(self): """Return green value.""" return self.y def b(self): """Return blue value.""" return self.z 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)