Logo

Programming-Idioms

History of Idiom 154 > diff from v25 to v26

Edit summary for version 26 by bukzor:
New Python implementation by user [bukzor]

Version 25

2017-10-28, 12:06:58

Version 26

2018-04-14, 05:28:36

Idiom #154 Halfway between two hex color codes

Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.

Illustration

Idiom #154 Halfway between two hex color codes

Find color c, the average between colors c1, c2.

c, c1, c2 are strings of hex color codes: 7 chars, beginning with a number sign # .
Assume linear computations, ignore gamma corrections.

Illustration
Extra Keywords
hexa hexadecimal css avg mean radix base
Extra Keywords
hexa hexadecimal css avg mean radix base
Imports
import numpy
Code
class RGB(numpy.ndarray):
  @classmethod
  def from_str(cls, rgbstr):
    return numpy.array([
      int(rgbstr[i:i+2], 16)
      for i in range(1, len(rgbstr), 2)
    ]).view(cls)
 
  def __str__(self):
    self = self.astype(numpy.uint8)
    return '#' + ''.join(format(n, 'x') for n in self)
 
c1 = RGB.from_str('#a1b1c1')
print(c1)
c2 = RGB.from_str('#1A1B1C')
print(c2)

print((c1 + c2) / 2)
Comments bubble
numpy is standard for array numerics, and maps nicely to this problem.