예제 #1
0
def colour_distance(c1, c2):
    stringkeyA = c1 + "," + c2
    stringkeyB = c2 + "," + c1
    if stringkeyA in colour_distance_dict:
        return colour_distance_dict[stringkeyA]
    elif stringkeyB in colour_distance_dict:
        return colour_distance_dict[stringkeyB]

    else:
        color1 = sRGBColor.new_from_rgb_hex(c1)
        color2 = sRGBColor.new_from_rgb_hex(c2)
        lab_c1 = convert_color(color1, LabColor)
        lab_c2 = convert_color(color2, LabColor)
        delta_e = deltaE2000(lab_c1, lab_c2)
        colour_distance_dict[stringkeyA] = delta_e
        return colour_distance_dict[stringkeyA]
def closest_named_colour(rgb):
    """Get closest named colour according to XKCD's colour naming survey
    http://xkcd.com/color/rgb/

    Exception: "black" and "white" are only returned when the input colour is
    true black or true white.

    :param rgb: Hex value (3 or 6 digits, with or without leading `#`) or triple
    of rgb colour (0-255).
    :return: name, named_rgb, input_rgb
    """

    _init()

    if isinstance(rgb, basestring):
        srgb = sRGBColor.new_from_rgb_hex(rgb)
    else:
        srgb = sRGBColor(rgb[0], rgb[1], rgb[2], True)
    lab = convert_color(srgb, LabColor)

    # If true black or white, use the reserved values
    upscaled = srgb.get_upscaled_value_tuple()
    if upscaled[0] == 0 and upscaled[1] == 0 and upscaled[2] == 0:
        return "black", '#000000', srgb.get_rgb_hex()
    if upscaled[0] == 255 and upscaled[1] == 255 and upscaled[2] == 255:
        return "white", '#ffffff', srgb.get_rgb_hex()

    # Find closest entry
    arr = [delta_e_cie2000(lab, c["lab"]) for c in colours]
    idx = np.where(arr == np.min(arr))[0][0]
    closest = colours[idx]
    return closest["name"], closest["srgb"].get_rgb_hex(), srgb.get_rgb_hex()
예제 #3
0
def named_colorset(colorfile):
    """From a file, generate a set of named color objects"""
    colorset = json.load(open(colorfile))
    for color in colorset['colors']:
        cobj = convert_color(sRGBColor.new_from_rgb_hex(color['hex']), LabColor)
        color['obj'] = cobj
    return colorset['colors']
예제 #4
0
파일: device.py 프로젝트: drewp/light9
 def cmyAttr(attr):
     rgb = sRGBColor.new_from_rgb_hex(deviceAttrSettings.get(attr, '#000000'))
     out = colormath.color_conversions.convert_color(rgb, CMYColor)
     return (
         _8bit(out.cmy_c),
         _8bit(out.cmy_m),
         _8bit(out.cmy_y))
def _init():
    global _initialized

    if _initialized:
        return

    global colours

    colours = []
    filename = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                            'rgb.txt')
    with open(filename, 'rb') as csvfile:
        spamreader = csv.reader(csvfile, delimiter='\t')
        for row in spamreader:
            if row[0] == '#':
                continue
            try:
                name = row[0]

                # Reserve "black" and "white" for true black and white
                if name == "black" or name == "white":
                    continue

                srgb = sRGBColor.new_from_rgb_hex(row[1])
                colours.append({
                    "name": name,
                    "hex": row[1],
                    "srgb": srgb,
                    "lab": convert_color(srgb, LabColor),
                })
            except:
                pass

    _initialized = True
def parse_bsdf_albedo(bsdf):
    """ Return (diffuse RGB albedo, specular RGB albedo) for a BRDF """
    from colormath.color_objects import sRGBColor as RGBColor

    rgb = RGBColor.new_from_rgb_hex(bsdf['color'])
    v = max(rgb.rgb_r, rgb.rgb_b, rgb.rgb_g) / 255.0
    # approximate cielab_inverse_f.
    # we have V instead of L, so the same inverse formula doesn't
    # apply anyway.
    finv = v ** 3
    if bsdf['metallic']:
        rho_s = finv
        s = rho_s / (v * 255.0) if v > 0 else 0
        return (
            (0, 0, 0),
            (s * rgb.rgb_r, s * rgb.rgb_g, s * rgb.rgb_b),
        )
    else:
        rho_d = finv
        t = bsdf['contrast'] + (rho_d * 0.5) ** (1.0 / 3.0)
        rho_s = t ** 3 - rho_d * 0.5
        rho_t = rho_s + rho_d
        if rho_t > 1:
            rho_s /= rho_t
            rho_d /= rho_t
        s = rho_d / (v * 255.0) if v > 0 else 0
        return (
            (s * rgb.rgb_r, s * rgb.rgb_g, s * rgb.rgb_b),
            (rho_s, rho_s, rho_s)
        )
예제 #7
0
def get_greyscale_equivalent(hex_str):
  rgb_color = sRGBColor.new_from_rgb_hex(hex_str)
  lab_color = convert_color(rgb_color, LabColor)
  lab_color.lab_a = 0
  lab_color.lab_b = 0
  grey_rgb_color = convert_color(lab_color, sRGBColor)
  return grey_rgb_color.get_rgb_hex()
예제 #8
0
def get_alternative_hues(hex_str, num_hues=10):
  rgb_color = sRGBColor.new_from_rgb_hex(hex_str)
  lab_color = convert_color(rgb_color, LabColor)
  lab_color.lab_a = 0
  lab_color.lab_b = 0
  grey_rgb_color = convert_color(lab_color, sRGBColor)
  return grey_rgb_color.get_rgb_hex()
예제 #9
0
 def update_closest_swatches(self, l):
     own_color = convert_color(sRGBColor.new_from_rgb_hex(self.hex_color),
                               LabColor)
     l = l.exclude(pk=self.pk)
     self.closest_1 = self._get_closest_color_swatch(l, own_color)
     l = l.exclude(pk=self.closest_1.pk)
     self.closest_2 = self._get_closest_color_swatch(l, own_color)
def parse_bsdf_albedo(bsdf):
    """ Return (diffuse RGB albedo, specular RGB albedo) for a BRDF """
    from colormath.color_objects import sRGBColor as RGBColor

    rgb = RGBColor.new_from_rgb_hex(bsdf['color'])
    v = max(rgb.rgb_r, rgb.rgb_b, rgb.rgb_g) / 255.0
    # approximate cielab_inverse_f.
    # we have V instead of L, so the same inverse formula doesn't
    # apply anyway.
    finv = v**3
    if bsdf['metallic']:
        rho_s = finv
        s = rho_s / (v * 255.0) if v > 0 else 0
        return (
            (0, 0, 0),
            (s * rgb.rgb_r, s * rgb.rgb_g, s * rgb.rgb_b),
        )
    else:
        rho_d = finv
        t = bsdf['contrast'] + (rho_d * 0.5)**(1.0 / 3.0)
        rho_s = t**3 - rho_d * 0.5
        rho_t = rho_s + rho_d
        if rho_t > 1:
            rho_s /= rho_t
            rho_d /= rho_t
        s = rho_d / (v * 255.0) if v > 0 else 0
        return ((s * rgb.rgb_r, s * rgb.rgb_g, s * rgb.rgb_b), (rho_s, rho_s,
                                                                rho_s))
def print_closest_color(colors, target_color):
    target_rgb = sRGBColor.new_from_rgb_hex(target_color)
    min_diff = 255 * 3
    closest_hex_str = None
    stats = None
    for hue_index, shades in enumerate(colors):
        for shade_index, color in enumerate(shades):
            hex_str, clip_amount = color
            if not clip_amount:
                color_rgb = sRGBColor.new_from_rgb_hex(hex_str)
                r_diff = abs(target_rgb.rgb_r - color_rgb.rgb_r)
                g_diff = abs(target_rgb.rgb_g - color_rgb.rgb_g)
                b_diff = abs(target_rgb.rgb_b - color_rgb.rgb_b)
                diff = r_diff + g_diff + b_diff
                if diff < min_diff:
                    min_diff = diff
                    closest_hex_str = hex_str
                    stats = (diff, hue_index, shade_index)
    print('Closest color to:', target_color, closest_hex_str,
          ' - diff, hue, shade:', stats)
예제 #12
0
def fmtHex(str):
    black = convert_color(sRGBColor(0, 0, 0), LabColor)
    white = convert_color(sRGBColor(1, 1, 1), LabColor)
    color = sRGBColor.new_from_rgb_hex(str)
    lcolor = convert_color(color, LabColor)
    if delta_e_cie2000(lcolor, white) > delta_e_cie2000(lcolor, black):
        return "\033[48;2;{};{};{};38;2;255;255;255m{}\033[0m".format(
            int(255 * color.rgb_r), int(255 * color.rgb_g),
            int(255 * color.rgb_b), color.get_rgb_hex())
    else:
        return "\033[48;2;{};{};{};38;2;0;0;0m{}\033[0m".format(
            int(255 * color.rgb_r), int(255 * color.rgb_g),
            int(255 * color.rgb_b), color.get_rgb_hex())
예제 #13
0
def loadScheme(filePath):
    schemeRaw = {}
    with open(filePath) as file:
        schemeRaw = json.load(file)
    scheme = {}
    for key, val in schemeRaw.items():
        scheme[key] = [sRGBColor.new_from_rgb_hex(x) for x in val]
    global XTERM
    with open('xterm.json') as file:
        schemeRaw = json.load(file)
    for entry in schemeRaw:
        XTERM.append({
            'id':
            entry['colorId'],
            'color':
            convert_color(sRGBColor.new_from_rgb_hex(entry['hexString']),
                          LabColor),
            'name':
            entry['name']
        })

    return scheme
def draw_hues_for_color(base_color_hex_str, num_hues=10):
    """Draws a palette of colors that only vary in hue.

  The base color's hue is used as one of the hues and the other hues
  will evenly divide the 360 degree space. All colors will use the
  lightness and chroma values of the base color.
  """
    rgb_color = sRGBColor.new_from_rgb_hex(base_color_hex_str)
    lab_color = convert_color(rgb_color, LabColor)
    l, a, b = lab_color.get_value_tuple()
    c, h = ab_to_ch(a, b)
    hues = []
    for cur_h in np.linspace(h, h + math.tau, num_hues, endpoint=False):
        hues.append(lch_to_hex_str_and_clip_amount(l, c, cur_h))
    draw_svg([hues])
def replace_impose(strColorHex, value, impose="H"):
    color = RGBColor.new_from_rgb_hex(strColorHex)
    color = convert_color(color, HSVColor)
    # we fixe the value depending of the parameter impose
    if impose.lower() == "h":
        color.hsv_h = value
    elif impose.lower() == "s":
        color.hsv_s = value
    elif impose.lower() == "v":
        color.hsv_v = value
    else:
        print("impose = ", impose)
        print("Should be H, S or V")
    color = convert_color(color, RGBColor)
    return color.get_rgb_hex()
예제 #16
0
    def set_from_hex(self, hex_str):
        hex_str = hex_str.strip()

        if hex_str.startswith('#'):
            hex_str = hex_str[1:]

        if len(hex_str) == 3:
            hex_str = '{r}{r}{g}{g}{b}{b}'.format(r=hex_str[0],
                                                  g=hex_str[1],
                                                  b=hex_str[2])

        if len(hex_str) != 6:
            return

        color = sRGBColor.new_from_rgb_hex(hex_str)
        self._set_rgb_color(color)
예제 #17
0
    async def color(self, ctx):
        # Important so that we aren't duplicating upper/lowercase versions of the role
        ctx.message.content = ctx.message.content.upper().split()[1]

        # Check validness of color code
        # TODO: Maybe add support for 3 long hexcodes that would just be expanded
        if not re.search(r'^(?:[0-9a-fA-F]){6}$', ctx.message.content):
            await ctx.channel.send(
                'Invalid color\nExample Usage: &color FABCDE')
            return

        # Check for similarity to background colors so names are visible still
        test_color = convert_color(
            sRGBColor.new_from_rgb_hex(ctx.message.content), LabColor)

        dark_delta_e = delta_e_cie2000(test_color, DISCORD_DARK_COLOR)

        light_delta_e = delta_e_cie2000(test_color, DISCORD_LIGHT_COLOR)

        if dark_delta_e <= 13.0:
            await ctx.channel.send(
                'Try another color.\nToo similar to Discord\'s dark background.'
            )
            return

        if light_delta_e <= 13.0:
            await ctx.channel.send(
                'Try another color.\nToo similar to Discord\'s light background.'
            )
            return

        role = discord.utils.get(ctx.guild.roles, name=ctx.message.content)
        # If color exists just assign it to the user
        if role:
            print(f"Added existing role to user {ctx.author}")
            await ctx.author.add_roles(role,
                                       reason="Adding existing role to user")
        else:
            print(f"Creating role for user {ctx.author}")
            new_role = await ctx.guild.create_role(
                name=ctx.message.content,
                color=discord.Colour(int(ctx.message.content, 16)))
            await ctx.author.add_roles(new_role,
                                       reason="Created new role for user")

        await ctx.channel.send('Added role')
예제 #18
0
def change_lightness(base_color_rgb_hex, lightness_change):
    base_color_lab = convert_color(
        sRGBColor.new_from_rgb_hex(base_color_rgb_hex), LabColor)
    new_color_lab = LabColor(
        base_color_lab.lab_l +
        lightness_change,  # This value might be out of gammut and therefor invalid
        base_color_lab.lab_a,
        base_color_lab.lab_b,
        base_color_lab.observer,
        base_color_lab.illuminant)
    new_color_rgb = convert_color(
        new_color_lab,
        sRGBColor)  # This value might be out of gammut and therefor invalid
    # use the "clamped" values which means they are within the gammut and therefor valid
    new_color_rgb_clamped = sRGBColor(new_color_rgb.clamped_rgb_r,
                                      new_color_rgb.clamped_rgb_g,
                                      new_color_rgb.clamped_rgb_b)
    return new_color_rgb_clamped.get_rgb_hex()
def get_palette_colors(base_color, num_l, num_c, num_h,
                       chroma_index_of_base_color):
    rgb_color = sRGBColor.new_from_rgb_hex(BASE_COLOR)
    lab_color = convert_color(rgb_color, LabColor)
    l, a, b = lab_color.get_value_tuple()
    c, h = ab_to_ch(a, b)

    print('Base color:', base_color)
    print('L:', l)
    print('C:', c)
    print('H:', h)

    start_l = 0
    end_l = 100
    start_c = 0
    end_c = c * (num_c - 1) / chroma_index_of_base_color
    start_h = h

    return get_chromas(start_l, end_l, num_l, start_c, end_c, num_c, start_h,
                       num_h)
예제 #20
0
    def adjust_hex(self, orig_hex):
        """Given an original hex value, return the adjusted value

        If the adjusted value would have r, g, or b exceeding 1 (i.e., 255), raises an
        exception.
        """

        orig_color = sRGBColor.new_from_rgb_hex(orig_hex)

        orig_rgb = np.array(orig_color.get_value_tuple())
        new_rgb = orig_rgb * self._adjust

        max_rgb = np.max(new_rgb)
        if max_rgb > 1:
            raise RuntimeError("Adjusted rgb has a value exceeding 1")

        new_color = sRGBColor(rgb_r = new_rgb[0],
                              rgb_g = new_rgb[1],
                              rgb_b = new_rgb[2])

        return new_color.get_rgb_hex()
예제 #21
0
    def _get_closest_color_swatch(self, library: QuerySet,
                                  color_to_match: LabColor):
        distance_dict = dict()

        for item in library:
            possible_color = convert_color(
                sRGBColor.new_from_rgb_hex(item.hex_color), LabColor)

            distance = delta_e_cmc(color_to_match, possible_color)

            distance_dict.update({item: distance})

        distance_dict = {
            i: distance_dict[i]
            for i in distance_dict if distance_dict[i] is not None
        }

        sorted_distance_list = sorted(distance_dict.items(),
                                      key=lambda kv: kv[1])

        try:
            return sorted_distance_list[0][0]
        except IndexError:
            return None
예제 #22
0
	def do_POST(self):
		self._set_headers()
		data_string = self.rfile.read(int(self.headers['Content-Length']))

		self.send_response(200)
		self.end_headers()

		data = parse_qs(data_string)
		if data[b'group'][0] == b'static':
			# we got a static color
			self.set_accepting_dynamic_color(False)
			# convert e.g. "#0000ff" to "0000FF" for the RGB hex parser
			color_str = data[b'static_color'][0][1:].upper()
			color_obj = sRGBColor.new_from_rgb_hex(color_str)
			color_tuple = color_obj.get_upscaled_value_tuple()
			
			self.color_callback(True, color_tuple)
			print('setting static color to ', color_tuple)
		elif data[b'group'][0] == b'dynamic':
			print('setting color to dynamic')
			# ignore the static color, dynamic it is
			self.set_accepting_dynamic_color(True)
		else:
			print(data)
예제 #23
0
def rgb_to_lch(h):
    rgb = sRGBColor.new_from_rgb_hex(h)
    return convert_color(rgb, LCHabColor).get_value_tuple()
예제 #24
0
파일: map.py 프로젝트: smartnova/samples
spi2019 = pd.read_excel('../data/spi2019.xlsx',
                        sheet_name='2019')[['Country'] + SPI]
spi2019 = spi2019[spi2019['Country'] != 'World']

mean, std = spi2019.mean('rows'), spi2019.std('rows')
spi2019['Needs'], spi2019['Wellbeing'], spi2019['Opportunity'] = [
    ((spi2019[i] - mean[i]) / std[i] * 10 + 80).clip(50, 100) for i in SPI
]
print(spi2019)

from colormath.color_objects import ColorBase, sRGBColor as sRGB, LabColor as Lab
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000

# sRGB
sRGB.fromHex = lambda hex: sRGB.new_from_rgb_hex(hex)
sRGB.hex = lambda c: c.get_rgb_hex()
sRGB.clamp = lambda c: sRGB(
    *[c.clamped_rgb_r, c.clamped_rgb_g, c.clamped_rgb_b])
ColorBase.values = ColorBase.get_value_tuple

# 色変換
ColorBase.sRGB = lambda c: c if isinstance(c, sRGB) else convert_color(c, sRGB)
ColorBase.Lab = lambda c: c if isinstance(c, Lab) else convert_color(c, Lab)

# 色距離
ColorBase.delta = lambda c1, c2: delta_e_cie2000(c1.Lab(), c2.Lab())

labs = [
    np.array([50, 50 * np.cos(theta), 50 * np.sin(theta)])
    for theta in np.linspace(0, 2 * np.pi, num=4)[:-1]
예제 #25
0
#f9c547
#fef0cf
#8a638b
#3b3b3b""".split()
print("start!")
#flag="#fdeeb2 #9e4365 #291051 #ffd06c".split()

gamut = [
    convert_color(sRGBColor(*i), LabColor).get_value_tuple()
    for i in list(product([0, 1], repeat=3))
]

print("gamut'd")

labs = [
    convert_color(sRGBColor.new_from_rgb_hex(i), LabColor).get_value_tuple()
    for i in flag
]
l = []
a = []
b = []
for i in range(len(labs)):
    l.extend(np.linspace(labs[i - 1][0], labs[i][0], 256))
    a.extend(np.linspace(labs[i - 1][1], labs[i][1], 256))
    b.extend(np.linspace(labs[i - 1][2], labs[i][2], 256))

print("labbed")

height = 255

 def rgb_error(self):
     return delta_e_cie2000(convert_color(self.m_lch, LabColor),
                            convert_color(sRGBColor.new_from_rgb_hex(self.rgb()), LabColor))
예제 #27
0
def de(a, b):
    return delta_e_cie2000(
        convert_color(sRGBColor.new_from_rgb_hex(a), LabColor),
        convert_color(sRGBColor.new_from_rgb_hex(b), LabColor))
예제 #28
0
 def rgb_error(self):
     return delta_e_cie2000(
         convert_color(self.m_lch, LabColor),
         convert_color(sRGBColor.new_from_rgb_hex(self.rgb()), LabColor))
예제 #29
0
def home():
    form =ColorSearchForm(request.form)

    # Handle search
    if request.method == 'POST':
        if form.validate_on_submit():
            return redirect(url_for("public.home") + '?color={0}'.format(form.color.data.replace('#', '')))
        else:
            flash_errors(form)

    color_results = Color.query
    max_colors = app.config['MAX_COLORS']

    color = None
    colors = None

    colors_cie2000 = None
    colors_cie1976 = None
    colors_cie1994 = None
    colors_cmc = None

    colors_cie1976_elapsed = None
    colors_cie2000_elapsed = None

    colors_cie1976_db = None
    colors_cie2000_db = None

    colors_cie1976_db_elapsed = None
    colors_cie2000_db_elapsed = None

    is_show_createschema_msg = False
    is_show_createcolors_msg = False

    if not db.engine.dialect.has_table(db.engine.connect(), 'color'):
        form = None
        is_show_createschema_msg = True
    elif (not request.args.get('color', None)) and (not color_results.count()):
        form = None
        is_show_createcolors_msg = True
    elif request.args.get('color', None):
        color = '#{0}'.format(request.args.get('color'))

        from operator import itemgetter
        from colormath.color_conversions import convert_color
        from colormath.color_objects import sRGBColor, LabColor
        from colormath.color_diff import (delta_e_cie2000,
                                          delta_e_cie1976,
                                          delta_e_cie1994,
                                          delta_e_cmc)

        from colorsearchtest.queries import (delta_e_cie1976_query,
                                             delta_e_cie2000_query)

        c_rgb = sRGBColor.new_from_rgb_hex(color)
        c_lab = convert_color(c_rgb, LabColor)

        if app.config['IS_DELTA_E_COLORMATH_ENABLED']:
            start_time = timeit.default_timer()

            colors_cie2000_tmp = []

            for c in color_results.all():
                c2_lab = LabColor(lab_l=c.lab_l,
                                  lab_a=c.lab_a,
                                  lab_b=c.lab_b,
                                  illuminant='d65')

                colors_cie2000_tmp.append({
                    'hex': str(c),
                    'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))),
                    'delta_e_cie2000': delta_e_cie2000(c_lab,
                                                       c2_lab)})

            colors_cie2000 = sorted(colors_cie2000_tmp, key=itemgetter('delta_e_cie2000'))[:max_colors]

            colors_cie2000_elapsed = timeit.default_timer() - start_time

            start_time = timeit.default_timer()

            colors_cie1976_tmp = []

            for c in color_results.all():
                c2_lab = LabColor(lab_l=c.lab_l,
                                  lab_a=c.lab_a,
                                  lab_b=c.lab_b,
                                  illuminant='d65')

                colors_cie1976_tmp.append({
                    'hex': str(c),
                    'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))),
                    'delta_e_cie1976': delta_e_cie1976(c_lab,
                                                       c2_lab)})

            colors_cie1976 = sorted(colors_cie1976_tmp, key=itemgetter('delta_e_cie1976'))[:max_colors]

            colors_cie1976_elapsed = timeit.default_timer() - start_time

        colors = None

        if app.config['IS_DELTA_E_DBQUERY_ENABLED']:
            start_time = timeit.default_timer()

            color_results = delta_e_cie1976_query(
                lab_l=c_lab.lab_l,
                lab_a=c_lab.lab_a,
                lab_b=c_lab.lab_b,
                limit=max_colors)

            colors_cie1976_db = []
            for c in color_results:
                colors_cie1976_db.append({
                    'hex': '#{:02X}{:02X}{:02X}'.format(c[0], c[1], c[2]),
                    'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c[0], c[1], c[2])))),
                    'delta_e_cie1976_db': c[3]})

            colors_cie1976_db_elapsed = timeit.default_timer() - start_time

            start_time = timeit.default_timer()

            color_results = delta_e_cie2000_query(
                lab_l=c_lab.lab_l,
                lab_a=c_lab.lab_a,
                lab_b=c_lab.lab_b,
                limit=max_colors)

            colors_cie2000_db = []
            for c in color_results:
                colors_cie2000_db.append({
                    'hex': '#{:02X}{:02X}{:02X}'.format(c[0], c[1], c[2]),
                    'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c[0], c[1], c[2])))),
                    'delta_e_cie2000_db': c[3]})

            colors_cie2000_db_elapsed = timeit.default_timer() - start_time
    else:
        colors = [{
                'hex': str(c),
                'fore_color': ('#{:02X}{:02X}{:02X}'.format(*calc_fore_color((c.rgb_r, c.rgb_g, c.rgb_b)))),
                'delta_e_cie2000': None}
            for c in color_results
                .order_by(func.random())
                .limit(max_colors)
                .all()]

    return render_template("public/home.html",
                           form=form,
                           is_show_createschema_msg=is_show_createschema_msg,
                           is_show_createcolors_msg=is_show_createcolors_msg,
                           colors=colors,
                           colors_cie2000=colors_cie2000,
                           colors_cie1976=colors_cie1976,
                           colors_cie1994=colors_cie1994,
                           colors_cmc=colors_cmc,
                           colors_cie1976_elapsed=colors_cie1976_elapsed,
                           colors_cie2000_elapsed=colors_cie2000_elapsed,
                           colors_cie1976_db=colors_cie1976_db,
                           colors_cie2000_db=colors_cie2000_db,
                           colors_cie1976_db_elapsed=colors_cie1976_db_elapsed,
                           colors_cie2000_db_elapsed=colors_cie2000_db_elapsed,
                           color=color)
예제 #30
0
#!/usr/bin/env python

import argparse
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000
from colormath.color_objects import LabColor, sRGBColor

parser = argparse.ArgumentParser(
    description='Find the visually closest color from a set of colors')
parser.add_argument(
    'colors_file',
    type=argparse.FileType('r'),
    help='path to file containing hex colors separated by newline')
parser.add_argument('color', type=str, help='target color in hex format')
args = parser.parse_args()

hex_color = sRGBColor.new_from_rgb_hex(args.color)
target_color = convert_color(hex_color, LabColor)

colors = []
for line in args.colors_file.readlines():
    hex_color = sRGBColor.new_from_rgb_hex(line.rstrip())
    colors.append(convert_color(hex_color, LabColor))

deltas = list(map(lambda x: delta_e_cie2000(target_color, x), colors))
min_delta_index = deltas.index(min(deltas))

closest_rgb_color = convert_color(colors[min_delta_index], sRGBColor)
print(closest_rgb_color.get_rgb_hex())
예제 #31
0
 def from_hex(hex_str):
     """ Creates a color instance from hex rgb notation. """
     return Color(*sRGBColor.new_from_rgb_hex(hex_str).get_value_tuple())
예제 #32
0
    highlight = 60
    # Minimum Delta E between the highlight color and the background
    min_delta_background_highlight = 20
    # Minimum Delta E between all other colors and the background
    min_delta_background_color = 50
    # Luminance is adjusted this much each step until the required delta to the
    # background is achieved
    lum_adjust_highlight = -.001
    lum_adjust_color = -.001
    # Fixed colors, use for example:
    #   sRGBColor.new_from_rgb_hex('#000000')
    #   sRGBColor(128, 0, 255, is_upscaled=True)
    #   sRGBColor(.5, 0, 1)
    #   HSLColor(0, 0, .8)
    # Background
    background = sRGBColor.new_from_rgb_hex('#ffffff')
else:
    # Approximate hue of highlight color (e.g. background color for matches
    # when searching in a man page), can be 'None'
    highlight = 240
    # Minimum Delta E between the highlight color and the background
    min_delta_background_highlight = 20
    # Minimum Delta E between all other colors and the background
    min_delta_background_color = 50
    # Luminance is adjusted this much each step until the required delta to the
    # background is achieved
    lum_adjust_highlight = .001
    lum_adjust_color = .001
    # Fixed colors, use for example:
    #   sRGBColor.new_from_rgb_hex('#000000')
    #   sRGBColor(128, 0, 255, is_upscaled=True)
예제 #33
0
from argparse import ArgumentParser

from terminaltables import SingleTable
from colormath.color_objects import sRGBColor, LabColor, HSVColor, HSLColor, XYZColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000

XTERM = []
with open('xterm.json') as file:
    schemeRaw = json.load(file)
for entry in schemeRaw:
    XTERM.append({
        'id':
        entry['colorId'],
        'color':
        convert_color(sRGBColor.new_from_rgb_hex(entry['hexString']),
                      LabColor),
        'name':
        entry['name']
    })


def fmtHex(str):
    black = convert_color(sRGBColor(0, 0, 0), LabColor)
    white = convert_color(sRGBColor(1, 1, 1), LabColor)
    color = sRGBColor.new_from_rgb_hex(str)
    lcolor = convert_color(color, LabColor)
    if delta_e_cie2000(lcolor, white) > delta_e_cie2000(lcolor, black):
        return "\033[48;2;{};{};{};38;2;255;255;255m{}\033[0m".format(
            int(255 * color.rgb_r), int(255 * color.rgb_g),
            int(255 * color.rgb_b), color.get_rgb_hex())
예제 #34
0
    elif (49 >= a >= 11):
        return 'Colors are more similar than different'
    elif (11 > a > 2):
        return 'Color difference is visible at a glance'
    elif (2 >= a > 1):
        return 'Color difference visible through close observation'
    elif (a <= 1):
        return 'Color difference not perceptible with human eyes'


name_to_value = {}

for i in lines:
    split = i.split(':')
    if (len(split) == 2):
        name_to_value[split[0]] = sRGBColor.new_from_rgb_hex(split[1].upper())

for i in name_to_value:
    min_diff = 101.0
    min_diff_name = ''
    for j in name_to_value:
        if (i == j): continue

        lab_i = convert_color(name_to_value[i], LabColor)
        lab_j = convert_color(name_to_value[j], LabColor)

        delta_e = delta_e_cie2000(lab_i, lab_j)

        if (delta_e < min_diff):
            min_diff = delta_e
            min_diff_name = j
예제 #35
0
def convert_from_hex_to_rgb(hex_color):
    """
    converts a hex color into an RGB one
    """
    rgb_color = sRGBColor.new_from_rgb_hex(hex_color)
    return rgb_color.get_upscaled_value_tuple()
def hex_to_lab(hx):
    rgb = sRGBColor.new_from_rgb_hex(hx)
    return convert_color(rgb, LabColor)
import numpy as np
from tqdm import tqdm
from colormath.color_objects import LabColor, HSLColor, sRGBColor
from colormath.color_conversions import convert_color
from colormath.color_diff import delta_e_cie2000

# Base colors
#color_1 = sRGBColor.new_from_rgb_hex("#d95f02")
#color_2 = sRGBColor.new_from_rgb_hex("#7570b3")
#color_2 = sRGBColor.new_from_rgb_hex("#3E36B3")

color_1 = sRGBColor.new_from_rgb_hex("#D95E00")
color_2 = sRGBColor.new_from_rgb_hex("#0C00B3")

# Optimisation parameters
nb_final_candidates = 5

max_luminance_distance = 0.05
min_saturation_distance = 0.5

min_saturation = 0.25

max_luminance = 0.75
min_luminance = 0.15

luminance_step = 0.01
saturation_step = 0.01

# Convert them to Lab and HSL coordinates
lab_color_1 = convert_color(color_1, LabColor)
lab_color_2 = convert_color(color_2, LabColor)
 def test_set_from_rgb_hex(self):
     rgb = sRGBColor.new_from_rgb_hex('#7bc832')
     self.assertColorMatch(rgb, sRGBColor(0.482, 0.784, 0.196))
def color_diff(hex_color, color_triple):
    return delta_e_cie2000(
        convert_color(sRGBColor.new_from_rgb_hex(hex_color), LabColor),
        convert_color(sRGBColor(*color_triple, is_upscaled=True), LabColor),
    )
예제 #40
0
 def from_rgb(cls, rgb):
     c = sRGBColor.new_from_rgb_hex(rgb).get_upscaled_value_tuple()
     return cls(c[0], c[1], c[2])