def update_color(rgb, update_name=True): global blinkstick c_hex = webcolors.rgb_to_hex(rgb) try: c_name = webcolors.hex_to_name(c_hex) except: c_name = '' fg = '#000' if use_black_text(rgb) else '#fff' canvas.configure(text=c_hex + '\n' + c_name, bg=c_hex, fg=fg) if update_name: try: old_name = top.tk.globalgetvar('name') except: old_name = None if c_name and c_name != old_name: top.tk.globalsetvar('name', c_name) if blinkstick is not None: try: blinkstick.set_color(rgb) except: blinkstick = None top.tk.globalsetvar('dev_button', 'No device')
def get_colour_name(requested_colour): try: closest_name = actual_name = webcolors.hex_to_name(requested_colour) except ValueError: closest_name = closest_colour(requested_colour) actual_name = None return actual_name, closest_name
def convertWebColorToOpenScad(cstr): try: res = webcolors.hex_to_name(cstr) except: res = [c / 255 for c in webcolors.hex_to_rgb(cstr)] #res.append(0.5) return res
def getColors(request): trousers = list(TrouserVariant.objects.all().values_list( 'color', flat=True).distinct()) wavecaps = list(WavecapVariant.objects.all().values_list( 'color', flat=True).distinct()) temp = set(trousers + wavecaps) colors = [webcolors.hex_to_name(x).title() for x in temp] return JsonResponse(colors, safe=False)
def get_color_name(various, peak): try: closest_name = actual_name = webcolors.hex_to_name(various) except ValueError: closest_name = closest_color(peak) actual_name = None print "Actual color name:", actual_name, ", closest color name:", closest_name return closest_name
def test_hex_to_name(self): """ Test conversion from hex to color name. """ test_pairs = ((u'#ffffff', u'white'), (u'#fff', u'white'), (u'#000080', u'navy'), (u'#daa520', u'goldenrod')) for pair in test_pairs: self.assertEqual(pair[1], webcolors.hex_to_name(pair[0]))
def style_to_highlight_wdcolor(value, constants): try: name = webcolors.hex_to_name(value).lower() if value.startswith("#") else value.lower() if name in WORD_WDCOLORINDEX_MAPPING: return getattr(constants, WORD_WDCOLORINDEX_MAPPING[name]) # Try and get the color from the wdColors enumeration return getattr(constants, "wd" + name.capitalize()) except (AttributeError, ValueError): return None
def style_to_highlight_wdcolor(value, constants): try: name = webcolors.hex_to_name(value).lower() if value.startswith( "#") else value.lower() if name in WORD_WDCOLORINDEX_MAPPING: return getattr(constants, WORD_WDCOLORINDEX_MAPPING[name]) # Try and get the color from the wdColors enumeration return getattr(constants, "wd" + name.capitalize()) except (AttributeError, ValueError): return None
def addArray(array, article): #rgb = (int(float(array[0])), int(float(array[1])), int(float(array[2]))) rgb = tuple(array) hex_result = '%02x%02x%02x' % rgb print(hex_result) input = hex_result + ', ' + article item = getClosestColor(input) recommendation = item print(recommendation) value = recommendation[0].split(', ') color = value[0] item = value[1] print("Wear a " + webcolors.hex_to_name('#' + color) + " " + item) subscription_key = "3dcb81c95f9d46248813f574677f3272" app = text2speech.TextToSpeech(subscription_key, webcolors.hex_to_name('#' + color), article) app.get_token() app.save_audio("suggestion.wav") playsound('suggestion.wav')
def find_color(string): ''' "Find the color of #00FF00 and #FF4500" ['lime', 'orangered'] ''' text = re.findall('\#(?:[0-9a-fA-F]{3}){1,2}', string) conv_name = [] for i in text: conv_name.append(webcolors.hex_to_name(i)) return conv_name
def rgb_name(self): """Get the RGB color name.""" try: return webcolors.hex_to_name(self.rgb_hex_color()) except: _LOGGER.error( "Could not convert HEX %s to color name: %s", self.rgb_hex_color(), sys.exc_info()[0], ) raise UnknownStateException("no_rgb_name_color")
def test_hex_to_name_specs(self): """ Using one of the supported specifications succeeds; using an unsupported specification raises ValueError. """ for supported_spec in webcolors.SUPPORTED_SPECIFICATIONS: result = webcolors.hex_to_name("#ffffff", spec=supported_spec) assert "white" == result for unsupported_spec in ("css1", "css4", "html5"): self.assertRaises(ValueError, webcolors.hex_to_name, "#ffffff", spec=unsupported_spec)
def test_hex_to_name(self): """ Test conversion from hex to color name. """ test_pairs = ( (u'#ffffff', u'white'), (u'#fff', u'white'), (u'#000080', u'navy'), (u'#daa520', u'goldenrod') ) for hex_value, name in test_pairs: assert name == webcolors.hex_to_name(hex_value)
def test_hex_to_name(self): """ Test conversion from hex to color name. """ test_pairs = ( ("#ffffff", "white"), ("#fff", "white"), ("#000080", "navy"), ("#daa520", "goldenrod"), ) for hex_value, name in test_pairs: assert name == webcolors.hex_to_name(hex_value)
def test_hex_to_name_specs(self): """ Using one of the supported specifications succeeds; using an unsupported specification raises ValueError. """ for supported_spec in (u'html4', u'css2', u'css21', u'css3'): self.assertEqual(u'white', webcolors.hex_to_name(u'#ffffff', spec=supported_spec)) for unsupported_spec in (u'css1', u'css4', u'html5'): self.assertRaises(ValueError, webcolors.hex_to_name, '#ffffff', spec=unsupported_spec)
async def color_hex_command(self, ctx, text): result = re.search(self.color_match, text) if result is None: return await self.send_text(ctx, "WRONG_HEX_CODE") hex_color = result["color"] rgb = self.hex_to_rgb(hex_color) try: color_name = webcolors.hex_to_name(f"#{hex_color}") except: color_name = "???" embed = discord.Embed(title=f"Hex: {hex_color}", color=int(f'0x{hex_color}', 16)) embed.add_field(name="hex", value=f"#{hex_color}", inline=False) embed.add_field(name="rgb", value=f"r: {rgb[0]}, g:{rgb[1]}, b:{rgb[2]}", inline=False) embed.add_field(name="name", value=color_name) await ctx.send(embed=embed)
def push_colors(handler, hex_query, rgb): handler.add_new_item(title=hex_query, subtitle="Hex", arg=hex_query) try: name = hex_to_name(hex_query, spec='css3') css3_color = "color: %s;" % name handler.add_new_item(title=css3_color, subtitle="CSS3", arg=css3_color) except ValueError: pass rgb_str = "rgb(%s, %s, %s)" % rgb handler.add_new_item(title=rgb_str, subtitle="RGB", arg=rgb_str)
def hex2name(c): h_color = "#{:02x}{:02x}{:02x}".format(int(c[0]), int(c[1]), int(c[2])) try: nm = webcolors.hex_to_name(h_color, spec="css3") except ValueError as v_error: # print("{}".format(v_error)) rms_lst = [] for img_clr, img_hex in webcolors.CSS3_NAMES_TO_HEX.items(): cur_clr = webcolors.hex_to_rgb(img_hex) rmse = np.sqrt(mean_squared_error(c, cur_clr)) rms_lst.append(rmse) closest_color = rms_lst.index(min(rms_lst)) nm = list(webcolors.CSS3_NAMES_TO_HEX.items())[closest_color][0] return nm
def test_hex_to_name_specs(self): """ Using one of the supported specifications succeeds; using an unsupported specification raises ValueError. """ for supported_spec in webcolors.SUPPORTED_SPECIFICATIONS: result = webcolors.hex_to_name(u'#ffffff', spec=supported_spec) assert u'white' == result for unsupported_spec in (u'css1', u'css4', u'html5'): self.assertRaises( ValueError, webcolors.hex_to_name, '#ffffff', spec=unsupported_spec )
def create_palette_from_hex_list(self, hexadecimal, output_json): """ Given a list of hexadecimal code colors, it creates a new palette saved in output_json contains the hexadecimal and RGB codes, and color names (if existing). Parameters ---------- hexadecimal: list of strings List of hexadecimal values in format: ['#XXXXXX', ...] output_json : string Path for the JSON file where to save the palette in the correct format. Returns ------- palette : dictionary Python dictionary contains colors codes and values. Examples ------- >>> from mypalette import LoadPalette >>> palette = LoadPalette() >>> p = palette.create_palette_from_hex_list( hexadecimal = ['#000000', '#FFFFFF'], output_json = 'black_and_white.json') >>> print(p) {'HEXs': ['#000000', '#FFFFFF'], 'RGBs': [(0.0, 0.0, 0.0), (1.0, 1.0, 1.0)], 'Names': ['black', 'white']} """ hexadecimal = [ x if x.startswith("#") else '#' + x for x in hexadecimal ] Names = [] for x in hexadecimal: try: Names.append(webcolors.hex_to_name(x)) except ValueError: Names.append("") rgb = [clr.to_rgb(x) for x in hexadecimal] palette = { 'HEXs': hexadecimal, 'RGBs': rgb, 'Names': Names, } self.__save_palette(palette=palette, output_json=output_json) return palette
async def color_rgb_command(self, ctx, r, g, b): if not (r.isdigit() and g.isdigit() and b.isdigit()): return await self.send_text(ctx, "WRONG_RGB") elif not (int(r) <= 255 and int(g) <= 255 and int(b) <= 255): return await self.send_text(ctx, "WRONG_RGB") r = int(r); g = int(g); b = int(b) hex_color = '#{:02x}{:02x}{:02x}'.format(r, g, b) try: color_name = webcolors.hex_to_name(hex_color) except: color_name = "???" embed = discord.Embed(title=f"RGB: {r} {g} {b}", color=int(f'0x{hex_color.replace("#", "")}', 16)) embed.add_field(name="hex", value=hex_color, inline=False) embed.add_field(name="rgb", value=f"r: {r}, g:{g}, b:{b}", inline=False) embed.add_field(name="name", value=color_name) await ctx.send(embed=embed)
def GetColorValue(self): from selenium.webdriver.support.color import Color import webcolors """Fetch the value attribute from the specified element.(For cases where GetText doesn't work) :rtype: str """ self._searchElement() text = None try: text = self._currentElement.value_of_css_property("color") hexform = Color.from_string(text).hex if hexform == "#303f9f": colname = 'blue' else: colname = webcolors.hex_to_name(hexform, spec='css3') except: self.testCache.logger_service.logger.exception( "ActionFailure-GetCSSValue:") return colname
def hextoname(hex: hug.types.text): return webcolors.hex_to_name("#" + hex)
def get_color_name(hex_color): try: return wc.hex_to_name(hex_color) except ValueError: return get_approx_color(hex_color)
def print_color(self, color_code): try: print webcolors.hex_to_name(color_code) except: print color_code
def get_color_name(self): return webcolors.hex_to_name(self.color).title()
# Random hex Color Generator import random # Create list of total hexdigits for colors import webcolors import bs4 letters = ['1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'A', 'B', 'C', 'D', 'E', 'F'] ColorGen = random.sample(letters, 6) # a variable that create random 6 numbers from the letters list Color = ''.join(ColorGen) # remove the spaces hexColor = str('#' + Color) print(hexColor) # rgb= hex_to_rgb(hexColor) # print(rgb) # print(webcolors.rgb_to_name(rgb, u'html4')) import re str = hexColor match = re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', str) if match: print('Hex is valid') print(webcolors.hex_to_name(hexColor)) else: print('Hex is not valid') # # print(webcolors.hex_to_name("#ffffff", u'css3')) # c = input('he') # print(webcolors.hex_to_name(c))
def color_name(hexcode): return webcolors.hex_to_name(hexcode).title()
def get_color_name(self): try: return webcolors.hex_to_name(self.color) except ValueError: # default to while on broken color return "white"
import webcolors def rgb_to_hex(red, green, blue): rgbList = [red, green, blue] returnList = [] for idx in rgbList: if idx < 10: returnList.append('0' + hex(idx)[2:].upper()) else: returnList.append(hex(idx)[2:].upper()) return '#'+"".join(returnList) abc = rgb_to_hex(255,0,0) print(abc) print(webcolors.hex_to_name(abc))
def _scrape_team_colors(self, team_soup): def find_nearest_color(hex_color): # make hex rgb rgb_triplet = webcolors.hex_to_rgb(hex_color) min_colours = defaultdict() # {score: color name,..} for key, name in webcolors.CSS3_HEX_TO_NAMES.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - rgb_triplet[0])**2 gd = (g_c - rgb_triplet[1])**2 bd = (b_c - rgb_triplet[2])**2 min_colours[rd + gd + bd] = name return (min_colours[min(min_colours.keys())]) team_colors = defaultdict(lambda: defaultdict(list)) # background colors first (kit) imgs = team_soup.find('td', attrs={'class': 'toccolours'}) if imgs: hexs = [] for ss in imgs.find_all('div', style=re.compile('background-color')): colcode = ss["style"].split('background-color:')[-1].replace( ';', '').strip() if len(colcode) == 7: hexs.append(colcode) for t in Counter(hexs).most_common(5): try: c = webcolors.hex_to_name(webcolors.normalize_hex(t[0])) except: c = find_nearest_color(t[0]) team_colors['kit']['hex'].append(t[0]) team_colors['kit']['name'].append(c) team_colors['kit']['name'] = list(set(team_colors['kit']['name'])) # team logos if not os.path.isdir('data_temp'): os.mkdir('data_temp') im_logo = team_soup.find('a', class_='image') with open('data_temp/logofile.png', 'wb') as f: f.write( requests.get('https:' + im_logo.find('img')['src']).content) i1 = cv2.imread('data_temp/logofile.png') rgbs = [] for x in range(i1.shape[0]): for y in range(i1.shape[1]): bgr = list(i1[x, y, :]) rgbs.append(tuple(bgr[::-1])) for t in Counter(rgbs).most_common(5): try: c = webcolors.rgb_to_name(t[0]) except: c = find_nearest_color(webcolors.rgb_to_hex(t[0])) team_colors['logo']['hex'].append(webcolors.rgb_to_hex(t[0])) team_colors['logo']['name'].append(c) shutil.rmtree('data_temp') team_colors['logo']['name'] = list(set(team_colors['logo']['name'])) return {"team_colors": team_colors}
def test_color_conversion(color_name): hex_color = color_weechat_to_html(color_html_to_weechat(color_name)) new_color_name = webcolors.hex_to_name(hex_color, spec='html4') assert new_color_name == color_name
@property def as_dict(self): return { "name": self.name, "rgb": self.rgb, "hsv": self.hsv, "hex": self.hex, "hls": self.hls, "yiq": self.yiq } if __name__ == "__main__": hex_color = "#ff0000" color_name = hex_to_name(hex_color) print(color_name) h, s, v = name_to_hsv(color_name) print(h, s, v) r, g, b = hex_to_rgb(hex_color) print(r, g, b) h, s, v = rgb_to_hsv(r, g, b) print(h, s, v) color = Color() print(color.name) print(color.as_dict) color = Color.from_name("red") print(color.name, color.rgb) print(color.as_dict) color = Color.from_name("violet")