Search code examples
pythoncolors

How can I proportionally mix colors in Python?


There are lots of questions out there about mixing colors, but mine is about mixing colors proportionally. I imagine it like mixing paint: one liter of white plus a half-liter of blue should produce a very light blue.

So given a dictionary of color: proportion like {"white": 1.0, "blue": 0.5, "black": 0.05}, I want to be able to mix the colors proportionally. Is there a way to do that in Python? I know I can get hex codes from color words easily, but then I'm unsure about how to combine values from those hex codes to mix colors just a little bit.


Solution

  • I don't actually know how to "get hex codes from color words easily", but the rest of the problem is straightforward. I'll just assume you already have the hex value. Extract the red, green blue components from the hex value, multiply by the proportion, sum them together, divide by the sum of the weights.

    def combine_hex_values(d):
      d_items = sorted(d.items())
      tot_weight = sum(d.values())
      red = int(sum([int(k[:2], 16)*v for k, v in d_items])/tot_weight)
      green = int(sum([int(k[2:4], 16)*v for k, v in d_items])/tot_weight)
      blue = int(sum([int(k[4:6], 16)*v for k, v in d_items])/tot_weight)
      zpad = lambda x: x if len(x)==2 else '0' + x
      return zpad(hex(red)[2:]) + zpad(hex(green)[2:]) + zpad(hex(blue)[2:])
    
    >>> combine_hex_values({"ffffff": 1.0, "0000ff": 0.5, "000000": 0.05})
    'a4a4f6'
    >>> combine_hex_values({"ffffff": 1.0, "0000ff": 0.5, "000000": 0.5})
    '7f7fbf'
    >>> combine_hex_values({"ffffff": 0.05, "0000ff": 1.0, "000000": 0.05})
    '0b0bf3'