def init_hol(hol, basecolor=None, pattern=None): """ Initialize a Holiday to some random-ish colors """ if basecolor is not None: (r, g, b) = webcolors.hex_to_rgb(basecolor) hol.fill(r, g, b) elif pattern is not None: for globeidx, vals in enumerate(pattern): (r, g, b) = webcolors.hex_to_rgb(vals) hol.setglobe(globeidx, r, g, b) pass else: for globeidx in range(0, HolidaySecretAPI.NUM_GLOBES): color = [] # red color.append(random.randint(0, 130)) #color.append(0) # green color.append(random.randint(0, 130)) # blue color.append(random.randint(0, 130)) #color.append(0) r, g, b = color hol.setglobe(globeidx, r, g, b) pass hol.render() pattern = hol.globes[:] return pattern
def colored_image(request, color): from webcolors import hex_to_rgb base_dir = join(settings.MEDIA_ROOT, 'event_logs') full_path = join(base_dir, '%s.png' % color) if hasattr(settings, 'USE_S3_STORAGE') and settings.USE_S3_STORAGE: rgb = hex_to_rgb('#%s' % color) image = Image.new('RGB', (1, 1), rgb) response = HttpResponse(mimetype="image/png") image.save(response, "PNG") return response else: # make the dir if it doesn't exist if not isdir(base_dir): mkdir(base_dir) try: f = open(full_path, 'rb') data = f.read() f.close() except: rgb = hex_to_rgb('#%s' % color) image = Image.new('RGB', (1, 1), rgb) image.save(full_path, "PNG") f = open(full_path, 'rb') data = f.read() f.close() return HttpResponse(data, mimetype="image/png")
def closest_delta_e(self, hex): """ Calculates the Delta E difference between a hex value and others in the specified palette and returns the closest match (CMC method) http://en.wikipedia.org/wiki/Color_difference#CMC_l:c_.281984.29 """ incumbent = RGBColor(*webcolors.hex_to_rgb(hex)) shortest_dist = None nearest_colour = None for key, details in self.colours().items(): candidate = RGBColor(*webcolors.hex_to_rgb(key)) cdist = incumbent.delta_e(candidate, method="cmc") if nearest_colour is None: nearest_colour = (candidate, key, details) shortest_dist = cdist elif cdist < shortest_dist: shortest_dist = cdist nearest_colour = (candidate, key, details) details = nearest_colour[2] name = details['name'] hex = self.hex(name) return hex, name
def _parse_led_color(self, led, color): if led not in (LED_LOGO, LED_WHEEL): raise ValueError("Invalid LED: %s" % (led,)) if is_strtype(color): try: color = webcolors.name_to_rgb(color) except ValueError: try: color = webcolors.hex_to_rgb(color) except ValueError: color = webcolors.hex_to_rgb("#" + color) if not hasattr(color, '__iter__'): raise ValueError("Invalid Color: %s" % (color, )) return color
def hex_me_up(self): self.hex_value = webcolors.rgb_to_hex(self.rgb) snapped, colour_name = swatchbook.closest_delta_e('css3', self.hex_value) snapped_rgb = webcolors.hex_to_rgb(snapped) hsv = self.rgb_to_hsv(*snapped_rgb) target = RGBColor(*snapped_rgb) original = RGBColor(*self.rgb) cdist = target.delta_e(original, method="cmc") prom = Decimal(self.prominence).quantize(TWOPLACES) dist = Decimal(cdist).quantize(TWOPLACES) ELITE = False self.css = { 'r': self.rgb[0], 'g': self.rgb[1], 'b': self.rgb[2], 'hue': hsv[0], 'hex': snapped, 'name': colour_name, 'distance': float(dist), 'prominence': float(prom), 'elite': ELITE, } return self.css
def rgb(self, rgb): if type(rgb) is StringType and rgb[0] == '#': rgb = hex_to_rgb(rgb) elif type(rgb) is StringType: rgb = name_to_rgb(rgb) r,g,b = rgb return (b << 16) + (g << 8) + r
def parsecolor(cc): if multiplier.search(cc): (fact, cc) = multiplier.split(cc, 1) fact = float(fact) else: fact = 1. cc = cc.strip() try: c = numpy.array(map(float, cc.split(','))) if c.size == 1: c = c.repeat(3) if c.size != 3: raise StandardError() return c * fact except ValueError: pass try: c = webcolors.hex_to_rgb(cc) return numpy.array(c)/255. * fact except ValueError: pass c = webcolors.name_to_rgb(cc) return numpy.array(c)/255. * fact
def text_color(css_color, light, dark): if css_color[0] == '#': color = webcolors.hex_to_rgb(css_color) else: color = webcolors.name_to_rgb(css_color) color = colorsys.rgb_to_hls(*(a / 255. for a in color)) return light if color[1] < 0.7 else dark
def to_gray(hex_str): c = webcolors.hex_to_rgb(hex_str) g = int(c[0] * 0.299 + c[1] * 0.587 + c[2] * 0.114) c = (g, g, g) h = webcolors.rgb_to_hex(c) #return h if h != "#c7c7c7" else "#ffffff" return h
def read(filename): colors = [] basewidth = 100 im = Image.open(filename) waspect = (basewidth/float(im.size[0])) haspect = int((float(im.size[1])*float(waspect))) im = im.resize((basewidth,haspect),PIL.Image.ANTIALIAS) if im.mode != "RGB": im = im.convert("RGB") px = im.load() width,height = im.size for i in range(0,height): for j in range(0,width): min_colors = {} r,g,b = px[j,i] for key,name in webcolors.css3_hex_to_names.items(): rc,gc,bc = webcolors.hex_to_rgb(key) rd = (rc-r) ** 2 gd = (gc-g) ** 2 bd = (bc-b) ** 2 min_colors[(rd+gd+bd)] = name color_name = min_colors[min(min_colors.keys())] if color_name not in colors: colors.append(color_name) return colors
def set_state(): request_data = request.get_json().copy() color = request_data.pop('color', None) if color is not None: rgb = webcolors.hex_to_rgb(color) hls = colorsys.rgb_to_hls(*rgb) data['hue'] = hls[0] data['saturation'] = hls[2] data['brightness'] = hls[1] power = request_data.pop('power', None) if power is not None: if power in ['on', 'off']: data['power'] = power request_data['power'] = power else: return json.dumps({ 'error': "Invalid value for 'power'!" }, indent=4), 400 for key, value in request_data.items(): data['key'] = value return json.dumps({ "results": [ { "id": "l1fxl4mp", "label": "lamp", "status": "ok", } ] }, indent=4)
def draw_event(draw, height, width, event, begintime): box = solve_box_corners(event, height, width) draw.rectangle(box, fill=webcolors.hex_to_rgb('#'+event.category.color)) text = event.begin.time().strftime('%H:%M') + ' ' + event.category.name if event.split_tail is False: draw_text(draw, (box[0],box[1]+3), text)
def readable_text_color(color_hex): r, g, b = webcolors.hex_to_rgb(color_hex) # Calculate brightness of the background and compare to threshold if 0.2126 * r + 0.7152 * g+ 0.0722 * b < 0.279*255: return "#FFFFFF" else: return "#000000"
def __parseColor(color): try: return webcolors.name_to_rgb(color) except ValueError: if not color.startswith('#'): color = "#" + color return webcolors.hex_to_rgb(color)
def resolve(deviceType, deviceAttr, values): """ return one value to use for this attr, given a set of them that have come in simultaneously. len(values) >= 1. bug: some callers are passing a device instance for 1st arg """ if len(values) == 1: return values[0] if deviceAttr == L9['color']: rgbs = [hex_to_rgb(v) for v in values] return rgb_to_hex([max(*component) for component in zip(*rgbs)]) # incomplete. how-to-resolve should be on the DeviceAttr defs in the graph. if deviceAttr in [L9['rx'], L9['ry'], L9['zoom'], L9['focus'], L9['iris']]: floatVals = [] for v in values: if isinstance(v, Literal): floatVals.append(float(v.toPython())) elif isinstance(v, (int, float)): floatVals.append(float(v)) else: raise TypeError(repr(v)) # averaging with zeros? not so good return Literal(sum(floatVals) / len(floatVals)) return max(values)
def make_rainbow(colours, width, height): count = len(colours) slice = 100 width = slice * count height = 200 im = Image.new("RGBA", (width, height)) canvas = ImageDraw.Draw(im) dx = width / float(len(colours)) x = 0 y = height / 2.0 for hex in colours: rgb = webcolors.hex_to_rgb(hex) canvas.line((x, y, x + dx, y), width=height, fill=rgb) canvas.text((x + 10, 10), hex, fill=(255,255,255)) x += dx return im
def set_led_color(led, color): if led not in (LED_LOGO, LED_WHEEL): raise ValueError("Invalid LED: %s" % (led,)) if is_strtype(color): try: color = webcolors.name_to_rgb(color) except ValueError: try: color = webcolors.hex_to_rgb(color) except ValueError: color = webcolors.hex_to_rgb("#" + color) if not hasattr(color, '__iter__'): raise ValueError("Invalid Color: %s" % (color, )) args = (chr(led),) + tuple([chr(b) for b in color]) return "\x08%s%s%s%s" % args
def color2intensity(colorString, minIntensity=0, maxIntensity=1000): if colorString == "" or colorString == "none": return minIntensity else: rgb = webcolors.hex_to_rgb(colorString) gray = 0.2989 * rgb[0] + 0.5870 * rgb[1] + 0.1140 * rgb[2] intensity = (1-gray/255) * (maxIntensity-minIntensity) + minIntensity return intensity
def get_colour_name(self, rgb_triplet): min_colours = {} for key, name in webcolors.css21_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())]
def closest_colour(requested_colour): min_colours = {} for key, name in webcolors.css3_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())]
def hex_to_wdcolor(value): """ Receive a HEX color attribute string like '#9bbb59' (or '9bbb59') and transform it to a numeric constant in order to use it as a Selection.Font.Color attribute (as an item of WdColor enumeration) :param value: A HEX color attribute :return: A numeric WDCOLOR value """ rgbstrlst = webcolors.hex_to_rgb(value) return int(rgbstrlst[0]) + 0x100 * int(rgbstrlst[1]) + 0x10000 * int(rgbstrlst[2])
def color_to_rgb(color): import webcolors if color == 'none' or isinstance(color, (list, tuple)): rgb = color elif re.match('#', color): rgb = webcolors.hex_to_rgb(color) else: rgb = webcolors.name_to_rgb(color) return rgb
def get_color_name(requested_color): min_colors = {} for key, name in webcolors.css3_hex_to_names.items(): if name in ['grey','red','green','yellow','blue','magenta','cyan','white']: r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_color[0]) ** 2 gd = (g_c - requested_color[1]) ** 2 bd = (b_c - requested_color[2]) ** 2 min_colors[(rd + gd + bd)] = name return min_colors[min(min_colors.keys())]
def _closest_colour(self, requested_colour): min_colours = {} # css21 colors https://www.w3.org/TR/css3-color/ for key, name in webcolors.css21_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())]
def closest_color(requested_color): """Find the closest color name from an 8 bits RGB tuple.""" min_colors = {} for key, name in webcolors.css21_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_color[0]) ** 2 gd = (g_c - requested_color[1]) ** 2 bd = (b_c - requested_color[2]) ** 2 min_colors[(rd + gd + bd)] = name return min_colors[min(min_colors.keys())]
def get_closest_color(hex_color): rgb_color = colorweave.hex_to_rgb(hex_color) min_colors = {} for name, hex in ARTWORK_IMAGE_COLORS: r_c, g_c, b_c = webcolors.hex_to_rgb(hex) rd = (r_c - rgb_color[0]) ** 2 gd = (g_c - rgb_color[1]) ** 2 bd = (b_c - rgb_color[2]) ** 2 min_colors[(rd + gd + bd)] = name return min_colors[min(min_colors.keys())]
def hex_to_rgb(hex_value): """ Convert a hexadecimal color value to a 3-tuple of integers suitable for use in an rgb() triplet specifying that color. :param hex_value: The hexadecimal color to convert :returns: 3-tuple of int """ return webcolors.hex_to_rgb(hex_value)
def type_color(var): try: return webcolors.name_to_rgb(var) except ValueError as e: pass try: return webcolors.hex_to_rgb(var) except ValueError as e: pass raise ArgumentTypeError("invalid color value: '%s'" % var)
def cmd_set_color(self, *args): color = args[0][0] try: if color.startswith('#'): self._magic_blue.set_color(webcolors.hex_to_rgb(color)) else: self._magic_blue.set_color(webcolors.name_to_rgb(color)) except ValueError as e: logger.error('Invalid color value : {}'.format(str(e))) self.print_usage('set_color')
def closest_color(bgr): b, g, r = bgr color_distance = {} for hex, name in webcolors.CSS3_HEX_TO_NAMES.items(): rc, gc, bc = webcolors.hex_to_rgb(hex) rd = (r - rc) ** 2 gd = (g - gc) ** 2 bd = (b - bc) ** 2 color_distance[(rd+gd+bd)] = name return color_distance[min(color_distance.keys())]
def _to_color(tokens): rgb = None if len(tokens) == 3: try: rgb = [int(i) for i in tokens] except ValueError: print('\tbad color `{}`'.format(tokens)) elif tokens[0].startswith('#'): try: rgb = webcolors.hex_to_rgb(tokens[0]) except ValueError: print('\tbad color `{}`'.format(tokens[0])) else: try: rgb = webcolors.name_to_rgb(tokens[0]) except ValueError: print('\tbad color `{}`'.format(tokens[0])) # print('\tRGB: ', rgb) return rgb
def palette(): if 'clusters' not in request.form: resp = jsonify({'message': 'No number of clusters specified'}) resp.status_code = 400 return resp if 'image' not in request.files: resp = jsonify({'message': 'No file part in the request'}) resp.status_code = 400 return resp file = request.files['image'] if file.filename == '': resp = jsonify({'message': 'No file selected for uploading'}) resp.status_code = 400 return resp if file and allowed_file(file.filename): filename = secure_filename(file.filename) filepath = os.path.join(app.config['UPLOADS_DEFAULT_DEST'], filename) file.save(filepath) cluster_n = int(request.form.get('clusters')) kmeans = Kmeans(filepath, cluster_n) color_hex = kmeans.get_tints() print(color_hex) color_names = [] for color in color_hex: r, g, b = hex_to_rgb(color) name = Knn().get_color_name(r, g, b) color_names.append(name) print(color_names) resp = jsonify({ 'message': 'File successfully uploaded', 'colors': color_hex, 'names': color_names }) resp.status_code = 201 return resp else: resp = jsonify({'message': 'Allowed file types are png, jpg, jpeg'}) resp.status_code = 400 return resp
def closest_color(requested_color): # init dict min_color = {} for key, name in webcolors.html4_hex_to_names.items(): # Saving RGB value for the color being treated r_c, g_c, b_c = webcolors.hex_to_rgb(key) # We substract the color treated with the unknown value rd = (r_c - requested_color[0])**2 gd = (g_c - requested_color[1])**2 bd = (b_c - requested_color[2])**2 # We fill the the dict with the sum of the the RBG value # from the previous substraction # The dict is filled with all the colors with the color deviation # between the color know and the one we are trying to find min_color[(rd + gd + bd)] = name # We return the name of the color which has the minimum deviation return min_color[min(min_color.keys())]
def draw_filled_rectangle(x1, y1, x2, y2, color): # limit to x to 480, y to 272 try: if int(color, 16): hex_color = webcolors.hex_to_rgb('#' + color) elif color == '000000': hex_color = (0, 0, 0) except ValueError: hex_color = webcolors.name_to_rgb(color) upper_color_byte = (hex_color[0] >> 3 << 3) + (hex_color[1] >> 5 ) # RRRRR GGG lower_color_byte = (hex_color[1] >> 2 << 5) % 256 + (hex_color[2] >> 3 ) # GGG BBBBB #print bin(upper_color_byte), bin(lower_color_byte) # probably need to cast x1, x2, y1, y2 to ints here pytronics.serialWrite( chr(0xFF) + chr(0xC4) + chr(x1 / 256) + chr(x1 % 256) + chr(y1 / 256) + chr(y1 % 256) + chr(x2 / 256) + chr(x2 % 256) + chr(y2 / 256) + chr(y2 % 256) + chr(upper_color_byte) + chr(lower_color_byte), 9600) return 'Rectangle drawn'
async def add_closest_colour(requested_colour: list): """ Based on euclidean distance find nearest specified WebColor and add it. :param requested_colour: list [R, G, B] color """ logging.info("Searching for closest colour to %s", requested_colour) min_colours = {} for key, name in webcolors.CSS3_HEX_TO_NAMES.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0])**2 gd = (g_c - requested_colour[1])**2 bd = (b_c - requested_colour[2])**2 min_colours[(rd + gd + bd)] = name closed = min(min_colours.keys()) # Saving it for later use webcolors.CSS3_HEX_TO_NAMES[webcolors.rgb_to_hex( requested_colour)] = min_colours[closed] logging.info("Find and save closest colour for %s named %s", requested_colour, min_colours[closed])
def convert_rgb_to_names(rgb_tuple): """ But : Fonction qui retourne la couleur la couleur html la plus proche en fonction de l'intensité rgb Input : - rgb_tuple : tuple de longueur 3 contenant les intensités des pixels rouge, vert et bleu Output: - f' {names[index]}' : string de la couleur html la plus proche du tuple rgb fourni """ # a dictionary of all the hex and their respective names in css css3_db = webcolors.CSS3_HEX_TO_NAMES names = [] rgb_values = [] for color_hex, color_name in css3_db.items(): names.append(color_name) rgb_values.append(webcolors.hex_to_rgb(color_hex)) kdt_db = KDTree(rgb_values) distance, index = kdt_db.query(rgb_tuple) return f' {names[index]}'
def fill_attribute_dict(attribute_dict): """parse the color""" if 'color' in attribute_dict: if re.match("#[0-9a-fA-F]{6}", attribute_dict['color']): col = [z / 255. for z in hex_to_rgb(attribute_dict['color'])] attribute_dict['color'] = colors.Color(col[0], col[1], col[2], 1) else: attribute_dict.pop('color') """parse the font family""" if 'font_family' in attribute_dict: if not font_reader.is_registered_font( attribute_dict['font_family']): logging.warning("{} not found, using Helvetica instead".format( attribute_dict['font_family'])) # Helvetica is built into ReportLab, so we know it's safe attribute_dict['font_family'] = "Helvetica" """parse the font attributes""" for font_attr in [ 'font_size', 'first_line_indent', 'left_indent', 'right_indent' ]: if font_attr in attribute_dict: try: attribute_dict[font_attr] = int(attribute_dict[font_attr]) except ValueError as e: logging.warning("{} warning: {}".format(font_attr, e)) # Get rid of xml font attribute, will use default later attribute_dict.pop(font_attr) """parse the margins""" for margin_attr in [ 'top_margin', 'bottom_margin', 'left_margin', 'right_margin' ]: if margin_attr in attribute_dict: try: attribute_dict[margin_attr] = int( attribute_dict[margin_attr]) except ValueError as e: logging.warning("{} warning: {}".format(margin_attr, e)) # Get rid of xml margin attribute, will use default later attribute_dict.pop(margin_attr) return attribute_dict
def get_colour_name(requested_colour, spec='css3'): """Get colour name for an RGB tuple. Colour names can be those from css2 (simpler) or css3 (more flowery) """ try: return webcolors.rgb_to_name(requested_colour, spec) except ValueError: pass colours = getattr(webcolors, '%s_hex_to_names' % spec).items() min_colours = {} for key, name in colours: r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0]) ** 2 gd = (g_c - requested_colour[1]) ** 2 bd = (b_c - requested_colour[2]) ** 2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())]
def colour_seen(self, properties): colors = [(int(color.color.red), int(color.color.green), int(color.color.blue), color.pixel_fraction) for color in properties.dominant_colors.colors] colors.sort(key=lambda x: x[3], reverse=True) for color in colors[0:2]: try: closest_name = actual_name = (webcolors.rgb_to_name( color[0:3])) except ValueError: min_color = float('inf') for hex_val, name in webcolors.css3_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(hex_val) r_dist = (r_c - color[0])**2 g_dist = (g_c - color[1])**2 b_dist = (b_c - color[2])**2 if color[3] * (r_dist + g_dist + b_dist) < min_color: min_color = color[3] * (r_dist + g_dist + b_dist) closest_name = name return self.colour_group_mapping(closest_name)
def parse_colour(s, alpha=255): r = 0 g = 0 b = 0 if isinstance(s, tuple): try: r = s[0] g = s[1] b = s[2] except Error: pass return (r, g, b, alpha) s = s.lower() try: r, g, b = webcolors.name_to_rgb(s) except ValueError: try: r, g, b = webcolors.hex_to_rgb(s) except ValueError: pass return (r, g, b, alpha)
def closest_colour(requested_colour): """Prend en entré un triplet (r,g,b) correspondant au RGB d'un pixel d'une image, et renvoie la couleur la plus proche associée (distance euclidienne) Paramètre ---------- requested_colour : tuple Triplet RGB (r,g,b) d'un pixel Retour ------- str Couleur associé au pixel (choisi dans le dictionnaire colour_dict) """ min_colours = {} for key, name in colour_dict.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - requested_colour[0])**2 gd = (g_c - requested_colour[1])**2 bd = (b_c - requested_colour[2])**2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())]
def _color_to_autotap(color): hue, saturation = color.split(',') hue = int(hue) * 1.0 / 100 saturation = int(saturation) * 1.0 / 100 value = 1 r, g, b = colorsys.hsv_to_rgb(hue, saturation, value) r *= 255 g *= 255 b *= 255 current_color = None min_diff = None for key in webcolors.CSS3_NAMES_TO_HEX: rc, gc, bc = webcolors.hex_to_rgb(webcolors.CSS3_NAMES_TO_HEX[key]) rd = (r - rc) * (r - rc) gd = (g - gc) * (g - gc) bd = (b - bc) * (b - bc) diff = rd + gd + bd min_diff = diff if min_diff is None else min(min_diff, diff) current_color = key if min_diff is None or min_diff < diff else current_color return current_color
def getColorMap(engine, query, arglist, out_text): ###description: function to convert hex values to rgb df = pd.read_sql_query(query, con=engine) print df for index, row in df.iterrows(): rgb = wc.hex_to_rgb(row[arglist[1]]) print rgb r = rgb[0] g = rgb[1] b = rgb[2] rgb_string = '{0} {1} {2} {3}'.format(row[arglist[0]], r, g, b) print rgb_string df.at[index, 'colormap'] = rgb_string print df df['colormap'].to_csv(out_text, sep='\t', index=False)
def __init__(self, color=None): if color is None: self.r = self.g = self.b = 160 elif isinstance(color, Color): self.r, self.g, self.b = color.r, color.g, color.b elif isinstance(color, str): if color[0] == "#": c = hex_to_rgb(color) else: c = name_to_rgb(color) self.r = c.red self.g = c.green self.b = c.blue elif isinstance(color, (tuple, list)) and len(color) == 3: if all((isinstance(c, float) and (c <= 1.0) and (c >= 0.0)) for c in color): self.r, self.g, self.b = (int(c * 255) for c in color) elif all((isinstance(c, int) and (c <= 255) and (c >= 0)) for c in color): self.r, self.g, self.b = color else: self._invalid(color) else: self._invalid(color)
def _callback(self): from webcolors import name_to_rgb, hex_to_rgb if not self.send_updates_to_renderer: return for i in range(len(self.palette)): try: color = name_to_rgb(self.color_pickers[i].value) except ValueError: color = hex_to_rgb(self.color_pickers[i].value) c = [ float(color.red) / 255.0, float(color.green) / 255.0, float(color.blue) / 255.0, float(self.alpha_sliders[i].value) / 255.0 ] self.palette[i] = c if self._on_change: self._on_change(self)
def get_colors(image, number): clf = KMeans(n_clusters=number) labels = clf.fit_predict(image) counts = Counter(labels) center_colors = clf.cluster_centers_ ordered_colors = [center_colors[i] for i in counts.keys()] hex_colors = [RGB2HEX(ordered_colors[i]) for i in counts.keys()] rgb_colors = [webcolors.hex_to_rgb(hex_colors[i]) for i in counts.keys()] named_colors = [get_color_name(rgb_colors[i]) for i in counts.keys()] values = list(counts.values()) percentages = [] for i in values: p = round((i / 160000) * 100, 0) percentages.append(p) package = list(zip(hex_colors, named_colors, percentages)) return package
def png_api(color: str, width: int, height: int): if width > PNG_DIMENSION_LIMIT or height > PNG_DIMENSION_LIMIT: return "Dimension too large", 400 try: rgb = tuple(hex_to_rgb(color)) except ValueError: return "Invalid color", 400 rows = [] for row in range(height): row = [] for col in range(width): row.extend(rgb) rows.append(tuple(row)) buffer = io.BytesIO() writer = png.Writer(width, height, greyscale=False) writer.write(buffer, rows) buffer.seek(0) return send_file(buffer, mimetype="image/png")
def getColor(photoTitle): """ Returns the color most prominent in item image. Args: photoTitle (string) represents photoTitle to predict color of. Returns: color (string) represents color of item for given photo. """ color_thief = ColorThief(photoTitle) c = color_thief.get_color(quality=1) min_colours = {} print(c) for key, name in webcolors.css21_hex_to_names.items(): r_c, g_c, b_c = webcolors.hex_to_rgb(key) rd = (r_c - c[0])**2 gd = (g_c - c[1])**2 bd = (b_c - c[2])**2 min_colours[(rd + gd + bd)] = name return (min_colours[min(min_colours.keys())])
def rgb_to_name(color_rgb: Union[Tuple[int, int, int], Tuple[float, float, float]], color_spec: str = "css3") -> str: """ Convert an RGB tuple to the closest named web colour For a full list of colours, see: https://www.w3.org/TR/css-color-3/ :param color_rgb: a red, green, blue colour value tuple :param color_spec: a color spec from the webcolors module :returns: a named colour string """ from webcolors import hex_to_rgb # Default to CSS3 color spec if none specified color_spec = str.lower(color_spec) if color_spec == "html4": from webcolors import HTML4_HEX_TO_NAMES color_dict = HTML4_HEX_TO_NAMES elif color_spec == "css2": from webcolors import CSS2_HEX_TO_NAMES color_dict = CSS2_HEX_TO_NAMES elif color_spec == "css21": from webcolors import CSS21_HEX_TO_NAMES color_dict = CSS21_HEX_TO_NAMES else: from webcolors import CSS3_HEX_TO_NAMES color_dict = CSS3_HEX_TO_NAMES min_colours = {} for key, name in color_dict.items(): r_c, g_c, b_c = hex_to_rgb(key) rd = (r_c - color_rgb[0])**2 gd = (g_c - color_rgb[1])**2 bd = (b_c - color_rgb[2])**2 min_colours[(rd + gd + bd)] = name return min_colours[min(min_colours.keys())]
def color_object_to_tuple(color): global webcolors_available # see if it's already a color tuple if type(color) is tuple and len(color) == 3: return color # can't convert non-string if type(color) is not str: return None color = color.strip() if webcolors_available: # try to convert from an english name try: return webcolors.name_to_rgb(color) except ValueError: pass except: pass # try to convert an web hex code try: return webcolors.hex_to_rgb(webcolors.normalize_hex(color)) except ValueError: pass except: pass # try to convert a string RGB tuple try: val = ast.literal_eval(color) if type(val) is not tuple or len(val) != 3: raise Exception return val except: pass return None
async def colour(self, ctx, *arg): if len(arg) > 3: await ctx.send('You did something wrong fam') return if len(arg) == 3: # must be rgb numbers! try: red, green, blue = [int(args) for args in arg] # passes RGB as ints except ValueError as err: await ctx.send(err) return if (len(arg) == 1) and (arg[0].startswith('#')): # this is a hex value try: red, blue, green = webcolors.hex_to_rgb(arg[0]) except ValueError as err: await ctx.send(err) return if (len(arg) == 1) and (not arg[0].isdigit()) and ( not arg[0].startswith('#')): # must be colour name try: red, green, blue = webcolors.name_to_rgb(arg[0], spec='css3') except ValueError as err: await ctx.send(err) return names = [] for light in self.lights: try: Bulb(light['ip'], effect="smooth", duration=1500).set_rgb(red, green, blue) except AssertionError as err: await ctx.send(err) return names.append(light['name']) successMsg = ", ".join(names) await self.lightEventMsg( ctx, f'Set colour to \({red}, {green}, {blue}\) on **{successMsg}**', red, green, blue)
def colored_image(request, color): from webcolors import hex_to_rgb base_dir = join(settings.MEDIA_ROOT, 'event_logs') full_path = join(base_dir, '%s.png' % color) # make the dir if it doesn't exist if not isdir(base_dir): mkdir(base_dir) try: f = open(full_path, 'rb') data = f.read() f.close() except: rgb = hex_to_rgb('#%s' % color) image = Image.new('RGB', (1, 1), rgb) image.save(full_path, "PNG") f = open(full_path, 'rb') data = f.read() f.close() return HttpResponse(data, mimetype="image/png")
def parse_color(c: str) -> Tuple[int, int, int]: """ Parse and returns the corresponding color :param c: RGB or hexadecimal string representation of the color :return: the color :raises ValueError: if c is not correctly defined """ try: c = hex_to_rgb(c) (red, green, blue) = c.red, c.green, c.blue except ValueError as e: regex_rgb = r"^rgb\((\d{1,3}),(\d{1,3}),(\d{1,3})\)$" _match = match(regex_rgb, c) if _match is not None: red = int(_match.groups()[0]) green = int(_match.groups()[1]) blue = int(_match.groups()[2]) if 0 > red or 0 > green or 0 > blue or 255 < red or 255 < green or 255 < blue: raise ValueError() else: raise ValueError() return red, green, blue
def exec(self) -> dict: ids = [] error = None for s in self.args['sections']: try: color = hex_to_rgb(s['color']) color = (int(color[0]), int(color[1]), int(color[2])) ids.append(self.controller.new_section(s['start'], s['end'], color)) except Overlapping: error = ExecutionError('section overlapping') break except ValueError: error = ExecutionError('start > end for some section') break # rollback in case of error if error is not None: self.controller.remove_sections(ids) raise error self.controller.render() return {'sections': ids}
def get_Pixel_Color_Names(i, pixels, name_storage): print("I am thread {0}".format(i)) w = 8 for k in range(i, i + 1): for j in range(0, w): # RGB = [] RGB = pixels[k, j] # num_storage.append(RGB) # Finds the nearest colour name within the webcolors dataset by converting the classification to rgb then then find the closest the square is to remove the negative value. try: colorname = webcolors.rgb_to_name(RGB) name_storage.append(colorname) except ValueError: min_colours = {} 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[0]) ** 2 gd = (g_c - RGB[1]) ** 2 bd = (b_c - RGB[2]) ** 2 min_colours[(rd + gd + bd)] = name name_storage.append(min_colours[min(min_colours.keys())])
def __init__(self): self.processing = False self._leds_data = bytearray(hyperion.ledCount * (0, 0, 0)) args = hyperion.args self.interval = int(100) self.level_min = int(args.get('level-min', 80)) self.level_max = int(args.get('level-max', 100)) self.color = args.get('color', 'green') if self.color.startswith('#'): self.color = webcolors.hex_to_rgb(self.color) else: self.color = webcolors.name_to_rgb(self.color) self.ledCount = hyperion.ledCount self._magnitudes = None print 'Effect: Volumetric Intensity ' print '----------------' print 'Led Count:' print self.ledCount self._spectrum = GstSpectrumDump(source=hyperion.args.get( 'audiosrc', 'autoaudiosrc'), vumeter=True, interval=self.interval, quiet=True, bands=4, callback=self.receive_magnitudes) self._spectrum.start() print 'Effect started, waiting for gstreamer messages...'
def index(): form = PhotoForm() if form.validate_on_submit(): image = form.photo.data filename = secure_filename(image.filename) # sanitize image name _, ext = os.path.splitext(filename) new_filename = uuid.uuid4().hex + ext # creating a random name image_with_palette, pallete, hex_codes = process_uploaded_image( image, pallete_division_factor=form.palette_height.data, outline_width=form.palette_outline_width.data, outline_color=hex_to_rgb( request.form.get("palette_outline_color")), ) image_with_pallete_path = os.path.join(app.root_path, "static/images", new_filename) pallete_path = os.path.join(app.root_path, "static/images", "pal" + new_filename) session["hex_codes"] = hex_codes # saving image and pallete image_with_palette.save(image_with_pallete_path) pallete.save(pallete_path) return redirect( url_for( "picture", name=new_filename, height=image_with_palette.height, width=image_with_palette.width, )) return render_template("index.html", form=form, src="default")
def parse_sms(): message = str(request.form['Body']).strip().lower() print("Received text message: " + message) universe = 1 num_fixtures = 24 data = array.array('B') if (message == "secret"): data.append(0) data.append(0) data.append(255) data.append(255) data.append(0) data.append(0) data = data * (num_fixtures / 2) else: try: color = webcolors.hex_to_rgb(xkcd_names_to_hex[message]) except: color = [randint(0, 255), randint(0, 255), randint(0, 255)] data.append(color[0]) data.append(color[1]) data.append(color[2]) data = data * num_fixtures ip = "172.16.11.50" port = 5000 message = "listentome" sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) sock.sendto(message.encode(), (ip, port)) time.sleep(0.1) global wrapper wrapper = ClientWrapper() client = wrapper.Client() client.SendDmx(universe, data, DmxSent) wrapper.Run() return ('<?xml version="1.0" encoding="UTF-8" ?><Response></Response>')
def mask_for_polygons(polygons, width, height): """ Create a color mask of classes with the same size as original image """ # White background img_mask = np.full((width, height, 3), 255, np.uint8) # Sort polygons by Z-order for cls, _ in sorted(ZORDER.items(), key=lambda x: x[1]): exteriors = [ np.array(poly.exterior.coords).round().astype(np.int32) for poly in polygons[str(cls)] ] cv2.fillPoly(img_mask, exteriors, webcolors.hex_to_rgb(COLOR_MAPPING[int(cls)])) # Some polygons have regions inside them which need to be excluded interiors = [ np.array(pi.coords).round().astype(np.int32) for poly in polygons[str(cls)] for pi in poly.interiors ] cv2.fillPoly(img_mask, interiors, (255, 255, 255)) return img_mask
def sms_response(request): ## 1 Get letter inp_str = request.POST["Body"] inp_str = inp_str.replace(' ', '') if any(i in inp_str[0].upper() for i in letters): let = inp_str[0].upper() color_str = inp_str[1:] ## 2 Get RGB if it exists if (re.match(rgb, color_str)): if all(0 <= int(group) <= 255 for group in re.match(rgb, color_str).groups()): color = re.match(rgb, color_str).groups() cur_r = color[0] cur_g = color[1] cur_b = color[2] print('rgb') ## 3 Get Hex if exists elif re.search(r'^#(?:[0-9a-fA-F]{3}){1,2}$', color_str): color = webcolors.hex_to_rgb(color_str) cur_r = color.red cur_g = color.green cur_b = color.blue print('hex') # 4 Get color from CSS3 name if it exists elif color_str in webcolors.CSS3_NAMES_TO_HEX: color = webcolors.name_to_rgb(color_str) cur_r = color.red cur_g = color.green cur_b = color.blue print('name') post_data = [('method', 'POST'), ('letter', 'M'), ('cur_r', '255'), ('cur_g', '0'), ('cur_b', '0')] # a sequence of two element tuples req = requests.porst() req.method = "POST" create_post(post_data)