Logo

Programming-Idioms

History of Idiom 154 > diff from v26 to v27

Edit summary for version 27 by bukzor:
[Python] improved commentary

Version 26

2018-04-14, 05:28:36

Version 27

2018-04-14, 16:12:35

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
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)
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.
Comments bubble
numpy is standard for array numerics, and works nicely for this problem. We can represent a RGB value as a special numpy array.