Compute the Convex Combination of Two Colors

Description

This function can be used to compute the result of color mixing, assuming additive mixing (e.g., as appropriate for RGB and XYZ).

Usage

mixcolor(alpha, color1, color2, where)

Arguments

alphafloat
The mixed color is obtained by combining an amount 1 - alpha of color1 with an amount alpha of color2.
color1
an object that can be converted into a palette.
color2
a second object that can be converted into a palette. Must have the same number of colors as the argument on color1.
wherestr
The color space where the mixing is to take place, either "RGB" or "CIEXYZ".

Examples

from colorspace.colorlib import RGB
from colorspace.colorlib import hexcols
from colorspace import *
# Mixing two colors defined in the RGB space
# via colorspace.colorlib.RGB. Mixing half-half
# in the RGB color space (M1) and in the HCL space (M2).
RGB_1  = RGB(R = 1, G = 0, B = 0)
RGB_2  = RGB(R = 0, G = 1, B = 0)
RGB_M1 = mixcolor(0.5, RGB_1, RGB_2, "sRGB")
RGB_M1
sRGB color object (1 colors)
            R       G       B
  1:     0.50    0.50    0.00
# Mixing via XYZ color space
RGB_M2 = mixcolor(0.5, RGB_1, RGB_2, "CIEXYZ")
RGB_M2
CIEXYZ color object (1 colors)
            X       Y       Z
  1:    38.50   46.39    6.93
# Mixing two lists of hex-colors of length 5.
#  Mixing takes place once in the RGB color space (M1)
#  and once in the HCL color space (M2)
HEX_1  = diverging_hcl()(5)
HEX_2  = diverging_hcl(rev = True)(5)
HEX_M1 = mixcolor(0.2, HEX_1, HEX_2, "sRGB")
HEX_M1
sRGB color object (5 colors)
            R       G       B
  1:     0.12    0.20    0.56
         0.66    0.64    0.76
         0.89    0.89    0.89
         0.76    0.62    0.67
         0.45    0.07    0.31
# Mixing via XYZ color space
HEX_M2 = mixcolor(0.8, HEX_1, HEX_2, "CIEXYZ")
HEX_M2
CIEXYZ color object (5 colors)
            X       Y       Z
  1:    11.33    6.22   11.03
        42.11   39.02   44.33
        72.28   76.05   82.80
        39.59   39.02   56.17
         9.28    6.27   30.02
swatchplot([HEX_1, HEX_2, HEX_M1, HEX_M2],
           show_names = False, figsize = (5.5, 1));

# Mixing objects of different length and type
#  Coordinates of the shorter object (RGB_1) will be recycled
#  to the same number of colors as in the longer object (HEX_2)
RES_1 = mixcolor(0.2, RGB_1, HEX_2, "sRGB")
RES_1.colors()
['#E8010C', '#F41F21', '#F92D2D', '#EC2128', '#CC0D21']
RES_2 = mixcolor(0.8, RGB_1, HEX_2, "sRGB")
RES_2.colors()
['#A5052F', '#D57D83', '#E8B5B5', '#B485A0', '#353284']
swatchplot([RGB_1, RES_2, HEX_2, RES_1, RES_2],
           show_names = False, figsize = (5.5, 2));

Raises

  • TypeError: In case alpha is not float or int.
  • ValueError: If alpha is not larger than 0.0 and smaller than 1.0.
  • TypeError: If where is not a str.
  • ValueError: If where is not among the allowed color spaces used for adaptive mixing.
  • Exception: If color1 or color2 cannot be converted into a palette object.