def __init__(self, definition, opacity=None): if not isinstance(definition, str): raise Exception("Unable to parse color %s" % definition) color_definition = definition.lower() self.opacity = float(1) if color_definition == "transparent": self.opacity = 0.0 self.value = '#000000' elif color_definition.startswith("rgb("): m = RGB_PARSER.match(color_definition) color_rgb = (int(m.group(1)), int(m.group(2)), int(m.group(3))) self.value = webcolors.rgb_to_hex(color_rgb) elif color_definition.startswith("rgba("): m = RGBA_PARSER.match(color_definition) color_rgb = (int(m.group(1)), int(m.group(2)), int(m.group(3))) self.value = webcolors.rgb_to_hex(color_rgb) self.opacity = float(m.group(4)) elif color_definition.startswith("#"): self.value = webcolors.normalize_hex(color_definition) else: self.value = webcolors.rgb_to_hex( webcolors.html5_parse_legacy_color(color_definition)) if opacity is not None: self.opacity = opacity
def conversionRGB2HEX(): engine = create_engine( 'postgresql://*****:*****@144.92.235.105:5432/usxp_deliverables') df = pd.read_csv( filepath_or_buffer= 'C:\\Users\\Bougie\\Desktop\\misc\\colormaps\\suitability_RdYlGn_8.clr', delimiter=' ', header=None) print df df.drop(df.columns[0], axis=1, inplace=True) yo = list(df.itertuples(index=False, name=None)) df = getPGtable() for index, row in df.iterrows(): print index print yo[index] print wc.rgb_to_hex(yo[index]) print row['class'], row['hex'] df.at[index, 'hex'] = wc.rgb_to_hex(yo[index]) print 'fdfdf', df df.to_sql(name='colormap_suitability', con=engine, schema='suitability', index=False, if_exists='replace')
def getColor(args): if "rgb" in args: index = args.index("rgb") + 1 rgbs = [int(x) for x in args[index:index+3]] color = webcolors.rgb_to_hex(rgbs) elif len(args) == 1: if args[0][0] == "#": color = args[0] else: # Name? try: color = webcolors.name_to_hex(args[0]) # No idea what it is then... except: color = None else: # Multiple things in the background line surely one of them is hex or a word for a in args: if "#" == a[0]: try: # To confirm it is a real hex, convert to RGB and back color = webcolors.rgb_to_hex( webcolors.hex_to_rgb(a)) break except: pass else: try: color = webcolors.name_to_hex(a) break except: pass color = None return color
def get_formatting_style(self, book): format_dict = self.format if self._num_format: format_dict["num_format"] = self._num_format if self._style: c = self._style["background_color"] if c.alpha == 1.0: format_dict["bg_color"] = rgb_to_hex((c.red * 255, c.green * 255, c.blue * 255)) if self._style["font_weight"] > 400: format_dict["bold"] = True format_dict["font_size"] = self._style["font_size"] if self._style["font_style"] == "italic": format_dict["italic"] = True c = self._style["color"] if c.alpha == 1.0: format_dict["font_color"] = rgb_to_hex((c.red * 255, c.green * 255, c.blue * 255)) if len(self._style["font_family"]) > 1: format_dict["font_family"] = self._style["font_family"][0] if self._style["text_align"] != "-weasy-start": format_dict["align"] = self._style["text_align"] for side in ("left", "top", "right", "bottom"): width = self._style["border_left_width"] if width == 0: continue format_dict[side] = 1 ##set width c = self._style["border_left_color"] format_dict["%s_color" % side] = rgb_to_hex((c.red * 255, c.green * 255, c.blue * 255)) format_dict["valign"] = self._style["vertical_align"] if format_dict["valign"] not in ("top", "bottom"): format_dict["valign"] = "vcenter" return book.add_format(format_dict)
def get_formatting_style(self, book): format_dict = self.format if self._num_format: format_dict['num_format'] = self._num_format if self._style: c = self._style['background_color'] if c.alpha == 1.0: format_dict['bg_color'] = rgb_to_hex( (c.red * 255, c.green * 255, c.blue * 255)) if self._style['font_weight'] > 400: format_dict['bold'] = True format_dict['font_size'] = self._style['font_size'] if self._style['font_style'] == 'italic': format_dict['italic'] = True c = self._style['color'] if c.alpha == 1.0: format_dict['font_color'] = rgb_to_hex( (c.red * 255, c.green * 255, c.blue * 255)) if len(self._style['font_family']) > 1: format_dict['font_family'] = self._style['font_family'][0] if self._style['text_align'] != '-weasy-start': format_dict['align'] = self._style['text_align'] for side in ('left', 'top', 'right', 'bottom'): width = self._style['border_left_width'] if width == 0: continue format_dict[side] = 1 ##set width c = self._style['border_left_color'] format_dict['%s_color' % side] = rgb_to_hex( (c.red * 255, c.green * 255, c.blue * 255)) format_dict['valign'] = self._style['vertical_align'] if format_dict['valign'] not in ('top', 'bottom'): format_dict['valign'] = 'vcenter' return book.add_format(format_dict)
def randomColour(colourInp, num_bars, shadedBars): if(shadedBars is True): base = colourInp rgbl = webcolors.name_to_rgb(base) chng = 0 if base in ['red', 'green', 'blue']: for i, val in enumerate(rgbl): if val > 0: chng = i segment = int(max(rgbl)/num_bars) colour_list = [webcolors.rgb_to_hex(rgbl)] rgbl = list(rgbl) for vals in range(num_bars-1): rgbl[chng] = rgbl[chng] - segment webcolors.IntegerRGB(rgbl[0], rgbl[1], rgbl[2]) colour_list.append(webcolors.rgb_to_hex(rgbl)) else: colour_list = [] for base in colourInp: rgbl = webcolors.name_to_rgb(base) colour_list.append(webcolors.rgb_to_hex(rgbl)) return colour_list
def __init__(self, name='goldpads', gds_layer=0, gds_datatype=0, description='Gold pads liftoff', inverted=False, color=None, alpha=0.6): self.name = name self.gds_layer = gds_layer self.gds_datatype = gds_datatype self.description = description self.alpha = alpha try: if color is None: # not specified self.color = None elif np.size(color) == 3: # in format (0.5, 0.5, 0.5) self.color = webcolors.rgb_to_hex( np.array(np.array(color) * 255, dtype=int)) elif color[0] == '#': # in format #1d2e3f self.color = webcolors.hex_to_rgb(color) self.color = webcolors.rgb_to_hex(self.color) else: # in named format 'gold' self.color = webcolors.name_to_hex(color) except: raise ValueError("""[PHIDL] Layer() color must be specified as a 0-1 RGB triplet, (e.g. [0.5, 0.1, 0.9]), an HTML hex color (e.g. #a31df4), or a CSS3 color name (e.g. 'gold' or see http://www.w3schools.com/colors/colors_names.asp ) """) Layer.layer_dict[(gds_layer, gds_datatype)] = self
def createRectangleTarget(): color = (random.randint(10, 255), random.randint(10, 255), random.randint(10, 255)) hexColors = ["rectangle", webcolors.rgb_to_hex(color)] W, H = random.randint(400, 600), random.randint(400, 600) shape_img = Image.new('RGBA', (W, H), (color[0], color[1], color[2], 0)) draw = ImageDraw.Draw(shape_img) draw.rectangle((0, 0, W, H), fill=(color[0], color[1], color[2])) font = ImageFont.truetype("Helvetica.ttf", random.randint(250, 450)) # draw.text((x, y),"Sample Text",(r,g,b)) color = (random.randint(10, 255), random.randint(10, 255), random.randint(10, 255)) msg = random.choice(string.ascii_letters) hexColors.append(msg) hexColors.append(webcolors.rgb_to_hex(color)) w, h = draw.textsize(msg, font=font) draw.text(((W - w) / 2, (H - h) / 2), msg, (color[0], color[1], color[2]), font=font) #shape_img= shape_img.rotate(random.randint(0,360)) shape_img.save('test.png', 'PNG') return hexColors
def hex_convert(self): # ---- Fetch values ---- # conversion_type = config.get('main', 'Convert_Type') entries = [self.r_entry, self.g_entry, self.b_entry] get_entries = [ self.r_entry.get(), self.g_entry.get(), self.b_entry.get() ] # --- Check all RGB value validity --- # for e in entries: if incorrect_entry_test(e.get(), conversion_type): e.config(background=entry_bg) else: e.config(background="red") # If there is no empty box... if '' not in get_entries: # Use conversion type... # Conversion type sRGB [0,1] if conversion_type == "sRGB [0,1]": rgb_nonlin = get_entries_convert(get_entries, conversion_type) rgb_linear = LSRGBtoSRGB8(rgb_nonlin) hexvals = rgb_to_hex(rgb_linear) self.hex_box_value.set( hexvals.upper()) # Sets hex box value self.colour_preview.config( {"background": self.hex_box.get()}) # Adds colour to side box # Conversion type sRGB [0,1] if conversion_type == "sRGB8 [0,255]": rgb_nonlin = get_entries_convert(get_entries, conversion_type) hexvals = rgb_to_hex(rgb_nonlin) self.hex_box_value.set( hexvals.upper()) # Sets hex box value self.colour_preview.config( {"background": self.hex_box.get()}) # Adds colour to side box if conversion_type == "sRGB' [0,1]": rgb_nonlin = get_entries_convert(get_entries, conversion_type) yeet = NLSRGBtoSRGB8(rgb_nonlin) hexvals = rgb_to_hex(yeet) self.hex_box_value.set( hexvals.upper()) # Sets hex box value self.colour_preview.config( {"background": self.hex_box.get()}) # Adds colour to side box
def find_contrast(soup, URL, first_bool, stylesheetName, fullCSSStyleLink, rule, socketio): TYPE = "accessibility for colorblind users" SEVERITY = "warning" inaccessible_colors = [] if first_bool: create_print_json(TYPE, socketio) cssString = rule.cssText if rule.style['color'] and rule.style['background-color']: color = str(rule.style['color']) backgroundColor = str(rule.style['background-color']) # dumb edge case if color == "#FFF" or color == "#fff": color = "#FFFFFF" if backgroundColor == "#FFF" or backgroundColor == "#fff": backgroundColor = "#FFFFFF" # get them both in hex if color.startswith("#") and len(str(color)) == 7: colorHex = color elif not color.startswith("rgb"): colorHex = webcolors.name_to_hex(color) else: # rgb colorHex = webcolors.rgb_to_hex(color) if backgroundColor.startswith("#") and len(str(backgroundColor)) == 7: backgroundHex = backgroundColor elif not backgroundColor.startswith("rgb"): backgroundHex = webcolors.name_to_hex(backgroundColor) else: backgroundHex = webcolors.rgb_to_hex(backgroundColor) # now we have them both in hex val = distinguish_hex(colorHex, backgroundHex) if val == []: # no issue return True else: text = "Bad contrast ratio between: " + color + " and " + backgroundColor + ". Consider changing them to similar colors: " + str( val) create_error_json(TYPE, SEVERITY, fullCSSStyleLink, text=text, meta=rule.cssText, socketio=socketio) return False
def _format_color(color, prog='tikz'): """Encode color in syntax for given program. @type color: - C{str} for single color or - C{dict} for weighted color mix @type prog: 'tikz' or 'dot' """ if isinstance(color, basestring): return color if not isinstance(color, dict): raise Exception('color must be str or dict') if prog is 'tikz': s = '!'.join([k + '!' + str(v) for k, v in color.iteritems()]) elif prog is 'dot': t = sum(color.itervalues()) try: import webcolors # mix them result = np.array((0.0, 0.0, 0.0)) for c, w in color.iteritems(): result += w / t * np.array(webcolors.name_to_rgb(c)) s = webcolors.rgb_to_hex(result) except: logger.warn('failed to import webcolors') s = ':'.join([k + ';' + str(v / t) for k, v in color.iteritems()]) else: raise ValueError('Unknown program: ' + str(prog) + '. ' "Available options are: 'dot' or 'tikz'.") return s
def conform_figure(figure, color_scheme): ''' Conforms given figure to use given color scheme. Args: figure (dict): Plotly figure. color_scheme (dict): Color scheme dictionary. Returns: dict: Conformed figure. ''' # create hex to hex lut lut = {} for key, val in cfg.COLOR_SCHEME.items(): if key in color_scheme: lut[val] = color_scheme[key] # rgba? to hex --> coerce to standard colors --> coerce with color_scheme figure = rpb.BlobETL(figure) \ .set( predicate=lambda k, v: isinstance(v, str) and 'rgb' in v, value_setter=lambda k, v: webcolors.rgb_to_hex(parse_rgba(v)[:3]).upper()) \ .set( predicate=lambda k, v: isinstance(v, str), value_setter=lambda k, v: COLOR_COERCION_LUT.get(v, v)) \ .set( predicate=lambda k, v: isinstance(v, str), value_setter=lambda k, v: lut.get(v, v)) \ .to_dict() return figure
async def set_rgb(self, rgb_color: tuple, push=False): color = webcolors.rgb_to_hex(rgb_color) self.data[ATTR_RGB_COLOR] = color if push: await self._post_state({ ATTR_RGB_COLOR: color, })
def parse_color(color): c = str(color).lower().strip() for k, v in _COLOR_FILTERS.items(): c = c.replace(k, v) hex = None try: hc = '#' + c if not c.startswith('#') else c rgb = webcolors.hex_to_rgb(hc) if rgb: return hc.upper() except Exception: # probably not a hex already pass try: hex = webcolors.name_to_hex(c) except Exception: pass if '%' in c: try: hex = webcolors.rgb_percent_to_hex( (int(x.strip()) for x in c.split(','))) except Exception: pass else: try: hex = webcolors.rgb_to_hex((int(x.strip()) for x in c.split(','))) except Exception: pass return hex
def autostyle(topic_name, topic_index): img, imgurl = magic_background.magic_background(topic_name) ct, p, b, t = color_knowledge(img, imgurl) print(p) #Will want the colors from the palette representable in HTML-friendly hex form, so do that here: colors = [] for rgbcolor in p: colors.append(rgb_to_hex(rgbcolor)) ''' #ti means tackiest_index ti = min(range(len(t)), key=t.__getitem__) #Doing a little cheat to get the brightness extremes; temporarily taking out the ti (so bi =/= ti) but then afterward the tackiest color will go back into the brightness measure... Or not, depending on list b will even get used after this function. bti = b[ti] b[ti] = (min(b) + max(b)) / 2 #lazy, not watertight way to hopefully ensure that b[ti] won't be considered the brightest OR the darkest... #bi means brightest_index bi = b.index(max(b)) #di means darkest_index di = b.index(min(b)) ''' #-------------------------------------------- # Redoing it all -- hopefully get better colors here: ti, bi, di = colorbychance(ct, p, b, t) #Now, put it in the table :) new_style = Style(title=topic_name, topic=topic_index, imgurl=imgurl, colors=np.array2string(np.array(colors)), tibidi=np.array2string(np.array([ti, bi, di]))) db.session.add(new_style) db.session.commit()
def generate_pixels(image_id): image_created = ImageModel.query.get(image_id) if not image_created: return jsonify({'message': 'Image not found'}), 404 if image_created.user != g.current_user: return jsonify({'message': 'Unauthorized'}), 401 # set the url and pixel size url = image_created.url pixelSize = image_created.difficulty.pixelSize # manipulate the image image = image_manipulation(url, pixelSize) # set the pixels array generated_pixels = create_pixels(image) for pixel in generated_pixels: pixel, errors = pixel_schema.load({ 'color': rgb_to_hex(pixel), 'ticked': False }) if errors: return jsonify(errors), 422 pixel.image = image_created pixel.save() return image_schema.jsonify(image_created), 202
def draw_symbols(self, img, embroidery_img, aspect_ratio, data_color): # print(every) width, height = len(img[0]), len(img) # count_x_symbols, count_y_symbols = int(width / every[0]), int(height / every[1]) scaleFont = 0.5 thickness = 1 for y in range(0, len(embroidery_img[0])): for x in range(0, len(embroidery_img)): hex_color = webcolors.rgb_to_hex(embroidery_img[x][y]).lower() try: ch = data_color[hex_color][1] except KeyError: ch = '?' size = cv2.getTextSize(ch, cv2.FONT_HERSHEY_PLAIN, scaleFont, thickness) x_pos = y * aspect_ratio[0] + int(size[0][0] / 2) y_pos = x * aspect_ratio[1] + int(size[0][1] / 2) + int( aspect_ratio[1] / 2) cv2.putText(img, ch, (x_pos, y_pos), cv2.FONT_HERSHEY_PLAIN, scaleFont, 127)
def _format_color(color, prog='tikz'): """Encode color in syntax for given program. @type color: - C{str} for single color or - C{dict} for weighted color mix @type prog: 'tikz' or 'dot' """ if isinstance(color, basestring): return color if not isinstance(color, dict): raise Exception('color must be str or dict') if prog is 'tikz': s = '!'.join([k + '!' + str(v) for k, v in color.iteritems()]) elif prog is 'dot': t = sum(color.itervalues()) try: import webcolors # mix them result = np.array((0.0, 0.0, 0.0)) for c, w in color.iteritems(): result += w/t * np.array(webcolors.name_to_rgb(c)) s = webcolors.rgb_to_hex(result) except: logger.warn('failed to import webcolors') s = ':'.join([k + ';' + str(v/t) for k, v in color.iteritems()]) else: raise ValueError('Unknown program: ' + str(prog) + '. ' "Available options are: 'dot' or 'tikz'.") return s
def random_stars(num): for a in range(num): c = randint(0, 55) color = rgb_to_hex([c, c, c]) x = randint(0, 700) y = randint(0, 700) canvas.create_rectangle(x, y, x + 2, y + 2, fill=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 filled_contours(p,cn,simplify_threshold = .01): """Creates a bokeh plot of filled contours Args: p (bokeh.plotting.Figure): Bokeh plot instance cn (contours): Contours generated from plt.contourf() simplify_threshold (Optional[float]): Resolution of the output contours in screenspace. Defaults to .01 Returns: None """ for cc in cn.collections: face_color = np.array(cc.get_facecolor()[0]) color = rgb_to_hex(tuple((255*face_color[:-1]).round().astype(int))) alpha = face_color[-1] for path in cc.get_paths(): path.simplify_threshold = simplify_threshold polygons = path.to_polygons() if len(polygons) == 1: p.patch(polygons[0][:,0], polygons[0][:,1], line_alpha = alpha, line_color = color, fill_alpha = alpha, fill_color = color) else: vertices = np.vstack(polygons) graph = triangulated_graph(polygons) islands = create_islands(graph) poly_graph = merge_islands(islands,polygons) merged_path = get_merged_path(poly_graph) p.patch(vertices[merged_path][:,0],vertices[merged_path][:,1], line_alpha = 0, line_color = color, fill_alpha = alpha, fill_color = color)
def get_complementary(rgb): """ Gets complementary color from rgb color then returns bgr code. Parameters: rgb(tuple): rgb code to get complementary color. Returns: comp2rgb(tuple): rgb code that is the complementary of param rgb """ #change rgb to hex color = webcolors.rgb_to_hex(rgb) # strip the # from the beginning color = color[1:] # convert the string into hex color = int(color, 16) comp_color = 0xFFFFFF ^ color # convert the color back to hex by prefixing a # comp_color = "#%06X" % comp_color #make hex to rgb comp2rgb = webcolors.hex_to_rgb(comp_color) return comp2rgb
def draw(results): count = len(results.keys()) slice = 100 width = count * slice height = 500 dx = slice dy = height / 2 x = 0 y = 0 im = Image.new("RGBA", (width, height)) canvas = ImageDraw.Draw(im) for hex, closest in results.items(): rainbow = map(webcolors.hex_to_rgb, (hex, closest[0])) for rgb in rainbow: h = webcolors.rgb_to_hex(rgb) canvas.rectangle((x, y, (x + dx), (y + dy)), fill=rgb) canvas.text((x + 10, y + 10), h, fill=(255,255,255)) y += dy x += dx y = 0 return im
def say_hello(**payload): global my_id data = payload['data'] #print(data) text = data.get('text', '') if not 'subtype' in data and ('<@' + my_id + '>' in text or data['channel'].startswith('D')): text_parts = text.split(' ') if len(text_parts) > 0: try: rgb = webcolors.html5_parse_legacy_color(text_parts[-1]) print(str(rgb)) #print(str(payload['timestamp'])) conn = http.client.HTTPConnection("127.0.0.1:8080") conn.request("GET","/vars/col?set=" + str(int(webcolors.rgb_to_hex((rgb.blue, rgb.green, rgb.red))[1:],16))) r1 = conn.getresponse() conn.close() #payload['web_client'].chat_postMessage( # channel=data['channel'], # text="Set color to: " + webcolors.rgb_to_hex((rgb.red, rgb.green, rgb.blue)), # thread_ts=data['ts'] #) payload['web_client'].reactions_add( channel=data['channel'], name='thumbsup', timestamp=data['ts'] ) except: print("Error: " + str(sys.exc_info()[0]))
def set_dict(d, path, value, color_paths=set()): ''' on dictionary d set the entry in the given path to value ''' is_color = False #if '#text' in path : # breakpoint() for key in path[:-1]: # color case, last path element is color dim if key in COLOR_ATTRS: is_color = True break d = d[key] if not is_color: attr = path[-1] if attr.startswith('#'): value = str(int(value)) d[attr] = value # color case else: attr = path[-2] color_dim = path[-1] if path[:-1] not in color_paths: color_paths.add(path[:-1]) rgb = [0, 0, 0] else: rgb = list(webcolors.hex_to_rgb(d[attr])) rgb[color_dim] = int(rgb[color_dim] + value) color = webcolors.rgb_to_hex(rgb) d[attr] = color
def effect_lightning(effectSettings, strength, songTime, noteTime): devs = [ L9["device/veryLow1"], L9["device/veryLow2"], L9["device/veryLow3"], L9["device/veryLow4"], L9["device/veryLow5"], L9["device/backlight1"], L9["device/backlight2"], L9["device/backlight3"], L9["device/backlight4"], L9["device/backlight5"], L9["device/down2"], L9["device/down3"], L9["device/down4"], L9["device/hexLow3"], L9["device/hexLow5"], L9["device/lip1 5"], L9["device/postL1"], L9["device/postR1"], ] out = {} col = rgb_to_hex([255 * strength] * 3) for i, dev in enumerate(devs): n = noise(songTime * 8 + i * 6.543) if n > 0.4: out[(dev, L9["color"])] = col return out
def color_attr(gender): csv_path = os.path.join(csv_dir, gender + '.csv') csv_file = open(csv_path, 'r') csv_color_path = os.path.join(csv_dir, gender + '_color.csv') csv_color_file = open(csv_color_path, 'w') writer = csv.writer(csv_color_file, delimiter=',') reader = csv.reader(csv_file, delimiter=',') for row in reader: index = int(row[0]) print(index) img_url = row[5] response = requests.get(img_url) image = response.content f = open(img_path, 'wb') f.write(image) f.close() im = cv2.imread(img_path) colors = color_recognition(im) while len(colors) == 0: colors = color_recognition(im) print(colors) temp = [] temp.append(index) for color in colors: rgb = (color[2], color[1], color[0]) hex = webcolors.rgb_to_hex(rgb) temp.append(hex) colors = temp writer.writerow(temp) os.remove(img_path)
def make_prediction(): if request.method == 'POST': file = request.files['image'] if not file: return render_template('index.html', label="No file") #convert string data to numpy array npimg = np.fromstring(file.read(), np.uint8) # convert numpy array to image img = cv2.imdecode(npimg, cv2.IMREAD_COLOR) img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) image = img.reshape((img.shape[0] * img.shape[1], 3)) clt = KMeans(n_clusters=3) clt.fit(image) hist = centroid_histogram(clt) hex_ = [ rgb_to_hex([floor(i) for i in c]) for c in clt.cluster_centers_.tolist() ] viz_data = {'colors': hex_, 'dist': hist.tolist()} return render_template('index.html', bob=hex_)
def getAvgHex(path): im = Image.open(path) smaller_img = im.resize((NEWSIZE, NEWSIZE)) size = smaller_img.size[0] pix = smaller_img.load() all_rgb_values = [] for x in range(0, size): for y in range(0, size): all_rgb_values.append(pix[x, y]) red_list = [] green_list = [] blue_list = [] for index in range(0, size): red_list.append(all_rgb_values[index][0]) green_list.append(all_rgb_values[index][1]) blue_list.append(all_rgb_values[index][2]) red_avg = numpy.mean(red_list) green_avg = numpy.mean(green_list) blue_avg = numpy.mean(blue_list) average_color = (int(red_avg), int(green_avg), int(blue_avg)) return webcolors.rgb_to_hex(average_color)
def color_dominant(image): def get_approx_color(hex_color): orig = wc.hex_to_rgb(hex_color) similarity = {} for hex_code, color_name in wc.CSS3_HEX_TO_NAMES.items(): approx = wc.hex_to_rgb(hex_code) similarity[color_name] = sum(np.subtract(orig, approx)**2) return min(similarity, key=similarity.get) def get_color_name(hex_color): try: return wc.hex_to_name(hex_color) except ValueError: return get_approx_color(hex_color) # https://stackoverflow.com/questions/50899692/most-dominant-color-in-rgb-image-opencv-numpy-python # https://stackoverflow.com/questions/44354437/classify-users-by-colors data = np.reshape(image, (-1, 3)) data = np.float32(data) criteria = (cv2.TERM_CRITERIA_EPS + cv2.TERM_CRITERIA_MAX_ITER, 10, 1.0) flags = cv2.KMEANS_RANDOM_CENTERS compactness, labels, centers = cv2.kmeans(data, 1, None, criteria, 10, flags) bgr_ = centers[0].astype(np.int32) rgb_ = bgr_ rgb_[0], rgb_[2] = bgr_[2], bgr_[0] # convert BGR to RGB hex_ = wc.rgb_to_hex(tuple(rgb_)) return get_color_name(hex_)
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 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 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 drawColumn(self, x): iImageX = self.getImageX(x) iPreviewX = self.getPreviewX(x) iPreviewXend = self.getPreviewX(x + 1) for y in range(0, self.iPixels): try: colour = self.aPixels[y][iImageX] except: colour = (0, 0, 0) if colour != (0, 0, 0): color = str(webcolors.rgb_to_hex(colour)) self.canPreview.create_rectangle( iPreviewX, (y * self.motePixelInSceenPixels), iPreviewXend, (y * self.motePixelInSceenPixels) + self.motePixelInSceenPixels, width=0, fill=color) if self.bPaintBlack & (self.currentColumn > 0 and self.currentColumn < self.graphWidth): self.canPreview.create_rectangle(iPreviewX, (0), iPreviewXend, self.motePixelInSceenPixels * 5, width=0, fill="#0F0")
def index(request): global shuiguole img_path = '/Users/evnw/Downloads/image.png' jud = True while jud or not request.method == "POST": try: im_temp = cv2.imread(img_path)[::-1] jud = False except: time.sleep(1) #im = Image.open(StringIO(request.FILES['im']['content'])) #im.save("D:/code", "PNG") #getColors = '#ffffff' #getClothes = None #detector = recognition.initialize() #im_crop = recognition.yolo_detect(img_path, detector) im_crop = cv2.imread(img_path) colors_BGR = crop_color_rec.color_detection(im_crop) colors_hex = [] for BGR in colors_BGR: colors_hex.append(webcolors.rgb_to_hex((BGR[2], BGR[1], BGR[0]))) jsonDec = json.decoder.JSONDecoder() allColors = color.objects.all() getColors = getFrom(colors_hex[0], allColors) print(getColors) print(len(getColors[0].getColors())) allClothes = pic.objects.all() getClothes = [] for colorObj in getColors: # for colorObj in colorObjList: ccolor = jsonDec.decode(colorObj.combination) for colorOb in ccolor: getClothes += getClothesFrom(colorOb, allClothes) if request.method == "POST" or shuiguole: print('postttttttttttttttttt') shuiguole = True getClothes = list(set(getClothes)) print(getClothes) #selectedColor = getColorData(request) os.remove(img_path) return render(request, 'index.html', context={ 'color_all': getColors, 'clothes': getClothes }) else: print('eeeeelllllllllllllllllll') return render(request, 'index.html', context={ 'color_all': getColors, 'clothes': getClothes })
def HexColors(pixels): hexpixels = [] for pixel in pixels: if pixel is None: hexpixels.append(None) else: hexpixels.append(rgb_to_hex([int(i) for i in pixel])) return hexpixels
def __init__(self, gds_layer=0, gds_datatype=0, name='unnamed', description=None, inverted=False, color=None, alpha=0.6, dither=None): if isinstance(gds_layer, Layer): l = gds_layer # We were actually passed Layer(mylayer), make a copy gds_datatype = l.gds_datatype name = l.name description = l.description alpha = l.alpha dither = l.dither inverted = l.inverted gds_layer = l.gds_layer self.gds_layer = gds_layer self.gds_datatype = gds_datatype self.name = name self.description = description self.inverted = inverted self.alpha = alpha self.dither = dither try: if color is None: # not specified self.color = None elif np.size(color) == 3: # in format (0.5, 0.5, 0.5) self.color = webcolors.rgb_to_hex( np.array(np.array(color) * 255, dtype=int)) elif color[0] == '#': # in format #1d2e3f self.color = webcolors.hex_to_rgb(color) self.color = webcolors.rgb_to_hex(self.color) else: # in named format 'gold' self.color = webcolors.name_to_hex(color) except: raise ValueError("""[PHIDL] Layer() color must be specified as a 0-1 RGB triplet, (e.g. [0.5, 0.1, 0.9]), an HTML hex color (e.g. #a31df4), or a CSS3 color name (e.g. 'gold' or see http://www.w3schools.com/colors/colors_names.asp ) """) Layer.layer_dict[(gds_layer, gds_datatype)] = self
def effect_Strobe(effectSettings, strength, songTime, noteTime): rate = 2 duty = 0.3 offset = 0 f = ((songTime + offset) * rate) % 1.0 c = (f < duty) * strength col = rgb_to_hex([c * 255, c * 255, c * 255]) return {(L9["device/colorStrip"], L9["color"]): Literal(col)}
def clamp_hash_token(intok, high): old = hexr.findall(intok.value) for match in old: color = webcolors.hex_to_rgb("#" + match) mean = sum(color) / len(color) if high: if mean > 150: color = tuple((max(255 - cval, 0) for cval in color)) new = webcolors.rgb_to_hex(color) intok.value = intok.value.replace(match, new) else: if mean < 100: color = tuple((min(cval, 100) for cval in color)) new = webcolors.rgb_to_hex(color).replace("#", "") intok.value = intok.value.replace(match, new) return intok
def clamp_hash_token(intok, high): old = hexr.findall(intok.value) for match in old: color = webcolors.hex_to_rgb("#"+match) mean = sum(color)/len(color) if high: if mean > 150: color = tuple((max(255-cval, 0) for cval in color)) new = webcolors.rgb_to_hex(color) intok.value = intok.value.replace(match, new) else: if mean < 100: color = tuple((min(cval, 100) for cval in color)) new = webcolors.rgb_to_hex(color).replace("#", "") intok.value = intok.value.replace(match, new) return intok
def effect_Strobe(effectSettings, strength, songTime, noteTime): rate = 2 duty = .3 offset = 0 f = (((songTime + offset) * rate) % 1.0) c = (f < duty) * strength col = rgb_to_hex([int(c * 255), int(c * 255), int(c * 255)]) return {(L9['device/colorStrip'], L9['color']): Literal(col)}
def rgb_to_hex(rgb_triplet): """ Convert a 3-tuple of integers, suitable for use in an rgb() color triplet, to a normalized hexadecimal value for that color. :param rgb_triplet: rgb_triplet (3-tuple of int) – The integer rgb() triplet to normalize. :returns: Hexadecimal color """ return webcolors.rgb_to_hex(hex_color)
def rgbstring_to_hex(value): """ Transform a string like rgb(199,12,15) into a wdColor format used by word :param value: A string like rgb(int,int,int) :return: An integer representation that Word understands """ left, right = value.find("("), value.find(")") values = value[left + 1:right].split(",") rgblist = [int(v.strip()) for v in values] return webcolors.rgb_to_hex(rgblist)
def test_rgb_to_hex(self): """ Test conversion from integer RGB triplet to hex. """ test_pairs = (((255, 255, 255), u'#ffffff'), ((0, 0, 128), u'#000080'), ((218, 165, 32), u'#daa520')) for triplet, hex_value in test_pairs: self.assertEqual(hex_value, webcolors.rgb_to_hex(triplet))
def _parseColor(self, val): """ Parse a color definition. Returns a color in hex format, 'inherit', or 'none'. 'none' means that the geometry is not to be rendered. See: http://www.w3.org/TR/SVG11/painting.html#SpecifyingPaint """ # http://www.w3.org/TR/SVG11/color.html # http://www.w3.org/TR/2008/REC-CSS2-20080411/syndata.html#color-units if val[0] == " ": val = val.strip() if val[0] == '#': return normalize_hex(val) elif val.startswith('rgba'): floats = parseFloats(val[5:-1]) if len(floats) == 4: log.warn("opacity in rgba is ignored, \ use stroke-opacity/fill-opacity instead") return rgb_to_hex(tuple(floats[:3])) elif val.startswith('rgb'): floats = parseFloats(val[4:-1]) if len(floats) == 3: return rgb_to_hex(tuple(floats)) elif val == 'none': # 'none' means the geometry is not to be filled or stroked # http://www.w3.org/TR/SVG11/painting.html#SpecifyingPaint return 'none' elif val.startswith('hsl'): log.warn("hsl/hsla color spaces are not supported") elif val.startswith('url'): log.warn("defs are not supported"); elif val in css3_names_to_hex: # named colors return css3_names_to_hex[val] elif val in ['currentColor', 'inherit']: return 'inherit' else: log.warn("invalid color, skipped: " + str(val)) return 'inherit'
def colormap(cats, mplmap='auto', categorical=None): """ Map a series of categories to hex colors, using a matplotlib colormap Generates both categorical and numerical colormaps. Args: cats (Iterable): list of categories or numerical values mplmap (str): name of matplotlib colormap object categorical (bool): if True, interpret this data as categorical. If False, interpret the data as numerical values (data must be convertible to float) Returns: List[str]: List of hexadecimal RGB color values in the in the form ``'#000102'`` """ # Should automatically choose the right colormaps for: # categorical data # sequential data (low, high important) # diverging data (low, mid, high important) global DEF_SEQUENTIAL from matplotlib import cm if hasattr(cm, 'inferno'): DEF_SEQUENTIAL = 'inferno' else: DEF_SEQUENTIAL = 'BrBG' # strip units units = None # TODO: build a color bar with units if hasattr(cats[0], 'magnitude'): arr = u.array(cats) units = arr.units cats = arr.magnitude is_categorical = False else: is_categorical = not isinstance(cats[0], float) if categorical is not None: is_categorical = categorical if is_categorical: values = _map_categories_to_ints(cats) if mplmap == 'auto': mplmap = DEF_CATEGORICAL else: values = np.array(map(float, cats)) if mplmap == 'auto': mplmap = DEF_SEQUENTIAL rgb = _cmap_to_rgb(mplmap, values) hexcolors = [webcolors.rgb_to_hex(np.array(c)) for c in rgb] return hexcolors
def generate_color(): # TODO - this might not be the optimal way - copy is expensive colors_to_generate = copy.copy(COLORBREWER_COLORS) colors_used = [] while True: try: color = colors_to_generate.pop(0) colors_used.append(color) except IndexError: new_colors = get_new_colors(colors_used) colors_to_generate = new_colors colors_used = [] yield webcolors.rgb_to_hex(color)
def extract_and_save_colors(image_file, Extractor): """ Given image file function extracts top colors from pallette and persists them in database saving: color name, (r, g, b) info and hex color name. """ results = [] mode = settings.IMAGE_COLOR_PERSIST_MODE helper = Extractor(image_file.source.file) palette = helper.get_palette(settings.IMAGE_VITAL_COLORS_COUNT) # if we are in hex mode # we are limiting results to unique r, g, b triplets that occur if mode == HEX_MODE: palette = [_ for _ in set(palette)] for index, triplet in enumerate(palette): hex_ = webcolors.rgb_to_hex(triplet) actual, closest = get_color_name(triplet) name = actual if actual else closest priority = index + 1 color = Color(**{ 'r': triplet[0], 'g': triplet[1], 'b': triplet[2], 'hex': hex_.lower(), 'name': name, 'image': image_file, 'priority': priority }) results.append(color) # if we are in name mode # we are limiting results to unique color names that occur if mode == NAME_MODE: colors, names = [], set() for c in results: if not c.name in names: names.add(c.name) colors.append(c) else: colors = results Color.objects.bulk_create(colors) return colors
def hash_color_tint(string, rgb_tint): h = hashlib.new("sha1") h.update(string) hex_color = "#{}".format(str(h.hexdigest()[:6])) rgb_color = webcolors.hex_to_rgb(hex_color) def avg2(a, b): return (a + b) / 2 rgb_color_tinted = (avg2(rgb_color[0], rgb_tint[0]), avg2(rgb_color[1], rgb_tint[1]), avg2(rgb_color[2], rgb_tint[2])) return webcolors.rgb_to_hex(rgb_color_tinted)
def emitDit(dit_length,color,dah=False): ''' Lights please! Either a dit or a dah (3*time of dit) ''' command = BLINK_TOOL_PATH + ' --rgb "'+webcolors.rgb_to_hex(color)+'" -m 0 ' print((command), end=' ') output = subprocess.call(command, stdout=subprocess.PIPE, shell=True) if dah==True: print("(dah)") time.sleep(float(dit_length*3)/1000) else: print("(dit)") time.sleep(float(dit_length)/1000) command_off = BLINK_TOOL_PATH + " --off -m 0" output = subprocess.call(command_off, stdout=subprocess.PIPE, shell=True) waitEmit(dit_length)
def get_color_range(num_colors): colors=[] if num_colors > 0: start = 0 stop = 360 stop_d = 360. step = (stop/num_colors) increment = 120 for i in xrange(start, stop, step): hue = i/stop_d lightness = (50 + increment * 10)/100. saturation = (90 + increment * 10)/100. color_rgb = colorsys.hls_to_rgb(hue, lightness, saturation) color_hex = webcolors.rgb_to_hex(color_rgb) colors.append(color_hex) return colors
def actuate( self, color ): if isinstance(color, tuple) and len(color) == 3: color = rgb_to_hex( color ) if isinstance(color, basestring): # check if the color is already in ninja-api supported format # if not, we'll pass it through webcolors if not re.match( NINJA_COLOR_RE, color ): if not color.startswith( '#' ): color = name_to_hex( color ) # ninja-api compatible color spec color = color.lstrip( '#' ).upper() return super(RGBLEDNinjaDevice, self).actuate( color ) else: raise ValueError( 'Color value must be a valid css3 color name or an (r,g,b) tuple' )
def effect_lightning(effectSettings, strength, songTime, noteTime): devs = [L9['device/veryLow1'], L9['device/veryLow2'], L9['device/veryLow3'], L9['device/veryLow4'], L9['device/veryLow5'], L9['device/backlight1'], L9['device/backlight2'], L9['device/backlight3'], L9['device/backlight4'], L9['device/backlight5'], L9['device/down2'], L9['device/down3'], L9['device/down4'], L9['device/hexLow3'], L9['device/hexLow5'], L9['device/lip1 5'], L9['device/postL1'], L9['device/postR1']] out = {} col = rgb_to_hex([int(255 * strength)] * 3) for i, dev in enumerate(devs): n = noise(songTime * 8 + i * 6.543) if n > .4: out[(dev, L9['color'])] = col return out
def filled_contours(p, cn, simplify_threshold=0.01): """Creates a bokeh plot of filled contours Args: p (bokeh.plotting.Figure): Bokeh plot instance cn (contours): Contours generated from plt.contourf() simplify_threshold (Optional[float]): Resolution of the output contours in screenspace. Defaults to .01 Returns: None """ for cc in cn.collections: face_color = np.array(cc.get_facecolor()[0]) color = rgb_to_hex(tuple((255 * face_color[:-1]).round().astype(int))) alpha = face_color[-1] for path in cc.get_paths(): path.simplify_threshold = simplify_threshold polygons = path.to_polygons() if len(polygons) == 1: p.patch( polygons[0][:, 0], polygons[0][:, 1], line_alpha=alpha, line_color=color, fill_alpha=alpha, fill_color=color, ) else: vertices = np.vstack(polygons) graph = triangulated_graph(polygons) islands = create_islands(graph) poly_graph = merge_islands(islands, polygons) merged_path = get_merged_path(poly_graph) p.patch( vertices[merged_path][:, 0], vertices[merged_path][:, 1], line_alpha=alpha, line_color=color, fill_alpha=alpha, fill_color=color, )
def _get_color(self): self.nearest = None self.shortest_distance = 100 chosen_name = None for color_dict in (COLOURS, GREYSCALE): for name, color in color_dict.iteritems(): desired_rgb = color[0] target = RGBColor(*desired_rgb) cdist = target.delta_e(RGBColor(*self.rgb), method='cmc') if self.nearest is None or cdist < self.shortest_distance: self.nearest = name self.nearest_rgb = desired_rgb self.shortest_distance = cdist self.distance = cdist # print 'Checking', name (hue_lo, hue_hi) = color[1] if hue_lo > hue_hi: h = self.spin(self.hue) hue_lo = self.spin(hue_lo) hue_hi = self.spin(hue_hi) else: h = self.hue sat_range = color[2] or DEFAULT_SAT val_range = color[3] or DEFAUL_VAL if h in range(hue_lo, hue_hi + 1) and \ self.sat in range(sat_range[0], sat_range[1] + 1) and \ self.val in range(val_range[0], val_range[1] + 1): # TODO set up desirable hues, sat and b per named colour target = RGBColor(*desired_rgb) self.distance = cdist chosen_name = name self.nearest_hex = webcolors.rgb_to_hex(self.nearest_rgb) return chosen_name return None
def draw(palette, image): palette = colour.palette(palette) utils = colour.utils(palette) results = {} im = Image.open(image) for y in range(im.size[1]): for x in range(im.size[0]): old = im.getpixel((x, y)) hex = webcolors.rgb_to_hex(old) closest = utils.closest_colour(hex) new = webcolors.hex_to_rgb(closest[0]) im.putpixel((x, y), new) return im
def scale(value, strength): if isinstance(value, Literal): value = value.toPython() if isinstance(value, Decimal): value = float(value) if isinstance(value, basestring): if value[0] == "#": if strength == "#ffffff": return value r, g, b = hex_to_rgb(value) if isinstance(strength, Literal): strength = strength.toPython() if isinstance(strength, basestring): sr, sg, sb = [v / 255 for v in hex_to_rgb(strength)] else: sr = sg = sb = strength return rgb_to_hex([int(r * sr), int(g * sg), int(b * sb)]) elif isinstance(value, (int, float)): return value * strength raise NotImplementedError("%r,%r" % (value, strength))
def hexFromRgb(rgb): return rgb_to_hex(tuple([x // 4 for x in rgb]))
def literalColor(rnorm, gnorm, bnorm): return Literal(rgb_to_hex([int(rnorm * 255), int(gnorm * 255), int(bnorm * 255)]))
def render_keys(kb): keys = kb['keys'] meta = kb['meta'] max_x = 0 max_y = 0 for key in keys: max_x = max(key.x*56+key.width*56, max_x) max_y = max(key.y*56+key.height*56, max_y) spacing = 10 img = Image.new("RGB", (int(max_x - 3 + 2 * spacing), int(max_y - 3 + 2 * spacing)), meta['backcolor']) draw = ImageDraw.Draw(img) font_scale = 4 font_layer = Image.new("RGBA", (img.size[0]*font_scale, img.size[1]*font_scale)) draw_font = ImageDraw.Draw(font_layer) for key in keys: x = key.x*56 - 1.5 + spacing y = key.y*56 - 1.5 + spacing w = key.width*56 - 3 h = key.height*56 - 3 light_color = webcolors.rgb_to_hex([color * 1.2 for color in webcolors.hex_to_rgb(key.color)]) lightdark_color = webcolors.rgb_to_hex([color + 25 for color in webcolors.hex_to_rgb(key.color)]) dark_color = webcolors.rgb_to_hex([color - 25 for color in webcolors.hex_to_rgb(key.color)]) draw.rectangle([(x, y), (x+w, y+h)], fill=key.color, outline=dark_color) draw.rectangle([(x + 5, y + 5), (x+w-6, y+h-6)], fill=light_color, outline=dark_color) font = ImageFont.truetype("fonts/Roboto-Light.ttf", int((8+key.fontheight*1.5)*font_scale)) small_font = ImageFont.truetype("fonts/Roboto-Light.ttf", 8*font_scale) key.centerx = key.align&1; key.centery = key.align&2; key.centerf = key.align&4; for label in key.labels: text = HTMLParser().unescape(re.sub(r'<.+>', '', label)) text_size = draw_font.textsize(text, font) small_text_size = draw_font.textsize(text, small_font) text_x = (x + 1.5 + 4)*font_scale text_y = (y + 1.5 + 4)*font_scale # top left if key.labels.index(label) == 0: if key.centerx: text_x = text_x + (56*key.width-15)/2*font_scale - text_size[0]/2 else: text_x += 1*font_scale if key.centery: text_y = text_y + (56*key.height/2 - 10)*font_scale - text_size[1]/2 # bottom left if key.labels.index(label) == 1: if key.centery: continue text_y = text_y + (56*key.height - 3 - 12 - 3)*font_scale- text_size[1] if key.centerx: text_x = text_x + (56*key.width-17)/2*font_scale - text_size[0]/2 else: text_x += 1*font_scale # top right if key.labels.index(label) == 2: if key.centerx: continue # bottom right if key.labels.index(label) == 3: if key.centery: continue if key.centerx: continue text_y = text_y + (56*key.height - 3 - 12 - 3)*font_scale - text_size[1] # side left if key.labels.index(label) == 4: if key.centerf: text_x = text_x + (56*key.width-15)/2*font_scale - small_text_size[0]/2 text_y = text_y + (56*key.height - 16)*font_scale draw_font.text((text_x, text_y), text, key.text, font=small_font) continue # side right if key.labels.index(label) == 5: if key.centerf: continue text_y = text_y + (56*key.height - 16)*font_scale text_x = text_x + (56*key.width - 15)*font_scale - small_text_size[0] draw_font.text((text_x, text_y), text, key.text, font=small_font) continue # middle left if key.labels.index(label) == 6: if key.centery: continue if key.centerx: text_x = text_x + (56*key.width-15)/2*font_scale - text_size[0]/2 text_y = text_y + (56*key.height/2 - 4)*font_scale - text_size[1] # middle right if key.labels.index(label) == 7: if key.centery: continue if key.centerx: continue text_y = text_y + (56*key.height/2 - 4)*font_scale - text_size[1] text_x = text_x + (56*key.width-15)*font_scale - text_size[0] draw_font.text((text_x, text_y), text, key.text, font=font) font_layer.thumbnail(img.size, Image.ANTIALIAS) img.paste(font_layer, (0, 0), font_layer) return img