def draw_box(self, bbox, image):
        out_boxes, out_scores, out_classes, num_boxes = bbox
        print(num_boxes)
        image_h, image_w, _ = image.shape
        classes = util.read_class_names(
            "./tensorflow-yolov4-tflite/data/classes/coco.names")
        num_classes = len(classes)

        hsv_tuples = [(1.0 * x / num_classes, 1., 1.)
                      for x in range(num_classes)]
        colors = list(map(lambda x: colorsys.hsv_to_rgb(*x), hsv_tuples))
        colors = list(
            map(lambda x: (int(x[0] * 255), int(x[1] * 255), int(x[2] * 255)),
                colors))
        random.seed(0)
        random.shuffle(colors)
        random.seed(None)

        for i in range(num_boxes):
            # if int(out_classes[0][i]) < 0 or int(out_classes[0][i]) > num_classes: continue
            coord = out_boxes[i]
            score = out_scores[i]
            class_ind = int(out_classes[i])
            bbox_color = colors[class_ind]
            bbox_thick = int(0.6 * (image_h + image_w) / 600)
            bbox_mess = '%s: %.2f' % (classes[class_ind], score)
            # print([coord[1], coord[0], coord[3], coord[2]])
            self.canvas.create_rectangle(coord[0],
                                         coord[1],
                                         coord[2],
                                         coord[3],
                                         width=bbox_thick,
                                         outline=util.rgb_to_hex(bbox_color))
            self.draw_text(bbox_mess, [coord[0], coord[1], coord[2], coord[3]])
        self.canvas.pack()
Example #2
0
 def _plot_gradient(self):
     """display the light dark domain."""
     xmin, xmax = self._x_range
     ymin, ymax = self._y_range
     # Note that higher brightness has lower brightness value
     hi_brightness = self._env.const
     lo_brightness = max(
         0.5 * (self._env.light - xmin)**2 + self._env.const,
         0.5 * (self._env.light - xmax)**2 + self._env.const)
     # Plot a bunch of rectangular strips along the x axis
     # Check out: https://stackoverflow.com/questions/10550477
     x = xmin
     verts = []
     colors = []
     while x < xmax:
         x_next = x + self._res
         verts.append([(x, ymin), (x_next, ymin), (x_next, ymax),
                       (x, ymax)])
         # compute brightness based on equation in the paper
         brightness = 0.5 * (self._env.light - x)**2 + self._env.const
         # map brightness to a grayscale color
         grayscale = int(
             round(
                 util.remap(brightness, hi_brightness, lo_brightness, 255,
                            0)))
         grayscale_hex = util.rgb_to_hex((grayscale, grayscale, grayscale))
         colors.append(grayscale_hex)
         x = x_next
     util.plot_polygons(verts, colors, ax=self._ax)
     self._ax.set_xlim(xmin, xmax)
     self._ax.set_ylim(ymin, ymax)
Example #3
0
def main():
    if len(sys.argv) != 4:
        print('Usage: python search_color.py <r> <g> <b>')
        return 1
    color = list(map(int, sys.argv[1:4]))
    print('Searching for {} - {}'.format(color, rgb_to_hex(color)))
    for url, count in search_color(color).items():
        print(url, count)
    return 0
Example #4
0
    def update_color(self):
        color = np.array([0, 0, 0])
        for species_id, species_pheromones in enumerate(self.pheromones):
            color += self.world.species[species_id].inv_color * \
                len(species_pheromones)

        color = np.clip(np.around(color / 100), 0, 255)
        color = np.array([255 - val for val in color])

        self.world.canvas.itemconfig(
            self.canvas_id, fill=rgb_to_hex(color))
Example #5
0
 def update_color(self):
     """
     Fonction qui met a jour la couleur de la cellule sur le canvas
     """
     color = np.array([0, 0, 0])
     for species_id, species_pheromones in enumerate(self.pheromones):
         # intensifie la couleur en fonction du nombre de pheromones sur la
         # case
         color += self.world.species[species_id].inv_color * \
             len(species_pheromones)
     #  couleur inversee (noir vers couleur inversee de l espece)
     color = np.clip(np.around(color / 100), 0, 255)
     #  on reinverse la couleur( blanc vers couleur de l espece)
     color = np.array([255 - val for val in color])
     # on met a jour la couleur de la case
     self.world.canvas.itemconfig(self.canvas_id, fill=rgb_to_hex(color))
Example #6
0
    def __init__(self, world, nest_id, x, y, species_id, nAnts):
        self.world = world
        self.pos = np.array([x, y])
        self.species_id = species_id
        self.scale = nAnts / 2
        self.size = nAnts
        self.nest_id = nest_id
        self.food = 0

        species = self.world.species[species_id]
        species.set_active()

        self.color = species.color
        hex_color = rgb_to_hex(self.color)
        self.canvas_id = create_circle(self.world.canvas, x, y, self.scale,
                                       hex_color)

        self.ants = [Ant(self.world, self, i, hex_color) for i in range(nAnts)]
Example #7
0
def index(request, city=None, year=None, temperature_config=None):
    '''
    Renders the index page of the scarf application, which is the page that allows you to 
    define a city, year, and temperature / color ranges. This page can take parameters, in which case
    it will pre-select options, or it can take no parameters, in which case all of the defaults
    will be used.
    
    Keyword Arguments:
    city -> String. Name of a city. Can contain alphanumeric as well as ()., and <space>. Default None.
    year -> String. Must match '^\d{4}$'. Default None.
    temperature_config -> String. An alternating, '/' delimited list of colors and temperatures. See
                          scarf.util.parse_scarf_config for more information. Default None.
    
    '''

    # Define the object that we will pass to the templating engine. The contents of this will change depending on specifics
    # of the request parameters and such.
    template_dict = {}
    
    # We always need the list of cities and years for populating selects..
    template_dict['cities'] = map(lambda x: x.city, sorted(City.objects.all(), key=lambda x: x.city))
    template_dict['years'] = range(DATA_START_YEAR, datetime.now().year + 1)[::-1]
    
    # The template also always needs this information. Minimum and maximum number of colors, the factor to darken hex
    # by (for the JS clientside darken function), the two classes for white and black text (for dynamic class switching
    # in the client), the max and min valid temperature, and the golden ratio conjugate (for JS client-side random color
    # generation).
    template_dict['min_colors'] = MIN_COLORS
    template_dict['max_colors'] = MAX_COLORS
    template_dict['darken_factor'] = COLOR_DARKEN_FACTOR
    template_dict['text_color_class_white'] = TCC_WHITE
    template_dict['text_color_class_black'] = TCC_BLACK
    template_dict['max_temperature'] = MAX_TEMPERATURE
    template_dict['min_temperature'] = MIN_TEMPERATURE
    template_dict['golden_ratio_conjugate'] = GOLDEN_RATIO_CONJUGATE
        
    # Now, check for the presence of a city or year parameter in the request. If they do not exist, we will dummy 
    # them in as the first entry in the cities list and the first entry in the year list. We do this prior to parsing
    # since these values are required.
    if city == '' or city is None:
        city = template_dict['cities'][0]
    if year is None:
        year = template_dict['years'][0]
    
    template_dict['city_selected'] = city    
    try:
        year = int(year)
    except ValueError:
        year = template_dict['years'][0] 
    template_dict['year_selected'] = year
    
    # Now we will attempt to parse the passed parameters (with our bit of city / year magic included). If the parse succeeds,
    # we can use the data we found. If it doesn't, we have to fake the colors and temperatures.
    try:
        city, year, colors, labels, temperatures = parse_scarf_config(city, year, temperature_config)
        
    except ScarfConfigError:
        # If we caught an error, the problem has to be in the temperature_config variable, because
        # we forced city and year to be valid values prior to calling the parse_scarf_config routine.
        # Therefore, we will now generate fake colors and temperatures to initially populate everything.
        if temperature_config is not None:
            template_dict['message'] = ('warning', 'Hey!', 'Something wasn\'t quite right with your request, and we weren\'t able to load your color or temperature selections. Please try again.')
        
        colors = []
        labels = []
        h = random.random()
        for _ in itertools.repeat(None, DEFAULT_NUM_COLORS):            
            h += GOLDEN_RATIO_CONJUGATE
            h %= 1
            new_color = hsv_to_rgb(h, HSV_S, HSV_V)
            colors.append(rgb_to_hex(map(lambda x: int(x * 255), new_color)))
            labels.append(None)
        
        temperatures = map(lambda x: DEFAULT_COLDEST_TEMP + x* DEFAULT_COLOR_INTERVAL, range(0, DEFAULT_NUM_COLORS - 1))

    # At this point, the color and temperature variables contain either the data from the request, or
    # demonstration data that we have mocked up. Populate the darkened colors and the position list,
    # and then render the template.
    colors_dark = [darken_hex(color, COLOR_DARKEN_FACTOR) for color in colors]
    text_color_classes = [get_text_color_class(color) for color in colors]
    temperature_positions = [(100.0 / len(colors)) * x for x in range(1, len(temperatures) + 1)]
    template_dict['colors'] = zip(colors, colors_dark, labels, text_color_classes)
    template_dict['temps'] = zip(temperatures, temperature_positions)
    template_dict['color_length'] = 100.0 / len(colors)
    
    # Put it all together and render the template.
    return render_to_response(TEMPLATE_INDEX,
                              template_dict,
                              context_instance = RequestContext(request))