Example #1
0
 def draw(self):
     pygame.draw.circle(self.current_screen, get_color(Colors.LIGHT_PURPL2),
                        self.current_position.to_table(), self.RADIUS)
     pygame.draw.circle(self.current_screen, self.COLOR_OUT,
                        self.current_position.to_table(), self.RADIUS,
                        self.THICK)
     pygame.draw.polygon(self.current_screen, get_color(Colors.LIGHTER_RED),
                         self.triangle.to_draw(self.current_position), 1)
Example #2
0
    def draw_label_with_text(self, screen):

        self.render_text(screen, get_color(Colors.WHITE), 40, "GAME OVER",
                         START_POSITION)

        self.render_text(screen, get_color(Colors.WHITE), 20,
                         "press space to restart",
                         Vector(START_POSITION.x, START_POSITION.y + 60))

        pygame.draw.rect(screen, get_color(Colors.LIGHT_RED),
                         [150, 170, 724, 420], 2)
Example #3
0
    def draw_label_with_text(self, screen):

        self.render_text(screen, get_color(Colors.WHITE), 40,
                         "PLAYER " + str(self.win_id) + " WON", START_POSITION)

        self.render_text(screen, get_color(Colors.WHITE), 20,
                         "press space to restart",
                         Vector(START_POSITION.x, START_POSITION.y + 60))

        pygame.draw.rect(screen, get_color(Colors.LIGHT_BLUE),
                         [150, 170, 724, 420], 2)
def draw_boxes(image, boxes, labels, obj_thresh, quiet=True):
    nb_box = 0
    face_center = [0, 0]
    for box in boxes:

        # elinminate face smaller than 30X30
        # if (box.xmax-box.xmin) < 50 and (box.ymax-box.ymin) < 50:
        #     continue

        # draw the box
        label_str = ''
        label = -1

        for i in range(len(labels)):
            if box.classes[i] > obj_thresh:
                if label_str != '': label_str += ', '
                label_str += (labels[i] + ' ' +
                              str(round(box.get_score() * 100, 2)) + '%')
                label = i
            if not quiet: print(label_str)
        # judge the box is a face or not----ZCY
        if label >= 0:
            nb_box += 1

            text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX,
                                        1.1e-3 * image.shape[0], 5)
            width, height = text_size[0][0], text_size[0][
                1]  # this is the text size, a small rectangle
            region = np.array([[box.xmin - 3, box.ymin],
                               [box.xmin - 3, box.ymin - height - 26],
                               [box.xmin + width + 13, box.ymin - height - 26],
                               [box.xmin + width + 13, box.ymin]],
                              dtype='int32')

            face_center = [(box.xmin + box.xmax) / 2,
                           (box.ymin + box.ymax) / 2]
            #face=image[max(box.ymin,0):min(box.ymax,image.shape[1]), max(0,box.xmin):min(box.xmax,image.shape[0]), :]
            #img_name=(image_path.split('/')[-1]).split('.')[-2]
            cv2.rectangle(img=image,
                          pt1=(box.xmin, box.ymin),
                          pt2=(box.xmax, box.ymax),
                          color=get_color(label),
                          thickness=5)
            cv2.imwrite('D:/CV/mypaper/test3' + '_%s' % nb_box + '.jpg', image)


# =============================================================================
#             cv2.fillPoly(img=image, pts=[region], color=get_color(label))
#             cv2.putText(img=image,
#                         text=label_str,
#                         org=(box.xmin+13, box.ymin - 13),
#                         fontFace=cv2.FONT_HERSHEY_SIMPLEX,
#                         fontScale=1e-3 * image.shape[0],
#                         color=(0,0,0),
#                         thickness=2)
# =============================================================================

    return image, nb_box, face_center
Example #5
0
	def draw(self):
		self.screen.fill(get_color(Colors.NAVYBLUE))
		for obj in ( self.enemy_list + self.obstacle_list ):
			obj.draw()

		for item in self.items_list:
			item.draw()

		self.graph.draw(self.screen)
Example #6
0
    def draw(self, screen):
        for i in range(len(self.nodes)):
            for j in range( len(self.nodes[i])):
                if self.nodes[i][j] is None : continue
                pygame.draw.circle(screen, (255,255,255), self.nodes[i][j].position.to_table(), 1 )
                if self.nodes[i][j].neighbours is None : continue
                for neighbour in self.nodes[i][j].neighbours:
                    pygame.draw.line(screen, get_color(Colors.RED),self.nodes[i][j].position.to_table(), neighbour.position.to_table(), 1 )

        if len( self.serc.keys() ) == 0: return 
Example #7
0
    def draw(self):
        if self.visible and not self.is_dead and not self.triggered:
            pygame.draw.circle(self.current_screen, self.COLOR,
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)
        elif not self.visible:
            pass
    #		pygame.draw.circle(self.current_screen, get_color(Colors.DARK_YELLOW), self.current_position.to_table(), self.RADIUS, self.THICKNESS )
        elif self.triggered:
            pygame.draw.circle(self.current_screen, get_color(Colors.YELLOW),
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)
        else:
            pygame.draw.circle(self.current_screen, get_color(Colors.RED),
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)

    #	pygame.draw.line(self.current_screen, get_color(Colors.RED),self.current_position.to_table(), ( self.current_position + self.velocity).to_table(), 2 )
    #	pygame.draw.line(self.current_screen, get_color(Colors.BLUE),Vector(512,0).to_table(), Vector(512,720).to_table(), 2 )
def get_options(opt, lw):
    mode = "line"
    color = None # LINECOLORS[0] #len(data) % len(LINECOLORS)]
    if opt is None:
        mode = "line"
    else:
        # mode?
        if opt[0] == '-':
            mode = "line"
        elif opt[0] == ',':
            mode = "points"
            
        # color?
        if (len(opt)==1):
            if opt not in "-,":
                color = get_color(opt[0])
        else:
            color = get_color(opt[1])
    return dict(lw=lw, mode=mode, color=color)
Example #9
0
    def load(self):
        filename = tkFileDialog.askopenfilename(filetypes=[("HTD", ".htd")])
        self.set_status("Loading...")
        if not filename:
            return
        htd = DataHTD.DataHTD(filename)

        pp = pprint.PrettyPrinter()
        #pp.pprint(htd.packages)

        minx = maxx = htd.packages[0][1]
        miny = maxy = htd.packages[0][2]
        #minc = maxc = htd.packages[0][3]
        for i in range(htd.noPackage - 1):
            if htd.packages[i][1] < minx:
                minx = htd.packages[i][1]
            elif htd.packages[i][1] > maxx:
                maxx = htd.packages[i][1]
            if htd.packages[i][2] < miny:
                miny = htd.packages[i][2]
            elif htd.packages[i][2] > maxy:
                maxy = htd.packages[i][2]
            '''if htd.packages[i][3] < minc:
                minc = htd.packages[i][3]
            elif htd.packages[i][3] > maxc:
                maxc = htd.packages[i][3]'''
        scalex = float(maxx - minx) / float(self.width)
        scaley = float(maxy - miny) / float(self.height)
        #scalec = float(maxc - minc) / float(255)
        #print minx, maxx, miny, maxy, minc, maxc
        #print scalex, scaley, scalec
        for i in range(htd.noPackage):
            #self.l.append([(htd.packages[i][1] - minx) / scalex, (htd.packages[i][2] - miny) / scaley, (htd.packages[i][3] - minc) / scalec])
            self.l.append([(htd.packages[i][1] - minx) / scalex,
                           (htd.packages[i][2] - miny) / scaley,
                           int(float(htd.packages[i][3] * 255) / 1000.0)])
        #pprint.pprint(self.l)

        #Rysowanie
        image = Image.new("RGB", (self.width, self.height), "white")
        draw = ImageDraw.Draw(image)
        for i in range(len(self.l) - 1):
            c = colors.get_color((self.l[i][2] + self.l[i + 1][2]) / 2.0)
            draw.line((self.scale * self.l[i][0] + self.xpad,
                       self.scale * self.l[i][1] + self.ypad,
                       self.scale * self.l[i + 1][0] + self.xpad,
                       self.scale * self.l[i + 1][1] + self.ypad),
                      fill=c)
        tkimage = ImageTk.PhotoImage(image)
        self.label.configure(image=tkimage)
        self.label.image = tkimage
        self.set_status("Loading complete.")
Example #10
0
def draw_boxes(image, boxes, labels, obj_treshold):
    for box in boxes:
        label_str = ''

        label = box.get_label()
        score = box.get_score()

        if score > obj_treshold:
            label_str += (label + ' ' + str(round(score * 100, 2)) + '%')
        else:
            label = -1

        if label >= 0:
            text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX,
                                        1.1e-3 * image.shape[0], 5)
            width, height = text_size[0][0], text_size[0][1]
            region = np.array([[box.xmin - 3, box.ymin],
                               [box.xmin - 3, box.ymin - height - 26],
                               [box.xmin + width + 13, box.ymin - height - 26],
                               [box.xmin + width + 13, box.ymin]],
                              dtype='int32')

            cv2.rectangle(img=image,
                          pt1=(box.xmin, box.ymin),
                          pt2=(box.xmax, box.ymax),
                          color=get_color(label),
                          thickness=5)
            cv2.fillPoly(img=image, pts=[region], color=get_color(label))
            cv2.putText(img=image,
                        text=label_str,
                        org=(box.xmin + 13, box.ymin - 13),
                        fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                        fontScale=1e-3 * image.shape[0],
                        color=(0, 0, 0),
                        thickness=2)

    return image
Example #11
0
class Cursor:

    COLOR = get_color(Colors.YELLOW)
    COLOR2 = get_color(Colors.DARK_YELLOW)
    RADIUS = 10
    THICK = 1
    position = Vector(0, 0)
    screen = None

    def __init__(self, screen):
        self.screen = screen

    def process_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.position = (Vector(event.pos[0], event.pos[1]))

    def draw(self):
        pygame.draw.circle(self.screen, self.COLOR2, self.position.to_table(),
                           self.RADIUS)

        pygame.draw.circle(self.screen, self.COLOR, self.position.to_table(),
                           self.RADIUS, self.THICK)

        pygame.draw.line(
            self.screen, self.COLOR,
            Vector(self.position.x - self.RADIUS / 3,
                   self.position.y).to_table(),
            Vector(self.position.x + self.RADIUS / 3,
                   self.position.y).to_table(), self.THICK)

        pygame.draw.line(
            self.screen, self.COLOR,
            Vector(self.position.x,
                   self.position.y - self.RADIUS / 3).to_table(),
            Vector(self.position.x,
                   self.position.y + self.RADIUS / 3).to_table(), self.THICK)
Example #12
0
 def save(self):
     #Zapisz do pliku pdf
     filename = tkFileDialog.asksaveasfilename(filetypes=[("PDF", ".pdf")])
     self.set_status("Saving...")
     if not filename:
         return
     can = pyx.canvas.canvas()
     for i in range(len(self.l) - 1):
         c0 = colors.get_color((self.l[i][2] + self.l[i + 1][2]) / 2.0)
         c = pyx.color.rgb(float(c0[0] / 255), float(c0[1] / 255),
                           float(c0[2] / 255))
         can.stroke(
             pyx.path.line(self.l[i][0], self.l[i][1], self.l[i + 1][0],
                           self.l[i + 1][1]),
             [linestyle.solid, linewidth(0.5), c])
     can.writePDFfile(filename)
     self.set_status("Saving complete.")
Example #13
0
def handle_client(client, clients_list_lock):
    log('Start thread for this client')
    incoming_msg = pickle.loads(client.recv(BUFSIZ))
    log('Server receive register message \n %s' % incoming_msg)
    welcome = 'Welcome %s! If you ever want to quit,' \
              ' type {quit} to exit\n' % incoming_msg['user_name']
    welcome_msg = create_server_json_msg(text=welcome)
    client.send(bytes(pickle.dumps(welcome_msg)))
    log('Send to %s \n msg= %s' % (client.getsockname(), welcome_msg))
    has_join = "%s has joined the chat!\n" % incoming_msg['user_name']
    has_join_msg = create_server_json_msg(has_join)
    broadcast(has_join_msg, clients_list_lock)
    with clients_list_lock:
        clients[client] = incoming_msg['user_name']
    client_color = colors.get_color()
    while True:
        try:
            incoming_msg = client.recv(BUFSIZ)
            incoming_msg = pickle.loads(incoming_msg)
        except EOFError:  # Possibly client has left brutality the chat.
            if incoming_msg.decode("utf8") == '':
                incoming_msg = {
                    'text': "{quit}\n"  # Back to safety quit scenario
                }
        if incoming_msg['text'] != "{quit}\n":
            log('Incoming message from %s \n message = %s'
                % (client.getsockname(), incoming_msg))
            incoming_msg['user_color'] = client_color
            log('Broadcasting the message')
            broadcast(incoming_msg, clients_list_lock)
        else:
            log('Client %s:%s has disconnected' % client.getsockname())
            left_client = client.getsockname()
            with clients_list_lock:
                client.close()
                log('client %s:%s deleted' % left_client)
                has_left = "%s has left the chat.\n" % clients[client]
                del clients[client]
            has_left_msg = create_server_json_msg(has_left)
            log('Broadcasting message %s' % has_left[:-2])
            broadcast(has_left_msg, clients_list_lock)
            break
    log('thread is finished')
Example #14
0
    def draw_graph(self):
        my_max = self.fx[0][0]
        my_min = self.fx[0][0]

        for i in range(0, len(self.fx)):
            for ii in range(0, len(self.fx[i])):
                if self.fx[i][ii] > my_max:
                    my_max = self.fx[i][ii]

                if self.fx[i][ii] < my_min:
                    my_min = self.fx[i][ii]

        if (len(self.fx) > 0):
            mul, unit = fx_with_units(float(my_max - my_min))
        else:
            mul = 1.0
            unit = "Hz"

        fx = []

        for i in range(0, len(self.fx)):
            local_fx = []
            for ii in range(0, len(self.fx[i])):
                local_fx.append(self.fx[i][ii] * mul)
            fx.append(local_fx)

        self.fig.clf()
        self.fig.subplots_adjust(bottom=0.2)
        self.fig.subplots_adjust(left=0.1)
        self.ax1 = self.fig.add_subplot(111)
        self.ax1.ticklabel_format(useOffset=False)

        self.ax1.set_ylabel(_("Magnitude") + " (" + _("Volts") + " )")

        for i in range(0, len(fx)):
            frequency, = self.ax1.plot(fx[i],
                                       self.mag[i],
                                       'ro-',
                                       color=get_color(i),
                                       linewidth=3,
                                       alpha=1.0)

        self.ax1.set_xlabel(_("Frequency") + " (" + unit + ")")
Example #15
0
class TeamSchema(ma.Schema):
    """ team schema """
    class Meta:
        model = Team
        fields = ('id', 'owner', 'name', 'colors', 'score')

    colors = ma.Function(lambda team: get_color(team.color))
    owner = ma.Nested(UserSchema)
    score = ma.Method('compute_score')

    def compute_score(self, team):
        """" retourne le score de l'equipe """
        return (sum(map(lambda pic: pic.objective.points, team.pictures)) +
                sum(map(lambda found: found.qr.points, team.qrs)))

    def dump(self, element):
        res = super().dump(element)
        if self.many:
            res.sort(key=lambda t: -t['score'])
        return res
Example #16
0
	def tick(self):
		if self.cursor>len(self.curves[0])-2: return
		if self.curves==None: return
		curves=self.curves
		
		for i in range(len(curves)):
			curve=curves[i]
			if curve==[]: return
			color=colors.get_color(i)
			mx=max(1, float(max(curve)))
			curve=map(lambda x: self.height-0.9*self.height*x/mx, curve)
			q=range(len(curve))
			q=map(lambda x: self.width*x/len(curve), q)
			xy=zip(q, curve)
			q=xy[self.cursor:self.cursor+2]
			if len(q)<2: return
			self.canvas.create_line(q, fill=color, width=2)
		self.cursor+=1
	
		
		
def _show():
    global i
    if i >= len(clusters):
        return
    x_list = []
    y_list = []
    for point in clusters[i]:
        x_list.append(cx[point])
        y_list.append(cy[point])
    col = get_color(len(x_list))
    plt.scatter(x_list, y_list, s=50, c=col)
    if centroids:
        plt.scatter([centroids[i][0]], [centroids[i][1]],
                    facecolors='none',
                    edgecolors=col)
        if i > 0:
            plt.scatter([centroids[i - 1][0]], [centroids[i - 1][1]],
                        c=[(1, 1, 1)],
                        alpha=1,
                        s=70)
    canvas.draw()
    i += 1
Example #18
0
from colors import get_color

if __name__ == "__main__":
    """When running as the main script, this program should:
        1) Ask the user for a color
        2) execute `get_color`, passing the color name obtained from the user
    """
    get_color(None)
Example #19
0
class HUD:

    color = get_color(Colors.WHITE)
    font_size = 20
    font = None
    screen = None
    player = None
    cursor = None

    HP_max = 0
    hp_bar_color = get_color(Colors.LIGHT_RED)
    hp_txt_position = (30, 30)
    hp_bar_position = (30, 60)

    delta = 0
    cooldown = 100
    cd_bar_color = get_color(Colors.BLUE_BAR)
    cd_txt_position = (780, 30)
    cd_bar_position = (840, 60)

    bar_width = 150

    def __init__(self, screen, player):
        self.screen = screen
        self.font = pygame.font.SysFont("consolas", self.font_size)
        self.player = player
        self.HP_max = player.get_HP()
        self.cursor = Cursor(screen)
        self.delta = self.cooldown

    def HP(self):
        return max(0, self.player.get_HP())

    def render_text(self, text):
        return self.font.render(str(text), True, self.color)

    def draw_HP_amount(self):
        self.screen.blit(
            self.render_text("HP : " + str(int(self.HP())) + " / " +
                             str(self.HP_max)), self.hp_txt_position)

    def draw_cooldown_amount(self):
        self.screen.blit(
            self.render_text("COOLDOWN : " + str(round(self.delta)) + " / " +
                             str(self.cooldown)), self.cd_txt_position)

    def draw_bar(self, color, position, fill):
        pygame.draw.rect(self.screen, color,
                         (position[0], position[1], fill, 10))
        pygame.draw.rect(self.screen, color,
                         (position[0], position[1], self.bar_width, 10), 1)

    def draw_HP_bar(self):
        self.draw_bar(self.hp_bar_color, self.hp_bar_position,
                      self.HP() * self.bar_width / self.HP_max)

    def draw_cooldown_bar(self):
        self.draw_bar(self.cd_bar_color, self.cd_bar_position,
                      self.delta / 100 * self.bar_width)

    def process_event(self, event):
        if event.type == Events.SHOOT:
            self.delta = 0
        self.cursor.process_event(event)

    def update(self, delta):
        self.delta += 98 * delta
        if self.delta > self.cooldown:
            self.delta = self.cooldown
            rise_event(Events.IS_READY, {})

    def draw(self):
        self.cursor.draw()

        self.draw_HP_amount()
        self.draw_HP_bar()

        self.draw_cooldown_amount()
        self.draw_cooldown_bar()
Example #20
0
    def do_plot(self):
        if len(self.data) == 0:
            return

        if self.data[0].valid_data == False:
            return

        key_text = []

        self.plot_type = ""

        #print(self.data[0].x_len,self.data[0].z_len,self.data[0].data)
        if self.data[0].type == "rgb":
            self.plot_type = "rgb"
        elif self.data[0].type == "quiver":
            self.plot_type = "quiver"
        else:
            if self.data[0].x_len == 1 and self.data[0].z_len == 1:
                self.plot_type = "linegraph"
            elif self.data[0].x_len > 1 and self.data[
                    0].y_len > 1 and self.data[0].z_len == 1:
                if self.data[0].type == "3d":
                    self.plot_type = "wireframe"
                if self.data[0].type == "heat":
                    self.plot_type = "heat"
            elif self.data[0].x_len > 1 and self.data[
                    0].y_len > 1 and self.data[0].z_len > 1:
                print("ohhh full 3D")
                self.plot_type = "3d"
            else:
                print(_("I don't know how to process this type of file!"),
                      self.data[0].x_len, self.data[0].y_len,
                      self.data[0].z_len)
                return

        self.setup_axis()

        all_plots = []
        files = []
        my_max = 1.0

        if self.plot_type == "linegraph":  #This is for the 1D graph case
            self.ax[0].set_xlabel(self.data[0].y_label + " (" +
                                  str(self.data[0].y_units) + ")")
            self.ax[0].set_ylabel(self.data[0].data_label + " (" +
                                  self.data[0].data_units + ")")

            for i in range(0, len(self.data)):
                if self.data[0].logy == True:
                    self.ax[i].set_xscale("log")

                if self.data[0].logdata == True:
                    self.ax[i].set_yscale("log")

                if self.data[i].data_min != None:
                    self.ax[i].set_ylim(
                        [self.data[i].data_min, self.data[i].data_max])

                if self.data[i].rgb() != None:
                    col = "#" + self.data[i].rgb()
                else:
                    col = get_color(i)
                cur_plot, = self.ax[i].plot(self.data[i].y_scale,
                                            self.data[i].data[0][0],
                                            linewidth=3,
                                            alpha=1.0,
                                            color=col,
                                            marker=get_marker(i))
                #print(self.data[i].y_scale,self.data[i].data[0][0])
                if self.data[i].key_text != "":
                    key_text.append(
                        "$" + numbers_to_latex(str(self.data[i].key_text)) +
                        " " +
                        pygtk_to_latex_subscript(self.data[0].key_units) + "$")

                all_plots.append(cur_plot)

                if len(self.data[i].labels) != 0:
                    #we only want this many data labels or it gets crowded
                    max_points = 12
                    n_points = range(0, len(self.data[i].y_scale))
                    if len(n_points) > max_points:
                        step = int(len(n_points) / max_points)
                        n_points = []
                        pos = 0
                        while (len(n_points) < max_points):
                            n_points.append(pos)
                            pos = pos + step

                    for ii in n_points:
                        label_text = self.data[i].labels[ii]
                        self.ax[i].annotate(label_text,
                                            xy=(self.data[i].y_scale[ii],
                                                self.data[i].data[0][0][ii]),
                                            xytext=(-20, 20),
                                            textcoords='offset points',
                                            ha='right',
                                            va='bottom',
                                            bbox=dict(boxstyle='round,pad=0.5',
                                                      fc='yellow',
                                                      alpha=0.5),
                                            arrowprops=dict(
                                                arrowstyle='->',
                                                connectionstyle='arc3,rad=0'))

                #print(self.data[i].labels)
        elif self.plot_type == "wireframe":

            self.ax[0].set_xlabel('\n' + self.data[0].x_label + '\n (' +
                                  self.data[0].x_units + ")")
            self.ax[0].set_ylabel('\n' + self.data[0].y_label + '\n (' +
                                  self.data[0].y_units + ")")
            self.ax[0].set_zlabel('\n' + self.data[0].data_label + '\n (' +
                                  self.data[0].data_units + ")")

            self.log_3d_workaround()

            if self.force_data_max == False:
                my_max, my_min = dat_file_max_min(self.data[0])
                for i in range(0, len(self.data)):
                    my_max, my_min = dat_file_max_min(self.data[i],
                                                      cur_min=my_min,
                                                      cur_max=my_max)
            else:
                my_max = self.force_data_max
                my_min = self.force_data_min

            self.ax[0].set_zlim(my_min, my_max)

            for i in range(0, len(self.data)):

                if self.data[i].logx == True:
                    self.ax[i].set_xscale("log")

                if self.data[i].logy == True:
                    self.ax[i].set_yscale("log")

                #if self.data[i].key_text!="":
                key = "$" + numbers_to_latex(str(
                    self.data[i].key_text)) + " " + pygtk_to_latex_subscript(
                        self.data[0].key_units) + "$"

                X, Y = meshgrid(self.data[i].y_scale, self.data[i].x_scale)
                Z = self.data[i].data[0]

                # Plot the surface
                col = get_color(i)
                #print(self.data[i].plot_type,"here")
                if self.data[i].plot_type == "wireframe" or self.data[
                        i].plot_type == "":
                    im = self.ax[0].plot_wireframe(Y,
                                                   X,
                                                   array(Z),
                                                   color=col,
                                                   label=key,
                                                   clip_on=True)
                elif self.data[i].plot_type == "contour":
                    im = self.ax[0].contourf(Y, X, array(Z), color=col)
                elif self.data[i].plot_type == "heat":
                    my_max, my_min = dat_file_max_min(self.data[0])
                    im = self.ax[0].plot_surface(Y,
                                                 X,
                                                 array(Z),
                                                 linewidth=0,
                                                 vmin=my_min,
                                                 vmax=my_max,
                                                 cmap="hot",
                                                 antialiased=False)

                self.ax[0].legend()
                #im=self.ax[0].contourf( Y,X, Z,color=col)

#cset = ax.contourf(X, Y, Z, zdir='y', offset=40, cmap=cm.coolwarm)
        elif self.plot_type == "heat":
            self.ax[0].set_xlabel(self.data[0].y_label + " (" +
                                  self.data[0].y_units + ")")
            self.ax[0].set_ylabel(self.data[0].x_label + " (" +
                                  self.data[0].x_units + ")")
            my_max, my_min = dat_file_max_min(self.data[0])
            for i in range(0, len(self.data)):
                if self.data[i].logdata == True:
                    if my_min == 0:
                        my_min = 1.0
                    im = self.ax[0].pcolor(self.data[i].y_scale,
                                           self.data[i].x_scale,
                                           self.data[i].data[0],
                                           norm=LogNorm(vmin=my_min,
                                                        vmax=my_max),
                                           vmin=my_min,
                                           vmax=my_max,
                                           cmap="gnuplot")
                else:
                    im = self.ax[0].pcolor(self.data[i].y_scale,
                                           self.data[i].x_scale,
                                           self.data[i].data[0],
                                           vmin=my_min,
                                           vmax=my_max,
                                           cmap="gnuplot")

                self.cb = self.fig.colorbar(im)

        elif self.plot_type == "3d":
            self.ax[0].set_xlabel(self.data[0].x_label + " (" +
                                  self.data[0].x_units + ")")
            self.ax[0].set_ylabel(self.data[0].y_label + " (" +
                                  self.data[0].y_units + ")")
            i = 0
            y_scale = self.data[i].y_scale
            x_scale = self.data[i].x_scale
            X, Y = meshgrid(
                y_scale, x_scale)  #self.data[i].y_scale,self.data[i].x_scale
            Z = self.data[i].data[0]
            col = get_color(i)
            my_max, my_min = dat_file_max_min(self.data[0])
        elif self.plot_type == "rgb":
            self.ax[0].set_xlabel(self.data[0].y_label + " (" +
                                  str(self.data[0].y_units) + ")")
            self.ax[0].set_ylabel(self.data[0].data_label + " (" +
                                  self.data[0].data_units + ")")
            self.ax[0].imshow(self.data[0].data[0])  #
            #,extent=[self.data[0].y_scale[0],self.data[0].y_scale[-1],0,20]
        elif self.plot_type == "quiver":
            self.ax[0].set_xlabel(self.data[0].x_label + " (" +
                                  self.data[0].x_units + ")")
            self.ax[0].set_ylabel(self.data[0].y_label + " (" +
                                  self.data[0].y_units + ")")
            self.ax[0].set_zlabel(self.data[0].z_label + " (" +
                                  self.data[0].z_units + ")")
            X = []
            Y = []
            Z = []
            U = []
            V = []
            W = []
            mag = []
            for d in self.data[0].data:
                X.append(d.x)
                Y.append(d.y)
                Z.append(d.z)
                U.append(d.dx)
                V.append(d.dy)
                W.append(d.dz)
                mag.append(d.mag)

            c = plt.cm.hsv(mag)

            mag = []
            for d in self.data[0].data:

                mag.append(2.0)

            self.ax[0].quiver(X, Y, Z, U, V, W, colors=c, linewidths=mag)
            self.ax[0].set_xlim([0, self.data[0].xmax])
            self.ax[0].set_ylim([0, self.data[0].ymax])
            self.ax[0].set_zlim([0, self.data[0].zmax])

        #setup the key
        if self.data[0].legend_pos == "No key":
            self.ax[i].legend_ = None
        else:
            if len(files) < 40:
                self.fig.legend(all_plots, key_text, self.data[0].legend_pos)

        if get_lock().is_trial() == True:
            x = 0.25
            y = 0.25
            #while(x<1.0):
            #	y=0
            #	while(y<1.0):
            self.fig.text(x,
                          y,
                          'gpvdm trial',
                          fontsize=20,
                          color='gray',
                          ha='right',
                          va='bottom',
                          alpha=self.watermark_alpha)

            #		y=y+0.1
            #	x=x+0.25

        if self.hide_title == False:
            title = self.data[0].title
            if self.data[0].time != -1.0 and self.data[0].Vexternal != -1.0:
                mul, unit = time_with_units(self.data[0].time)
                title = title + " V=" + str(
                    self.data[0].Vexternal) + " " + _("time") + "=" + str(
                        self.data[0].time * mul) + " " + unit

            self.fig.suptitle(title)

            self.setWindowTitle(title + " - www.gpvdm.com")

        self.fig.canvas.draw()
Example #21
0
	def draw(self):
		self.screen.fill(get_color(Colors.NAVYBLUE))
		self.player.draw()
		for obj in ( self.enemy_list + self.obstacle_list ):
			obj.draw()
Example #22
0
class Enemy2:
    THICKNESS = 4
    RADIUS = 9
    COLOR = get_color(Colors.LIGHT_BLUE)

    current_screen = None
    current_position = Vector(0, 0)
    velocity = Vector(0, 0)
    ai = None
    max_speed = Vector(50, 50)
    m = 1
    closest_obstacle = None

    rotate_behaviour = None

    ahead = Vector(0, 0)

    priorities = [0.05, 0.7, 0.5]
    state = "E"
    triggered = False
    visible = True
    is_dead = False

    last_hit_by = None

    representation = None

    hp = 100
    hp_max = 100
    armour = 100
    ammo_railgun = 100
    ammo_bazooka = 100

    railgun_to = Vector(0, 0)
    draw_railgun = False

    low_hp_color = get_color(Colors.RED)
    hig_hp_color = get_color(Colors.GREEN)

    need_path = False
    destination = Vector(0, 0)
    path = []

    scaner = [[], []]

    def __init__(self, screen, screen_size, m_id):
        self.draw_railgun = False
        self.current_screen = screen
        self.screen_size = screen_size
        self.current_position = Vector(
            randrange(0, self.screen_size.x, POINT_DISTANCE),
            randrange(0, self.screen_size.y, POINT_DISTANCE))
        self.previous_position = self.current_position

        self.destination = self.current_position
        self.m_id = m_id

        self.distance = Vector(0.0, 0.0)
        self.accumulate = Vector(0.0, 0.0)

        self.ai = FiniteStateMachine(self)
        self.ai.set_current_state(StateWander())
        self.need_target = True
        self.can_react = True
        self.mouse_point = Vector(0, 0)
        self.closest_hideout = None

        self.representation = Triangle(self.RADIUS)
        self.rotate_behaviour = EnemyRotateBehavior(self.current_position)

        self.triggered = False
        self.visible = True
        self.is_dead = False

        self.look_at = Vector(0, 0)

    def check_intersection(self, shoot_from, shoot_to):
        v_shoot = shoot_to - shoot_from
        v_enemy = self.current_position - shoot_from
        dot = v_shoot.norm().dot(v_enemy.norm())

        point = None
        if dot > 0:
            v_len = v_enemy.len()
            if v_len > v_shoot.len(): return point
            if dot > 1: dot = 1
            if dot < -1: dot = -1
            angle = math.acos(dot)
            distance = 2 * math.tan(angle / 2) * v_len
            if distance <= self.RADIUS:
                v = v_shoot.norm() * v_len
                point = shoot_from + v

        return point

    def process_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.mouse_point = Vector(event.pos[0], event.pos[1])

        if event.type == Events.HIT_ENEMY_CHECK:
            point = self.check_intersection(event.pt_from, event.pt_to)

            if point is not None:
                self.is_dead = True

    def bazooka_shot(self, direction):
        rise_event(
            Events.SHOOT2, {
                "atack_type": "Baz",
                "fro": self.current_position + direction.norm() * 15,
                "direction": direction * self.velocity.len()
            })
        self.ammo_bazooka -= 10

    def railgun_shot(self, direction):
        if self.draw_railgun: return
        self.railgun_to = self.current_position + (direction.norm() * 400)
        rise_event(
            Events.SHOOT2, {
                "atack_type": "Rai",
                "enemy_id": self.m_id,
                "fro": self.current_position + direction.norm() * 15,
                "to": self.current_position + (direction.norm() * 400)
            })
        self.ammo_railgun -= 30
        self.railgun_time_to_draw = time.time()

    def update(self, delta):
        if self.hp < 0: self.is_dead = True
        self.previous_position = self.current_position
        self.current_position += self.velocity * delta
        self.handle_rotation()

    def add_statistic(self, tab):
        if tab[0] == "HP":
            self.hp += tab[1]
            if self.hp > self.hp_max: self.hp = self.hp_max
        if tab[0] == "AA": self.armour += tab[1]
        if tab[0] == "AB": self.ammo_bazooka += tab[1]
        if tab[0] == "AR": self.ammo_railgun += tab[1]

        percent = (self.hp if self.hp > 0 else 0) / self.hp_max
        if percent > 1: percent = 1

        self.COLOR = (self.low_hp_color[0] * (1 - percent) +
                      self.hig_hp_color[0] * percent, self.low_hp_color[1] *
                      (1 - percent) + self.hig_hp_color[1] * percent,
                      self.low_hp_color[2] * (1 - percent) +
                      self.hig_hp_color[2] * percent)

    def set_to_railgun(self, point):
        self.railgun_to = point
        self.draw_railgun = True

    def handle_rotation(self):
        self.rotate_behaviour.update_position(self.current_position,
                                              self.look_at)
        if self.rotate_behaviour.get_rotation_change():
            self.representation.rotate(
                self.rotate_behaviour.get_rotation_angle())

    def deal_dmg(self, dmg):
        self.hp -= (1 - (self.armour / 100)) * dmg
        self.armour -= dmg

        if self.armour < 0: self.armour = 0

        percent = (self.hp if self.hp > 0 else 0) / self.hp_max
        if percent > 1: percent = 1

        self.COLOR = (self.low_hp_color[0] * (1 - percent) +
                      self.hig_hp_color[0] * percent, self.low_hp_color[1] *
                      (1 - percent) + self.hig_hp_color[1] * percent,
                      self.low_hp_color[2] * (1 - percent) +
                      self.hig_hp_color[2] * percent)

    def get_ammo(self):
        return [self.ammo_railgun, self.ammo_bazooka]

    def is_in_obstacle(self, point):
        if point.distance_to(self.current_position).len() < self.RADIUS:
            return True
        return False

    def get_hit(self, missle, dmg=0):
        if missle == None:
            self.deal_dmg(dmg)
            return

        if self.last_hit_by != missle:
            self.last_hit_by = missle
            self.deal_dmg(missle.get_dmg())
            return

    def draw(self):
        pygame.draw.line(self.current_screen, get_color(Colors.CRIMSON),
                         self.current_position.to_table(),
                         (self.current_position +
                          (self.velocity.norm() * 50)).to_table(), 2)
        if self.draw_railgun:
            pygame.draw.line(self.current_screen, get_color(Colors.ORANGERED),
                             (self.current_position +
                              (self.velocity.norm() * 5)).to_table(),
                             (self.railgun_to).to_table(), 2)
            if time.time() - self.railgun_time_to_draw > 0.67:
                self.draw_railgun = False

        pygame.draw.circle(self.current_screen, get_color(Colors.BLUE),
                           self.current_position.to_table(), 250, 1)

        #	pygame.draw.line(self.current_screen, get_color(Colors.KHAKI) ,self.current_position.to_table(), ( self.destination ).to_table() , 2 )

        for p in range(len(self.path) - 1):
            pygame.draw.line(self.current_screen, get_color(Colors.KHAKI),
                             (self.path[p]).to_table(),
                             (self.path[p + 1]).to_table(), 2)

        font = pygame.font.SysFont("consolas", int(10))
        text = font.render(
            str(self.ammo_bazooka) + " : " + str(self.ammo_railgun) + " \n " +
            self.ai.current_state.state, True, self.COLOR)
        text_rect = text.get_rect(center=(self.current_position.x,
                                          self.current_position.y - 20))
        self.current_screen.blit(text, text_rect)

        text = font.render(str(self.m_id), True, get_color(Colors.YELLOW))
        text_rect = text.get_rect(center=(self.current_position.x,
                                          self.current_position.y - 40))
        self.current_screen.blit(text, text_rect)

        #		self.armour += 1
        if self.visible and not self.is_dead and not self.triggered:
            #ARMOUR
            pygame.draw.circle(self.current_screen, get_color(Colors.WHITE),
                               self.current_position.to_table(),
                               int(10 * self.armour / 100))
            #BODY
            pygame.draw.polygon(
                self.current_screen, self.COLOR,
                self.representation.to_draw(self.current_position),
                self.THICKNESS)
            #BAZZOKA
            pygame.draw.circle(
                self.current_screen, get_color(Colors.GOLD),
                self.representation.get_verticle(1, self.current_position),
                int(0.50 * self.ammo_bazooka / 10))
            #RAILGUN
            pygame.draw.circle(
                self.current_screen, get_color(Colors.DARK_VIOLET),
                self.representation.get_verticle(2, self.current_position),
                int(1 * self.ammo_railgun / 30))
        elif not self.visible:
            pass
    #		pygame.draw.circle(self.current_screen, get_color(Colors.DARK_YELLOW), self.current_position.to_table(), self.RADIUS, self.THICKNESS )
        elif self.triggered:
            pygame.draw.polygon(
                self.current_screen, get_color(Colors.YELLOW),
                self.representation.to_draw(self.current_position),
                self.THICKNESS)
        else:
            pygame.draw.polygon(
                self.current_screen, get_color(Colors.RED),
                self.representation.to_draw(self.current_position),
                self.THICKNESS)

    #	pygame.draw.line(self.current_screen, get_color(Colors.RED),self.current_position.to_table(), ( self.current_position + self.velocity).to_table(), 2 )
    #	pygame.draw.line(self.current_screen, get_color(Colors.BLUE),Vector(512,0).to_table(), Vector(512,720).to_table(), 2 )
Example #23
0
    def draw(self):
        pygame.draw.line(self.current_screen, get_color(Colors.CRIMSON),
                         self.current_position.to_table(),
                         (self.current_position +
                          (self.velocity.norm() * 50)).to_table(), 2)
        if self.draw_railgun:
            pygame.draw.line(self.current_screen, get_color(Colors.ORANGERED),
                             (self.current_position +
                              (self.velocity.norm() * 5)).to_table(),
                             (self.railgun_to).to_table(), 2)
            if time.time() - self.railgun_time_to_draw > 0.67:
                self.draw_railgun = False

        pygame.draw.circle(self.current_screen, get_color(Colors.BLUE),
                           self.current_position.to_table(), 250, 1)

        #	pygame.draw.line(self.current_screen, get_color(Colors.KHAKI) ,self.current_position.to_table(), ( self.destination ).to_table() , 2 )

        for p in range(len(self.path) - 1):
            pygame.draw.line(self.current_screen, get_color(Colors.KHAKI),
                             (self.path[p]).to_table(),
                             (self.path[p + 1]).to_table(), 2)

        font = pygame.font.SysFont("consolas", int(10))
        text = font.render(
            str(self.ammo_bazooka) + " : " + str(self.ammo_railgun) + " \n " +
            self.ai.current_state.state, True, self.COLOR)
        text_rect = text.get_rect(center=(self.current_position.x,
                                          self.current_position.y - 20))
        self.current_screen.blit(text, text_rect)

        text = font.render(str(self.m_id), True, get_color(Colors.YELLOW))
        text_rect = text.get_rect(center=(self.current_position.x,
                                          self.current_position.y - 40))
        self.current_screen.blit(text, text_rect)

        #		self.armour += 1
        if self.visible and not self.is_dead and not self.triggered:
            #ARMOUR
            pygame.draw.circle(self.current_screen, get_color(Colors.WHITE),
                               self.current_position.to_table(),
                               int(10 * self.armour / 100))
            #BODY
            pygame.draw.polygon(
                self.current_screen, self.COLOR,
                self.representation.to_draw(self.current_position),
                self.THICKNESS)
            #BAZZOKA
            pygame.draw.circle(
                self.current_screen, get_color(Colors.GOLD),
                self.representation.get_verticle(1, self.current_position),
                int(0.50 * self.ammo_bazooka / 10))
            #RAILGUN
            pygame.draw.circle(
                self.current_screen, get_color(Colors.DARK_VIOLET),
                self.representation.get_verticle(2, self.current_position),
                int(1 * self.ammo_railgun / 30))
        elif not self.visible:
            pass
    #		pygame.draw.circle(self.current_screen, get_color(Colors.DARK_YELLOW), self.current_position.to_table(), self.RADIUS, self.THICKNESS )
        elif self.triggered:
            pygame.draw.polygon(
                self.current_screen, get_color(Colors.YELLOW),
                self.representation.to_draw(self.current_position),
                self.THICKNESS)
        else:
            pygame.draw.polygon(
                self.current_screen, get_color(Colors.RED),
                self.representation.to_draw(self.current_position),
                self.THICKNESS)

    #	pygame.draw.line(self.current_screen, get_color(Colors.RED),self.current_position.to_table(), ( self.current_position + self.velocity).to_table(), 2 )
    #	pygame.draw.line(self.current_screen, get_color(Colors.BLUE),Vector(512,0).to_table(), Vector(512,720).to_table(), 2 )
Example #24
0
class PlayerActions:

    screen = None
    railgun_color = get_color(Colors.YELLOW)
    railgun_thick = 2
    sum_delta = 0

    shoot = False  # Shot started

    is_ready = True  # Check if can shoot
    can_draw = True  # Ready to draw
    r_to_draw = True

    player_position = Vector(0, 0)
    mouse_position = Vector(0, 0)
    pt_to = Vector(1, 1)

    def __init__(self, screen, position):
        self.player_position = position
        self.screen = screen

    def draw_railgun(self):

        pygame.draw.line(self.screen, self.railgun_color,
                         self.player_position.to_table(),
                         self.pt_to.to_table(), self.railgun_thick)

    def call_shoot_event(self):
        self.pt_to = self.player_position + (
            1260 * (self.mouse_position - self.player_position).norm())
        rise_event(Events.SHOOT, {
            "pt_from": self.player_position,
            "pt_to": self.pt_to
        })

    def distance(self, P1, P2):
        return math.sqrt(((P1.x - P2.x)**2) + ((P1.y - P2.y)**2))

    def process_event(self, event):

        if event.type == Events.IS_READY:
            self.is_ready = True

        if event.type == pygame.MOUSEBUTTONDOWN:
            if self.is_ready:
                self.shoot = True
                self.can_draw = False
                self.is_ready = False
                self.mouse_position = (Vector(event.pos[0], event.pos[1]))
                self.call_shoot_event()

        if event.type == Events.INTERSECTION:
            if event.point.distance_to(
                    self.player_position).len() < self.pt_to.distance_to(
                        self.player_position).len():
                self.pt_to = event.point
            self.can_draw = True

    def draw(self):
        if not self.is_ready and self.shoot and self.can_draw:
            rise_event(Events.HIT_ENEMY_CHECK, {
                "pt_from": self.player_position,
                "pt_to": self.pt_to
            })
            self.draw_railgun()

    def update(self, delta, position):
        self.player_position = position
        if self.shoot:
            self.sum_delta += delta
            if (self.sum_delta > 0.08):
                self.shoot = False
                self.sum_delta = 0
Example #25
0
 def get_color(self, color):
     """ Do use this method on all colors given in constructors. Possible color values are integers
     (best given as hex 0xRRGGBB) or tuples (RRR, GGG, BB)"""
     return mod_colors.get_color(color)
Example #26
0
 def draw(self, block):
   drawable = self.window
   gc = drawable.new_gc()
   gc.set_foreground(self.get_colormap().alloc_color(colors.get_color(block.temp, self.color_grade)))
   gc.fill = gtk.gdk.SOLID
   drawable.draw_rectangle(gc, True, block.px, block.py, BLOCK_WD, BLOCK_HG)
Example #27
0
def infer_image(graph, input_fifo, output_fifo, img, frame):

    #score_threshold = 0.45
    score_threshold = 0.20
    iou_threshold = 0.25

    # Write the image to the input queue and queue the inference in one call
    graph.queue_inference_with_fifo_elem(input_fifo, output_fifo, img, None)

    # Get the results from the output queue
    output, userobj = output_fifo.read_elem()

    # Get execution time
    inference_time = graph.get_option(mvnc.GraphOption.RO_TIME_TAKEN)

    predictions = output

    input_width = frame.shape[1]
    input_height = frame.shape[0]

    w_scale = input_width / ARGS['dim'][0]
    h_scale = input_height / ARGS['dim'][1]

    input_image = frame

    #n_classes = 80
    n_classes = 4
    n_grid_cells = 13
    n_b_boxes = 5
    n_b_box_coord = 4

    classes = read_labels()

    # Pre-computed YOLOv2 shapes of the k=5 B-Boxes
    anchors = [
        0.57273, 0.677385, 1.87446, 2.06253, 3.33843, 5.47434, 7.88282,
        3.52778, 9.77052, 9.16828
    ]

    thresholded_predictions = []

    # IMPORTANT: reshape to have shape = [13 x 13 x (5 B-Boxes) x (4 Coords + 1 Obj score + 20 Class scores)]
    #predictions = np.reshape(predictions, (13, 13, 5, 85))
    predictions = np.reshape(predictions, (13, 13, 5, 9))

    # IMPORTANT: Compute the coordinates and score of the B-Boxes by considering the parametrization of YOLOv2
    for row in range(n_grid_cells):
        for col in range(n_grid_cells):
            for b in range(n_b_boxes):

                tx, ty, tw, th, tc = predictions[row, col, b, :5]

                # IMPORTANT: (416 img size) / (13 grid cells) = 32!
                center_x = (float(col) + sigmoid(tx)) * 32.0
                center_y = (float(row) + sigmoid(ty)) * 32.0

                roi_w = np.exp(tw) * anchors[2 * b + 0] * 32.0
                roi_h = np.exp(th) * anchors[2 * b + 1] * 32.0

                final_confidence = sigmoid(tc)

                # Find best class
                class_predictions = predictions[row, col, b, 5:]
                class_predictions = softmax(class_predictions)

                class_predictions = tuple(class_predictions)

                best_class = class_predictions.index(max(class_predictions))
                best_class_score = class_predictions[best_class]

                # Flip the coordinates on both axes
                left = int(center_x - (roi_w / 2.))
                right = int(center_x + (roi_w / 2.))
                top = int(center_y - (roi_h / 2.))
                bottom = int(center_y + (roi_h / 2.))

                if ((final_confidence * best_class_score) > score_threshold):
                    thresholded_predictions.append(
                        [[left, top, right,
                          bottom], final_confidence * best_class_score,
                         classes[best_class]])

    # Sort the B-boxes by their final score
    thresholded_predictions.sort(key=lambda tup: tup[1], reverse=True)

    # Non maximal suppression
    nms_predictions = []

    if (len(thresholded_predictions) > 0):
        nms_predictions = non_maximal_suppression(thresholded_predictions,
                                                  iou_threshold)

    # Draw final B-Boxes and label on input image
    biggest_object = (0, ())

    # nms_predictions 是 predict完成的 list
    for i in range(len(nms_predictions)):

        # nms_predictions:  [[left, right ,top , bottom], confidence, best_class_name]
        # nms_predictions:  [[101, 211, 175, 333], 0.32828456752606966, '1_pepper_young']

        # left, right ,top , bottom
        xmin = int(nms_predictions[i][0][0] * w_scale)
        ymin = int(nms_predictions[i][0][1] * h_scale)
        xmax = int(nms_predictions[i][0][2] * w_scale)
        ymax = int(nms_predictions[i][0][3] * h_scale)

        # Dimention of B-Box
        box_width = xmax - xmin
        box_height = ymax - ymin

        # Center point of B-Box
        centroid = (int(box_width / 2 + xmin), int(box_height / 2 + ymin))

        # Confidence
        confidence = '{:.2f}%'.format(nms_predictions[i][1] * 100)

        # Get best class name
        best_class_name = nms_predictions[i][2]

        # Show predict information
        #print('class: ' + best_class_name +
        #      ', confidence: ' + str(confidence) +
        #      ', took: ' + str(np.sum(inference_time)) + ' ms' +
        #      ', center coodinate: ' + str(centroid) +
        #      ', top left coodinate: ' + str(xmin) + ', ' + str(ymax)
        #     )

        center_x, center_y = centroid

        print('aia#' + best_class_name + '#' + str(confidence) + '#' +
              str(np.sum(inference_time)) + '#' + str(center_x) + '#' +
              str(center_y) + '#' + str(xmin) + '#' + str(ymax))

        # Compose label text of B-Box
        label_str = best_class_name + ': ' + confidence

        # Calclate label text size
        text_size = cv2.getTextSize(label_str, cv2.FONT_HERSHEY_SIMPLEX,
                                    1.1e-3 * input_image.shape[0], 3)

        width, height = text_size[0][0], text_size[0][1]

        # B-Box color
        b_box_color = get_color(classes.index(best_class_name))

        # Label background region
        region = np.array([[xmin - 3, ymin], [xmin - 3, ymin - height - 26],
                           [xmin + width + 13, ymin - height - 26],
                           [xmin + width + 13, ymin]],
                          dtype='int32')

        # Put a class rectangle with B-Box coordinates and a class label on the image
        input_image = cv2.circle(input_image, centroid, 5, b_box_color, -1)

        # Draw B-Box
        input_image = cv2.rectangle(input_image, (xmin, ymin), (xmax, ymax),
                                    b_box_color, 3)

        cv2.fillPoly(img=input_image, pts=[region], color=b_box_color)

        #cv2.putText(input_image, label_str, (xmin + 5, ymin - 10),
        #            cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,0,0), 1)

        cv2.putText(img=input_image,
                    text=label_str,
                    org=(xmin + 13, ymin - 13),
                    fontFace=cv2.FONT_HERSHEY_SIMPLEX,
                    fontScale=1e-3 * input_image.shape[0],
                    color=(0, 0, 0),
                    thickness=2)

        #cv2.imshow('Pepper', input_image)

    img_path, img_filename = os.path.split(ARGS['image'])

    cv2.imwrite(os.path.join('pepper_img_out', img_filename), input_image)
    print('#image#', os.path.join('pepper_img_out', img_filename))

    # If a display is available, show the image on which inference was performed
    if 'DISPLAY' in os.environ:
        cv2.imshow('NCS live inference', input_image)
Example #28
0
class Obstacle:
    RADIUS = 0
    COLOR_OUT = get_color(Colors.LIGHT_PURPLE)
    THICK = 2

    id = -1
    state = "Const"

    color = (0, 0, 0)
    thick = 0.0
    current_screen = None
    screen_size = Vector(0, 0)
    current_position = Vector(0, 0)
    velocity = Vector(0, 0)
    triangle = None

    def __init__(self, screen, screen_size, id, obs_list):
        self.RADIUS = randint(15, 35)
        self.current_screen = screen
        self.screen_size = screen_size

        self.id = id
        self.set_position(obs_list)
        self.triangle = Triangle(self.RADIUS)
        self.triangle.scale_back_line(1024)

#		points = self.intersection_points(Vector(3,2), 2, Vector(0,2))
#		print(str(points[0]))
#		print(str(points[1]))

    def set_position(self, obs_list):

        if len(obs_list) == 0:
            self.current_position = self.random_position()

        else:
            self.current_position = self.random_position()
            for i in range(len(obs_list)):
                if not self.check_position(obs_list[i]):
                    self.current_position = self.random_position()
                    self.set_position(obs_list)

        self.face = Vector(self.current_position.x,
                           self.current_position.y - 200)

    def random_position(self):
        position = Vector(randint(0, self.screen_size.x),
                          randint(0, self.screen_size.y))
        if (position.x >= 462 and position.x <= 562 and position.y >= 310
                and position.y <= 410):
            # player start position: Vector(512,360)
            position = self.random_position()
        return position

    def check_position(self, other):
        distance = (self.current_position - other.current_position).len()
        if distance > (self.RADIUS + other.RADIUS): return True
        else: return False

    def draw_id_number(self):
        font = pygame.font.SysFont("consolas", self.RADIUS - 3)

        text = font.render(str(self.id), True, self.COLOR_OUT)
        text_rect = text.get_rect(center=(self.current_position.x,
                                          self.current_position.y))
        self.current_screen.blit(text, text_rect)

    def draw(self):
        pygame.draw.circle(self.current_screen, get_color(Colors.LIGHT_PURPL2),
                           self.current_position.to_table(), self.RADIUS)
        pygame.draw.circle(self.current_screen, self.COLOR_OUT,
                           self.current_position.to_table(), self.RADIUS,
                           self.THICK)
        pygame.draw.polygon(self.current_screen, get_color(Colors.LIGHTER_RED),
                            self.triangle.to_draw(self.current_position), 1)

    #	self.draw_id_number()

    def is_in_shade(self, point):
        return self.triangle.is_in_triangle(point)

    def check_intersection(self, shoot_from, shoot_to):
        shot_dir = (shoot_to - shoot_from).norm()
        to_obs = self.current_position - shoot_from
        dot = shot_dir.dot(to_obs.norm())

        if dot <= 0: return None
        else:
            distance = (self.current_position - shoot_from -
                        shot_dir * to_obs.len()).len()

            if distance > self.RADIUS: return None
            else: return shoot_from + shot_dir * to_obs.len()

    def process_event(self, event):

        if event.type == Events.SHOOT:

            point = self.check_intersection(event.pt_from, event.pt_to)

            if point is None:
                point = event.pt_to

            rise_event(Events.INTERSECTION, {"point": point})

    def set_player_position(self, position):
        self.player_position = position
        self.angle = (self.face - self.current_position).norm().angle_between(
            (position - self.current_position).norm())

    def process_physics(self):
        pass

    angle = 0

    def update(self, delta):

        self.triangle.rotate(self.angle)

        pass
Example #29
0
class Enemy2:
    THICKNESS = 6
    RADIUS = 6
    COLOR = get_color(Colors.LIGHT_BLUE)

    current_screen = None
    current_position = Vector(0, 0)
    velocity = Vector(0, 0)
    ai = None
    max_speed = Vector(50, 50)
    m = 1
    closest_obstacle = None

    ahead = Vector(0, 0)

    priorities = [0.05, 0.7, 0.5]
    state = "E"
    triggered = False
    visible = True
    is_dead = False

    def __init__(self, screen, screen_size, id):

        self.current_screen = screen
        self.screen_size = screen_size
        self.current_position = Vector(randint(0, self.screen_size.x),
                                       randint(0, self.screen_size.y))
        self.previous_position = self.current_position

        self.destination = self.current_position
        self.id = id

        self.distance = Vector(0.0, 0.0)
        self.accumulate = Vector(0.0, 0.0)

        self.ai = FiniteStateMachine(self)
        self.ai.set_current_state(SteringWander())
        self.need_target = True
        self.can_react = True
        self.mouse_point = Vector(0, 0)
        self.closest_hideout = None

        self.triggered = False
        self.visible = True
        self.is_dead = False

    def check_intersection(self, shoot_from, shoot_to):
        shot_dir = (shoot_to - shoot_from).norm()
        to_enemy = self.current_position - shoot_from
        dot = shot_dir.dot(to_enemy.norm())

        if dot <= 0: return None
        else:
            if to_enemy.len() > (shoot_to - shoot_from).len(): return None
            distance = (self.current_position - shoot_from -
                        shot_dir * to_enemy.len()).len()

            if distance > self.RADIUS: return None
            else: return shoot_from + shot_dir * to_enemy.len()

    def process_event(self, event):
        if event.type == pygame.MOUSEMOTION:
            self.mouse_point = Vector(event.pos[0], event.pos[1])

        if event.type == Events.HIT_ENEMY_CHECK:
            point = self.check_intersection(event.pt_from, event.pt_to)

            if point is not None:
                self.is_dead = True

    def update(self, delta):
        self.previous_position = self.current_position
        self.current_position += self.velocity * delta

    def draw(self):
        if self.visible and not self.is_dead and not self.triggered:
            pygame.draw.circle(self.current_screen, self.COLOR,
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)
        elif not self.visible:
            pass
    #		pygame.draw.circle(self.current_screen, get_color(Colors.DARK_YELLOW), self.current_position.to_table(), self.RADIUS, self.THICKNESS )
        elif self.triggered:
            pygame.draw.circle(self.current_screen, get_color(Colors.YELLOW),
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)
        else:
            pygame.draw.circle(self.current_screen, get_color(Colors.RED),
                               self.current_position.to_table(), self.RADIUS,
                               self.THICKNESS)

    #	pygame.draw.line(self.current_screen, get_color(Colors.RED),self.current_position.to_table(), ( self.current_position + self.velocity).to_table(), 2 )
    #	pygame.draw.line(self.current_screen, get_color(Colors.BLUE),Vector(512,0).to_table(), Vector(512,720).to_table(), 2 )
Example #30
0
class Player:

    id = 0
    HP = 0
    THICK = 3
    RADIUS = 10
    COLOR_OUT = get_color(Colors.LIGHT_RED)
    COLOR_IN = get_color(Colors.LIGHTER_RED)
    screen = None
    move_behavior = None
    rotate_behavior = None
    actions_behavior = None

    state = "P"
    current_position = Vector(0, 0)
    previous_position = Vector(0, 0)
    velocity = Vector(0, 0)
    mouse_point = Vector(0, 0)
    screen_size = Vector(0, 0)
    graphic = Triangle(0)
    freeze = False
    speed = Vector(100.0, 100.0)

    def __init__(self, position, screen, hp):
        self.graphic = Triangle(12)
        self.current_position = position
        self.previous_position = position
        self.screen = screen
        self.move_behavior = PlayerMoveBehavior(position)
        self.rotate_behavior = PlayerRotateBehavior(position)
        self.actions_behavior = PlayerActions(screen, position)
        self.HP = hp

    def get_HP(self):
        return self.HP

    def decrease_HP(self, amount):
        self.HP -= amount

    def draw(self):

        self.actions_behavior.draw()

        pygame.draw.polygon(self.screen, self.COLOR_IN,
                            self.graphic.to_draw(self.current_position))

        pygame.draw.polygon(self.screen, self.COLOR_OUT,
                            self.graphic.to_draw(self.current_position),
                            self.THICK)

    def process_event(self, event):

        if event.type == Events.COLLIDE:
            self.current_position = event.where - self.velocity
            self.freeze = True

        self.actions_behavior.process_event(event)

        if event.type == pygame.MOUSEMOTION:
            self.mouse_point = (Vector(event.pos[0], event.pos[1]))
            self.rotate_behavior.process_event(event)

        if event.type == pygame.KEYDOWN or event.type == pygame.KEYUP:
            self.move_behavior.process_event(event)

    def __move(self, delta):
        self.previous_position = self.move_behavior.get_current_position()
        self.velocity = self.move_behavior.get_velocity()
        self.current_position += (self.velocity * delta) * self.speed
        self.rotate_behavior.update_position(self.current_position)

    def handle_rotation(self):
        if self.rotate_behavior.get_rotation_change():
            self.graphic.rotate(self.rotate_behavior.get_rotation_angle())

    def update(self, delta):
        if not self.freeze:
            self.__move(delta)
            self.move_behavior.handle_orientation_key_press()
        else:
            self.freeze = False
        self.handle_rotation()
        self.actions_behavior.update(delta, self.current_position)
Example #31
0
	def do_plot(self):
		if len(self.data)==0:
			return
		
		if self.data[0].valid_data==False:
			return

		self.fig.clf()
		self.fig.subplots_adjust(bottom=0.2)
		self.fig.subplots_adjust(bottom=0.2)
		self.fig.subplots_adjust(left=0.1)
		self.fig.subplots_adjust(hspace = .001)
		dim=""
		if self.data[0].x_len==1 and self.data[0].z_len==1:
			dim="linegraph"
		elif self.data[0].x_len>1 and self.data[0].y_len>1 and self.data[0].z_len==1:
			if self.data[0].type=="3d":
				dim="wireframe"
			if self.data[0].type=="heat":
				dim="heat"
		elif self.data[0].x_len>1 and self.data[0].y_len>1 and self.data[0].z_len>1:
			print("ohhh full 3D")
			dim="3d"
		else:
			print(_("I don't know how to process this type of file!"),self.data[0].x_len, self.data[0].y_len,self.data[0].z_len)
			return

		title=self.data[0].title
		if self.data[0].time!=-1.0 and self.data[0].Vexternal!=-1.0:
			mul,unit=time_with_units(self.data[0].time)
			title=self.data[0].title+" V="+str(self.data[0].Vexternal)+" "+_("time")+"="+str(self.data[0].time*mul)+" "+unit

		self.fig.suptitle(title)

		self.setWindowTitle(title+" - www.gpvdm.com")

		self.ax=[]


		for i in range(0,len(self.input_files)):
			if dim=="linegraph":
				self.ax.append(self.fig.add_subplot(111,axisbg='white'))
			elif dim=="wireframe":
				self.ax.append(self.fig.add_subplot(111,axisbg='white' ,projection='3d'))
			elif dim=="heat":
				self.ax.append(self.fig.add_subplot(111,axisbg='white'))
			elif dim=="3d":
				self.ax.append(self.fig.add_subplot(111,axisbg='white' ,projection='3d'))
			#Only place label on bottom plot
			#	if self.data[i].type=="3d":
			#else:
			#	self.ax[i].tick_params(axis='x', which='both', bottom='off', top='off',labelbottom='off') # labels along the bottom edge are off

			#Only place y label on center plot
			if self.data[0].normalize==True or self.data[0].norm_to_peak_of_all_data==True:
				y_text="Normalized "+self.data[0].data_label
				data_units="au"
			else:
				data_text=self.data[i].data_label
				data_units=self.data[i].data_units

			if self.data[0].logx==True:
				self.ax[i].set_xscale("log")

			if self.data[0].logy==True:
				self.ax[i].set_yscale("log")


		all_plots=[]
		files=[]
		my_max=1.0

			
		if dim=="linegraph":		#This is for the 1D graph case
			self.ax[0].set_xlabel(self.data[0].x_label+" ("+str(self.data[0].x_units)+")")
			self.ax[0].set_ylabel(self.data[0].data_label+" ("+self.data[0].data_units+")")

			for i in range(0,len(self.input_files)):
				cur_plot, = self.ax[i].plot(self.data[i].y_scale,self.data[i].data[0][0], linewidth=3 ,alpha=1.0,color=get_color(i),marker=get_marker(i))

				if self.labels[i]!="":
					files.append("$"+numbers_to_latex(str(self.labels[i]))+" "+pygtk_to_latex_subscript(self.data[0].key_units)+"$")

				all_plots.append(cur_plot)
				
				if len(self.data[i].labels)!=0:
					for ii in range(0,len(self.data[i].y_scale)):
						fx_unit=fx_with_units(float(self.data[i].labels[ii]))
						label_text=str(float(self.data[i].labels[ii])*fx_unit[0])+" "+fx_unit[1]
						self.ax[i].annotate(label_text,xy = (self.data[i].y_scale[ii], self.data[i].data[0][0][ii]), xytext = (-20, 20),textcoords = 'offset points', ha = 'right', va = 'bottom',bbox = dict(boxstyle = 'round,pad=0.5', fc = 'yellow', alpha = 0.5),arrowprops = dict(arrowstyle = '->', connectionstyle = 'arc3,rad=0'))
				#print(self.data[i].labels)
		elif dim=="wireframe":
			self.ax[0].set_xlabel(self.data[0].x_label+" ("+self.data[0].x_units+")")
			self.ax[0].set_ylabel(self.data[0].y_label+" ("+self.data[0].y_units+")")

			for i in range(0,len(self.input_files)):

				#new_data=[[float for y in range(self.data[0].y_len)] for x in range(self.data[0].x_len)]
				#for x in range(0,self.data[i].x_len):
				#	for y in range(0,self.data[i].y_len):
				#		print(x,y,len(self.data[i].data[0]),len(self.data[i].data[0][0]))
				#		new_data[x][y]=self.data[i].data[0][x][y]
				#z = 10 * outer(ones(size(data.x_scale)), cos(data.y_scale))
				#im=self.ax[0].plot_surface(data.x_scale,data.y_scale,z)
				#print(new_data)
				#print(self.data[i].x_scale)
				#print(self.data[i].y_scale)
				X, Y = meshgrid( self.data[i].y_scale,self.data[i].x_scale)
				Z = self.data[i].data[0]

				# Plot the surface
				im=self.ax[i].plot_wireframe( Y,X, Z)

				#pcolor
		elif dim=="heat":
			self.ax[0].set_xlabel(self.data[0].x_label+" ("+self.data[0].x_units+")")
			self.ax[0].set_ylabel(self.data[0].y_label+" ("+self.data[0].y_units+")")

			for i in range(0,len(self.input_files)):

				im=self.ax[0].pcolor(self.data[i].y_scale,self.data[i].x_scale,self.data[i].data[0])
				self.fig.colorbar(im)

				#pcolor

				#self.fig.colorbar(im, shrink=0.5, aspect=5)
				#self.ax[0].plot_surface(x, y, z, rstride=1, cstride=1, cmap=cm.coolwarm,linewidth=0, antialiased=False)
				#self.ax[0].invert_yaxis()
				#self.ax[0].xaxis.tick_top()
		elif dim=="3d":
			self.ax[0].set_xlabel(self.data[0].x_label+" ("+self.data[0].x_units+")")
			self.ax[0].set_ylabel(self.data[0].y_label+" ("+self.data[0].y_units+")")
			self.ax[0].set_zlabel(self.data[0].z_label+" ("+self.data[0].z_units+")")

			for ii in range(0,len(self.data[i].z_scale)):
				my_max,my_min=dat_file_max_min(self.data[i])
				X, Y = meshgrid( self.data[i].x_scale,self.data[i].y_scale)
				new_data=[[float for y in range(self.data[0].y_len)] for x in range(self.data[0].x_len)]
				for x in range(0,self.data[i].x_len):
					for y in range(0,self.data[i].y_len):
						new_data[x][y]=self.data[i].z_scale[ii]+self.data[i].data[ii][x][y]
				self.ax[i].contourf(X, Y, new_data, zdir='z')#

				self.ax[i].set_xlim3d(0, self.data[i].x_scale[-1])
				self.ax[i].set_ylim3d(0, self.data[i].y_scale[-1])
				self.ax[i].set_zlim3d(0, self.data[i].z_scale[-1])

		#setup the key
		if self.data[0].legend_pos=="No key":
			self.ax[i].legend_ = None
		else:
			if len(files)<40:
				self.fig.legend(all_plots, files, self.data[0].legend_pos)
			
		#self.fig.tight_layout(pad=0.0, w_pad=0.0, h_pad=0.0)
		self.fig.canvas.draw()
Example #32
0
 def fill_screen(self, screen):
     screen.fill(get_color(Colors.NAVYBLUE))
     return
Example #33
0
def data(key, value, size=None, label=None, label_position=None, color=None, fill_color=None):
    """
    Use this function to prepare data for all charts.
    """
    return ChartData(key, value, size, label, label_position, mod_colors.get_color(color),
                     mod_colors.get_color(fill_color))
Example #34
0
 def get_color(self, color_num):
     return colors.get_color(color_num)
Example #35
0
    def draw(self):
        """Draws the current menu to the screen."""
        self.draw_count += 1

        if DEBUG:
            self.debug_dict['draw_count'] = self.draw_count
            self.debug_dict['output_position'] = self.output_position

        # could be much cleverer here. Note what has changed and only
        # clear and redraw that.
        self.menu_window.clear()
        self.log_window.clear()

        anc_strings = self.ancestors_strings()
        for i, anc_str in enumerate(anc_strings):
            self.menu_window.addstr(
                i, 0, anc_str,
                colors.get_color(1))
        lines_shift = len(anc_strings)
        num_lines = self.scroll_end - lines_shift
        items = self.get_children(self.current_parent)
        try:
            current_item_pos = items.index(self.current_position)
        except:
            current_item_pos = 0

        start, stop = self.scroll_position, self.scroll_position + num_lines

        # make sure that the current item will be displayed
        if (current_item_pos < start):
            start = current_item_pos
            stop = current_item_pos + num_lines
        elif (current_item_pos >= stop):
            start = current_item_pos - num_lines + 1
            stop = current_item_pos + 1

        # if start is negative, shift both upward
        if start < 0:
            start = 0
            stop = stop + abs(start)

        # if stop is after the end of items, clip it
        stop = min(stop, len(items))
        self.scroll_position = start

        items = items[start:stop]

        for i, item in enumerate(items):
            color = colors.get_color(1)
            string = item.name
            if item is self.current_position:
                color = colors.get_color(2)
                string = '>' + string + '<'
            if item.func_isset():
                string += '*'
            if self.get_children(item):
                string += ' >>'
            y_pos = i + lines_shift

            self.menu_window.addstr(y_pos, 0, string, color)

        color = colors.get_color(1)

        if self.process_running:
            self.log_window.addstr(0, 0, 'running', color)
        self.update_ouput_list()

        for i, output_string in enumerate(self.output_list):
            self.log_window.addstr(i+1, 0, output_string, color)

        if DEBUG:
            for i, (key, value) in enumerate(list(self.debug_dict.items())):
                self.log_window.addstr(
                    i+11, 0, '{key} = {value}'.format(
                        key=key, value=value),
                    color)

        self.menu_window.refresh()
        self.log_window.refresh()
        self.screen.refresh()
Example #36
0
    def get_color(**kwargs):
        color = get_color("", **kwargs)
        if color:
            return color[:-4]

        return color