def _set_font_size(self): total_area = 0.0 freq = self._process_text() for i, (word, count) in enumerate(freq): color = get_color(self.color, self.custom_colors) if count == 1.0: font_size_prev = 0 # for same coloring for j in range(10): font_size_g = int(math.sqrt(PW_BOUND() * CANVAS_AREA / (FONT_UNIT * len(word)))) font_er = font.Font(self.font_path, font_size_g).render(word, True, color) f_rect = font_er.get_bounding_rect() font_size = font_size_g if PW_LOWER <= f_rect.width * f_rect.height / CANVAS_AREA <= PW_UPPER: break else: font_size = int(font_size_g * math.sqrt(count)) if font_size < MIN_FONT: font_size = MIN_FONT_RANGE() if font_size != font_size_prev: # for same coloring color = get_color(self.color, self.custom_colors) font_size_prev = font_size word_o = font.Font(self.font_path, font_size).render(word, True, color) w_rect = word_o.get_bounding_rect() total_area += (w_rect.width * w_rect.height) self.words.append(Word(word, word_o, color, 0)) if TR_UPPER/(total_area/CANVAS_AREA) < 1.0: self.ratio = TR_UPPER/(total_area/CANVAS_AREA)
def color(self): colors, distances = get_color(self.color_mean) if colors: return colors[0] else: return None
def main(): # color detection df = pd.read_json('widgets.json', orient='record') for i, row in df.iterrows(): colors = get_color('./all_widgets/' + row['name'] + '.png') df.at[i, 'color'] = colors break f = open('widgets1.json', 'w') f.write(df.to_json(orient='records')) f.close()
def upload(): """ Prend en entrée un fichier Retourne un json de type : - {"code": "ok", "color": "#<color>"} - Quand le fichier est bien reçu - {"code": "error", "error": "<explication>"} - Quand il y a une erreur avec l'envoie du fichier """ if 'file' not in request.files: d = {"error": "No file", "code": "error"} return jsonify(d) else: f = request.files['file'] if f.filename == '': d = {"error": "Filename is empty", "code": "error"} return jsonify(d) elif f: #sauvegarde du fichier photo sur le serveur print("etape 1") filename = secure_filename(f.filename) print("etape 2") f_path = os.path.join(app.config['UPLOAD_FOLDER'], filename) print("etape 3") f.save(f_path) print("etape 4") #génération de l'url_photo #obtention de la couleur f_color = color.get_color(f_path) print("etape 5") #récuperation user dressing_id = request.form['dressing_id'] print("etape 6") #récuperation type type_clothes = request.form['type_clothes'] print("etape 7") #sauvegarde des paramètre du vetement en BDD sql = "insert into vetement (dressing_id, path_photo, color, type) values ('%s','%s','%s','%s');" % ( dressing_id, f_path, f_color, type_clothes) d = {"code": "ok", "color": f_color} return jsonify(d) else: d = {"error": "error with upload file", "code": "error"} return jsonify(d)
def select_color(self, idx, col=None, auto=False): if not col: forbidden = { self.table[i, "col"].getRgb()[:3] for i in range(self.newrow) } col = get_color(auto=auto, forbidden=forbidden) if col is None: return self.table[(idx, "col")] = col color_button(self.table[idx, "new"], col) self.colUpdate.emit(idx)
def index(): try: if (request.method == 'POST'): url = request.form['image'] start_time = time.time() most_common_color = color.get_color(url) end_time = time.time() return render_template('index.html', url=url, color=most_common_color, time=end_time - start_time) except Exception as e: print(e) pass return render_template('index.html')
def bouding_box(idxs, image, boxes, colors, labels, classIDs, confiences): H, W = image.shape[:2] propertyObject = { "text": "", "confidence": "", "x": "", "y": "", "w": "", "h": "", "color": "" } if len(idxs) > 0: # loop over the indexes we are keeping for i in idxs.flatten(): # extract the bounding box coordinates (x, y) = (boxes[i][0], boxes[i][1]) (w, h) = (boxes[i][2], boxes[i][3]) # draw a bounding box rectangle and label on the image colorr = [int(c) for c in colors[classIDs[i]]] cv2.rectangle(image, (x, y), (x + w, y + h), colorr, 2) text = labels[classIDs[i]] confience = confiences[i] im = image[y:y+h, x:x+w] c = color.get_color(im) propertyObject['text'] = text propertyObject['confidence'] = confience propertyObject['x'] = x propertyObject['y'] = y propertyObject['w'] = w propertyObject['h'] = h propertyObject['color'] = c #cv2.putText(image, text, (x, y - 5), cv2.FONT_HERSHEY_SIMPLEX, 0.5, color, 2) # show the output image return propertyObject #def crop_object(image, idxs, boxes): # images = [] # if(len(idxs) > 0): # for i in idxs.flatten(): # (x, y) = (boxes[i][0], boxes[i][1]) # (w, h) = (boxes[i][2], boxes[i][3]) # im = image[y:y+h, x:x+w] # return images
def display_effect(curry): if curry.spicy > 500: spicy = u"修羅" elif curry.spicy > 400: spicy = u"地獄" elif curry.spicy > 300: spicy = u"激辛" elif curry.spicy > 200: spicy = u"大辛" elif curry.spicy > 100: spicy = u"中辛" elif curry.spicy > 10: spicy = u"辛口" else: spicy = u"甘口" key = curry.color[0] * 0x10000 + curry.color[1] * 0x100 + curry.color[2] color_name = color.get_color(key) return u"辛さは %s、色は %s、カロリーは %s kcal、値段は %d 円です。" % ( spicy, color_name, curry.kal, curry.price)
def plot_convergence(json_file: str, run_id: str = 'all', max_plots_per_line: int = 5, headless=False, combine_views=False, save_file: str = None, metrics='curvature, cost', dpi: int = 200, **kwargs): click.echo("Visualizing %s..." % click.format_filename(json_file)) stat_keys = parse_metrics(metrics) if headless and 'matplotlib' not in sys.modules: import matplotlib matplotlib.use('Agg') click.echo("Running headless") import matplotlib.pyplot as plt import matplotlib as mpl mpl.rcParams['mathtext.fontset'] = 'cm' mpl.rcParams['pdf.fonttype'] = 42 # make sure to not use Level-3 fonts file = open(json_file, "r") data = json.load(file) file.close() run_ids = parse_run_ids(run_id, len(data["runs"])) if combine_views: max_plots_per_line = min(max_plots_per_line, len(stat_keys)) axes_h = max_plots_per_line axes_v = int(math.ceil(len(stat_keys) / max_plots_per_line)) plt.figure("MPB Convergence %s" % json_file, figsize=(axes_h * 5, axes_v * 5)) run_id = run_ids[0] print_run_info(data, run_id, run_ids) for si, stat_key in enumerate(stat_keys): run = data["runs"][run_id] if combine_views: plt.subplot(axes_v, axes_h, si + 1) else: plt.figure("Run %i - %s (%s)" % (run_id, json_file, stat_key)) kwargs['run_id'] = run_id plt.title(stat_names[stat_key], fontsize=20) plt.grid() plt.gca().set_xlabel("Planning Time [sec]", fontsize=18) for j, (planner, plan) in enumerate(run["plans"].items()): if "intermediary_solutions" in plan and len(plan["intermediary_solutions"]) > 0: times = [] stats = [] for sol in plan["intermediary_solutions"]: times.append(sol["time"]) if stat_key == 'cost': stats.append(sol["cost"]) else: stats.append(sol["stats"][stat_key]) plt.plot(times, stats, '.-', color=get_color(j, **kwargs), label=planner) if not combine_views or si % axes_h == 0: plt.legend() if not combine_views and save_file is not None: plt.tight_layout() ext = save_file.rindex('.') filename = save_file[:ext] + '_%s' % stat_key + save_file[ext:] plt.savefig(filename, dpi=dpi, bbox_inches='tight') click.echo("Saved %s." % filename) if combine_views and save_file is not None: plt.tight_layout() plt.savefig(save_file, dpi=dpi, bbox_inches='tight') click.echo("Saved %s." % save_file) if not headless: plt.show()
def get_screenshots_from_verbo(): folders = os.listdir(PATH1)+os.listdir(PATH2)+os.listdir(PATH3) if '.DS_Store' in folders: folders.remove('.DS_Store') folders_app = {} for x in folders: folders_app[x.split('_')[0]] = x for i,row in df.iterrows(): id = int(row['name'].split('-')[1]) if id % 500 == 0: print(id) if id < 11463: package = row['package_name'] if package not in folders_app.keys(): continue if os.path.isdir(PATH1+folders_app[package]+'/stoat_fsm_output/ui/'): path = PATH1+folders_app[package]+'/stoat_fsm_output/ui/' elif os.path.isdir(PATH2+folders_app[package]+'/stoat_fsm_output/ui/'): path = PATH2+folders_app[package]+'/stoat_fsm_output/ui/' else: path = PATH3+folders_app[package]+'/stoat_fsm_output/ui/' else: continue files = [x.replace('.xml','') for x in os.listdir(path) if x.endswith('.xml')] for f in files: ob = parseXML(path+f+'.xml') match = False for class_,bounds in ob: class_bool = False b_bool = False p_bool = False color_bool = False # test class if class_==row['widget_class']: class_bool = True else: continue # test bounds if bounds== row['coordinates']['from']+row['coordinates']['to']: b_bool = True else: continue # test path if os.path.exists(path+f+'.png'): p_bool = True else: continue # test color try: image = cv2.imread(path+f+'.png') widgets = image[bounds[1]:bounds[3], bounds[0]:bounds[2]] except: continue colors = get_color(widgets) base_colors = row['color'] if type(colors) == int or type(base_colors) == int: continue if 'Red' in colors.keys(): del colors['Red'] if 'Red2' in colors.keys(): del colors['Red2'] color_bool = all(abs(base_colors[c] - v)<=0.1 for c,v in colors.items()) if class_bool and b_bool and p_bool and color_bool: match = True break # extract bounding image if match: cv2.rectangle(image, (bounds[0],bounds[1]), (bounds[2],bounds[3]), (0,0,255),2) cv2.imwrite('./screenshots/'+package+'-'+f+'-'+str(id)+'.png',image) break
def get_screenshots_from_rico(): # merge rico info df1 = pd.read_csv('ui_details.csv') df2 = pd.read_csv('app_details.csv') df_ui = pd.merge(df1, df2, on='App Package Name') df_ui = df_ui[['UI Number', 'App Package Name', 'Play Store Name', 'Category', 'Number of Downloads', 'Date Updated']] df_ui.columns = ['UI Number', 'package_name', 'application_name', 'category', 'downloads', 'date'] for i,row in df.iterrows(): targets = ["CheckBox","Button","Chronometer","RadioButton","RatingBar","SeekBar","Spinner","ToggleButton","ProgressBar","Switch","ImageButton"] targets_lower = ['checkbox', 'button', 'chronometer', 'radiobutton', 'ratingbar', 'seekbar', 'spinner', 'togglebutton', 'progressbar', 'switch', 'imagebutton'] id = int(row['name'].split('-')[1]) if id % 500 == 0: print(id) if id >= 11463: package = row['package_name'] files = df_ui[df_ui["package_name"]==package]['UI Number'].tolist() for f in files: if not (os.path.exists(PATH_RICO+str(f)+'.json') and os.path.exists(PATH_RICO+str(f)+'.jpg')):continue # image = Image.open('/Users/mac/Documents/Python/Data/Rico/'+str(i)+'.jpg') # image = image.resize((1440,2560),Image.BICUBIC) ob = parseRico(PATH_RICO+str(f)+'.json') list1 = [x for x in ob if (x[0] == 'ImageButton' or x[0] == 'Button')] list2 = parseSemantic(PATH_SEMANTIC+str(f)+'.json') matched = [x for x in list1 if x[1] in list2] unmatched = len(list1) - len(matched) if unmatched >= Threshold: ob = matched match = False for class_,bounds in ob: class_bool = False b_bool = False p_bool = False color_bool = False # test class if class_==row['widget_class']: class_bool = True else: continue # test bounds (normalise to 800*1280) bounds = [bounds[0]/1.8,bounds[1]/2,bounds[2]/1.8,bounds[3]/2] fake_bounds = row['coordinates']['from']+row['coordinates']['to'] if all(abs(bounds[i]-fake_bounds[i])<3 for i in range(len(bounds))): b_bool = True else: continue # test path if os.path.exists(PATH_RICO+str(f)+'.jpg'): p_bool = True else: continue # test color try: image = cv2.imread(PATH_RICO+str(f)+'.jpg') image = cv2.resize(image, (800, 1280), interpolation=cv2.INTER_CUBIC) widgets = image[fake_bounds[1]:fake_bounds[3], fake_bounds[0]:fake_bounds[2]] except: continue colors = get_color(widgets) base_colors = row['color'] if type(colors) == int or type(base_colors) == int: continue if 'Red' in colors.keys(): del colors['Red'] if 'Red2' in colors.keys(): del colors['Red2'] color_bool = all(abs(base_colors[c] - v)<=0.1 for c,v in colors.items()) if class_bool and b_bool and p_bool and color_bool: match = True break # extract bounding image if match: cv2.rectangle(image, (fake_bounds[0],fake_bounds[1]), (fake_bounds[2],fake_bounds[3]), (0,0,255),2) cv2.imwrite('./screenshots/'+package+'-'+str(f)+'-'+str(id)+'.png',image) break
import datetime import logging from pytz import UTC verbose = '-v' in sys.argv logging.basicConfig(level='WARNING' if verbose else 'ERROR', format="%(message)s") # Load config. Contains username and other sensitive info. with open("hue_config.json", "r") as f: config = json.loads(f.read()) bridge = config["bridge"] bridge = Bridge(bridge["address"], bridge["username"]) # What is optimum color temperature right now? ct, explanation = get_color(datetime.datetime.now(tz=UTC)) logging.warning("\nCalculated colour temperature is %s (%s)\n", ct, explanation) for light_id in LIGHT_IDS: light = bridge.lights[light_id]() name = light['name'] state = 'on' if light['state']['on'] else 'off' bri = light['state']['bri'] # If the light is on and it has a 'ct' setting... if state == 'on': if 'ct' in light['state']: if bri == 253 or light_id==19: # only act on certain lights in certain states # ...set its colour temperature to daytime-optimal value action = 'setting to %d...' % ct
from color import get_color import json import datetime import requests from pytz import UTC # Load config. Contains username and other sensitive info. with open("hue_config.json", "r") as f: config = json.loads(f.read()) bridge = config["bridge"] bridge = Bridge(bridge["address"], bridge["username"]) # What is optimum color temperature right now? auto = {} auto["ct"], explanation = get_color(datetime.datetime.now(tz=UTC)) scene_id = config["scene_id"] rule_id = config["rule_id"] # Set lights for scene if necessary if not sorted(bridge.scenes[scene_id]()['lights']) == sorted(config['lights'].keys()): bridge.scenes[scene_id](name='daylite',lights=config['lights'].keys()) # Mod lightstates for specified scene for light_id in config["lights"].keys(): settings = config["lights"][light_id] # Look for 'auto' in the value of a setting, replace with corresponding contents of auto # If not found, just take whatever's there kw = {}
def color_points(): for p in generate_points(): yield (p, get_color(p))
import logging from pytz import UTC verbose = '-v' in sys.argv logging.basicConfig(level='WARNING' if verbose else 'ERROR', format="%(message)s") # Load config. Contains username and other sensitive info. with open("hue_config.json", "r") as f: config = json.loads(f.read()) bridge = config["bridge"] bridge = Bridge(bridge["address"], bridge["username"]) # What is optimum color temperature right now? ct, explanation = get_color(datetime.datetime.now(tz=UTC)) logging.warning("\nCalculated colour temperature is %s (%s)\n", ct, explanation) for light_id in LIGHT_IDS: light = bridge.lights[light_id]() name = light['name'] state = 'on' if light['state']['on'] else 'off' bri = light['state']['bri'] # If the light is on and it has a 'ct' setting... if state == 'on': if 'ct' in light['state']: if bri == 253 or light_id == 19: # only act on certain lights in certain states # ...set its colour temperature to daytime-optimal value
def set_background(self, col=None): if not col: col = get_color('black') libtcod.console_set_background_color(0, col) logging.debug("background color set to [%s]" % col.name)
def set_foreground(self, col=None): if not col: col = get_color('white') libtcod.console_set_foreground_color(0, col) logging.debug("foreground color set to [%s]" % col.name)
fgp.add_child(folium.GeoJson(data=open('world.json', 'r', encoding='utf-8-sig').read(), style_function= lambda x: {'fillColor': '#228B22' if x['properties']['POP2005'] < (1000000 * 25) else '#FFFF00' if (1000000 * 25) <= x['properties']['POP2005'] < (1000000 * 50) else '#FFA500' if (1000000 * 50) <= x['properties']['POP2005'] < (1000000 * 100) else '#FF0000'})) us_map.add_child(fgp) # Feature group for Volcanoes data fgv = folium.FeatureGroup("US Volcanoes") for (name, location, elevation, lat, lon) in v: txt = "Name: "+name+" | Elevation: "+str(elevation)+" m | Location: "+location pop = folium.Popup(txt, parse_html=True) fgv.add_child(folium.CircleMarker(location=(lat, lon), radius=8, popup=pop, fill=True, fill_color=get_color(elevation), fill_opacity=0.8, color=get_color(elevation))) us_map.add_child(fgv) # Creating Legend legend_html_volcanoes = ''' <div style="position: fixed; bottom: 45px; left: 45px; width: 138px; height: 115px; border:2px solid grey; z-index:9999; font-size:14px; "> <b>Volcanoes of USA</b><br> <b><ins>Elevation</ins></b><br> <1000 <i class="fa fa-circle" style="color:#00BFFF"></i><br> < 3000 <i class="fa fa-circle" style="color:#FFA500"></i><br/> >= 3000 <i class="fa fa-circle" style="color:#B22222"></i>
from color import get_color import json import datetime import requests from pytz import UTC # Load config. Contains username and other sensitive info. with open("hue_config.json", "r") as f: config = json.loads(f.read()) bridge = config["bridge"] bridge = Bridge(bridge["address"], bridge["username"]) # What is optimum color temperature right now? auto = {} auto["ct"], explanation = get_color(datetime.datetime.now(tz=UTC)) scene_id = config["scene_id"] rule_id = config["rule_id"] # Set lights for scene if necessary if not sorted(bridge.scenes[scene_id]()['lights']) == sorted( config['lights'].keys()): bridge.scenes[scene_id](name='daylite', lights=config['lights'].keys()) # Mod lightstates for specified scene for light_id in config["lights"].keys(): settings = config["lights"][light_id] # Look for 'auto' in the value of a setting, replace with corresponding contents of auto # If not found, just take whatever's there
def __init__(self, pos: Position, width: int = 4): self._active = False self._pos = pos self._color = get_color() self.width = width