def get_nth_polygon_grid(self, num): polygon_edge_coordinates = self.get_nth_polygon_edge_coordinates(num) min_xcor, min_ycor, x_range, y_range = self.get_screen_info( polygon_edge_coordinates) grid = Screen.Screen(x_range + 2 * self.matrix_border_offset, y_range + 2 * self.matrix_border_offset) for index in xrange(len(polygon_edge_coordinates) - 1): coordinate_pair1, coordinate_pair2 = polygon_edge_coordinates[ index:index + 2] grid_x1 = int((coordinate_pair1[0] - min_xcor) * 10) + self.matrix_border_offset grid_y1 = y_range + self.matrix_border_offset - int( (coordinate_pair1[1] - min_ycor) * 10) grid_x2 = int((coordinate_pair2[0] - min_xcor) * 10) + self.matrix_border_offset grid_y2 = y_range + self.matrix_border_offset - int( (coordinate_pair2[1] - min_ycor) * 10) draw.draw_line(grid, grid_x1, grid_y1, grid_x2, grid_y2) draw.flood_fill(grid, 0, 0, 2, 0) first_interior_coordinate_match = re.search(' ', image_string(grid)) while first_interior_coordinate_match is not None: num_of_elems_in_row = x_range + 2 * self.matrix_border_offset draw.flood_fill( grid, first_interior_coordinate_match.start() % num_of_elems_in_row, first_interior_coordinate_match.start() / num_of_elems_in_row, 1, 0) first_interior_coordinate_match = re.search( ' ', image_string(grid)) # draw.flood_fill(grid, 0, 0, 0, 2) return grid
def draw(self, color='b'): """ Draw the COM trajectory. Parameters ---------- color : char or triplet, optional Color letter or RGB values, default is 'b' for green. Returns ------- handle : openravepy.GraphHandle OpenRAVE graphical handle. Must be stored in some variable, otherwise the drawn object will vanish instantly. """ handles = draw_trajectory(self.P, color=color) handles.extend(draw_trajectory(self.Z, color='m')) com_last = self.p_last dcm_last = self.p_last + self.pd_last / self.omega cp_target = self.dcm_target + gravity / self.omega2 cp_last = dcm_last + gravity / self.omega2 for k in xrange(self.nb_steps): p, z = self.P[k], self.Z[k] handles.append(draw_line(z, p, color='c', linewidth=0.2)) handles.extend([ draw_point(self.dcm_target, color='b', pointsize=0.025), draw_point(cp_target, color='b', pointsize=0.025), draw_line(self.dcm_target, cp_target, color='b', linewidth=1), draw_point(com_last, color='g', pointsize=0.025), draw_point(cp_last, color='g', pointsize=0.025), draw_line(com_last, cp_last, color='g', linewidth=1), ]) return handles
def expose_titlebar_separator(self, widget, event): '''Expose nav separator.''' # Init. cr = widget.window.cairo_create() rect = widget.allocation # Draw separator. cr.set_source_rgba(1, 1, 1, 0.5) draw_line(cr, rect.x + 1, rect.y + 2, rect.x + rect.width - 1, rect.y + 1) return True
def expose_button(self, widget, event): '''Expose button.''' # Init. cr = widget.window.cairo_create() rect = widget.allocation x, y, w, h = rect.x, rect.y, rect.width, rect.height # Get color info. if widget.state == gtk.STATE_NORMAL: text_color = ui_theme.get_color("button_font").get_color() border_color = ui_theme.get_color("button_border_normal").get_color() background_color = ui_theme.get_shadow_color("button_background_normal").get_color_info() elif widget.state == gtk.STATE_PRELIGHT: text_color = ui_theme.get_color("button_font").get_color() border_color = ui_theme.get_color("button_border_prelight").get_color() background_color = ui_theme.get_shadow_color("button_background_prelight").get_color_info() elif widget.state == gtk.STATE_ACTIVE: text_color = ui_theme.get_color("button_font").get_color() border_color = ui_theme.get_color("button_border_active").get_color() background_color = ui_theme.get_shadow_color("button_background_active").get_color_info() elif widget.state == gtk.STATE_INSENSITIVE: text_color = ui_theme.get_color("disable_text").get_color() border_color = ui_theme.get_color("disable_frame").get_color() disable_background_color = ui_theme.get_color("disable_background").get_color() background_color = [(0, (disable_background_color, 1.0)), (1, (disable_background_color, 1.0))] # Draw background. draw_vlinear( cr, x + 1, y + 1, w - 2, h - 2, background_color) # Draw border. cr.set_source_rgb(*color_hex_to_cairo(border_color)) draw_line(cr, x + 2, y + 1, x + w - 2, y + 1) # top draw_line(cr, x + 2, y + h, x + w - 2, y + h) # bottom draw_line(cr, x + 1, y + 2, x + 1, y + h - 2) # left draw_line(cr, x + w, y + 2, x + w, y + h - 2) # right # Draw four point. if widget.state == gtk.STATE_INSENSITIVE: top_left_point = ui_theme.get_pixbuf("button/disable_corner.png").get_pixbuf() else: top_left_point = ui_theme.get_pixbuf("button/corner.png").get_pixbuf() top_right_point = top_left_point.rotate_simple(270) bottom_right_point = top_left_point.rotate_simple(180) bottom_left_point = top_left_point.rotate_simple(90) draw_pixbuf(cr, top_left_point, x, y) draw_pixbuf(cr, top_right_point, x + w - top_left_point.get_width(), y) draw_pixbuf(cr, bottom_left_point, x, y + h - top_left_point.get_height()) draw_pixbuf(cr, bottom_right_point, x + w - top_left_point.get_width(), y + h - top_left_point.get_height()) # Draw font. draw_text(cr, self.label, x, y, w, h, self.font_size, text_color, alignment=pango.ALIGN_CENTER) return True
def expose_status_separator(self, widget, event): ''' Internal callback for `expose-event` signal. ''' # Init. cr = widget.window.cairo_create() rect = widget.allocation # Draw separator. cr.set_source_rgba(0, 0, 0, 0.5) draw_line(cr, rect.x + 1, rect.y + 1, rect.x + rect.width - 1, rect.y + 1) cr.set_source_rgba(1, 1, 1, 0.5) draw_line(cr, rect.x + 1, rect.y + 2, rect.x + rect.width - 1, rect.y + 2) return True
def show_com(self): """Show a red ball at the location of the center of mass.""" self.__show_com = True self.__com_handle = [ draw_point(self.com, pointsize=0.0005 * self.mass, color='r'), draw_line( self.com, self.com + [0., 0., -1.], linewidth=2., color='y')]
def draw_weather_grid(image, origin, displaysize): column_width = get_column_width(origin, displaysize) column_2_x = origin[0] + column_width column_3_x = origin[0] + (2 * column_width) draw.draw_line( image, (origin[0] + 7, displaysize[1], column_2_x - 6, displaysize[1])) draw.draw_line( image, (column_2_x + 7, displaysize[1], column_3_x - 6, displaysize[1])) draw.draw_line(image, (column_2_x, origin[1] + 5, column_2_x, displaysize[1] - 6)) draw.draw_line( image, (column_3_x + 7, displaysize[1], displaysize[0] - 6, displaysize[1])) draw.draw_line(image, (column_3_x, origin[1] + 5, column_3_x, displaysize[1] - 6))
def expose_titlebar_separator(self, widget, event): ''' Expose the separation line between the titlebar and the body of the window. @param widget: A widget of type Gtk.Widget. @param event: Not used. @return: Always return True. ''' # Init. cr = widget.window.cairo_create() rect = widget.allocation # Draw separator. cr.set_source_rgba(1, 1, 1, 0.5) draw_line(cr, rect.x + 1, rect.y + 2, rect.x + rect.width - 1, rect.y + 1) return True
def expose_nav_separator(self, widget, event): ''' Internal callback for `expose-event` signal. ''' # Init. cr = widget.window.cairo_create() rect = widget.allocation # Draw separator. cr.set_source_rgba(1, 1, 1, 0.5) draw_line(cr, rect.x + 1, rect.y + 1, rect.x + rect.width - 1, rect.y + 1) cr.set_source_rgba(0, 0, 0, 0.5) draw_line(cr, rect.x + 1, rect.y + 2, rect.x + rect.width - 1, rect.y + 2) return True
def on_tick(self, sim): if self.linestyle == '-': h = self.handles[self.next_index] if h is not None: h.Close() self.handles[self.next_index] = draw_line( self.last_pos, self.body.p, color=self.color, linewidth=self.linewidth) self.next_index = (self.next_index + 1) % self.buffer_size self.last_pos = self.body.p
def draw(self, ax): radius = self.radius().item() u, v = np.mgrid[0:2 * np.pi:20j, 0:np.pi:10j] x = np.cos(u) * np.sin(v) y = np.sin(u) * np.sin(v) z = np.cos(v) x = x * radius y = y * radius z = z * radius ax.plot_wireframe(x + self.p1.data[0].item(), y + self.p1.data[1].item(), z + self.p1.data[2].item(), color="g") ax.plot_wireframe(x + self.p2.data[0].item(), y + self.p2.data[1].item(), z + self.p2.data[2].item(), color="g") n = self.p2 - self.p1 h = torch.norm(n, 2) if h.item() > 0.0: n_hat = n / h q = torchext.normalize(perpendicular_vector(n_hat)) s = torchext.normalize(torch.cross(n_hat, q)) p1 = self.p1.detach().cpu().numpy() p2 = self.p2.detach().cpu().numpy() q = (q * radius).detach().cpu().numpy() s = (s * radius).detach().cpu().numpy() for theta in np.mgrid[0:2 * np.pi:20j]: offset = np.sin(theta) * q + np.cos(theta) * s draw.draw_line(ax, p1 + offset, p2 + offset, color="g")
A_x, A_y, A_z, B, F_x, F_y, F_z, F_f, F_o = build_model(pts1, pts2, pai_in_frame, L) # preliminary model #4 residuals = get_residuals(A_x, A_y, A_z, B, F_x, F_y, F_z, F_f, F_o, pts1, pts2) # generation of residual array B_values = [B] out = img1.copy() droped_out = [] points = bc_module.Points() for r in residuals: pt1 = r[1] pt2 = r[2] point = bc_module.Point(pt1, pt2) # pt1 + r[3] point.make_line() k, b = point.get_line() pt3 = pt1 + r[3] out = draw.draw_line(out, k, b, color = draw.gold) out = draw.draw_arrow(out, pt1, pt2) out = draw.draw_arrow(out, pt1, pt3, color=draw.cyan) points.add_point(pt1, pt2) out = draw.draw_text(out, (2 * Width//3, 30), 'A_x = {:02.05f}'.format(A_x), font_scale = fs, color = draw.blue) out = draw.draw_text(out, (2 * Width//3, 60), 'A_y = {:02.05f}'.format(A_y), font_scale = fs, color = draw.blue) out = draw.draw_text(out, (2 * Width//3, 90), 'A_z = {:02.05f}'.format(A_z), font_scale = fs, color = draw.blue) out = draw.draw_text(out, (2 * Width//3, 120), ' B = {:02.05f}'.format(B), font_scale = fs, color = draw.blue) PAI, _ = points.find_PAI() if _: out = draw.draw_arrow(out, pai_in_frame, PAI, color=draw.purple) out = draw.draw_point(out, PAI, color=draw.purple, thickness=3) cv2.imwrite('output/{}_A.png'.format(frame_itt), out) out = img1.copy()
def draw_rectangle(cr, x, y, w, h): draw_line(cr, x - 1, y, x + w, y) # top draw_line(cr, x, y + h, x + w, y + h) # bottom draw_line(cr, x, y, x, y + h) # left draw_line(cr, x + w, y, x + w, y + h - 1) # right
def center_road(pt_list, line_list, debug=False): def calc_y(pt0, pt1, x0): ax = pt1[0] - pt0[0] dx = x0 - pt0[0] if ax == 0 or dx == 0: return pt0[1] ay = pt1[1] - pt0[1] return dx / ax * ay + pt0[1] x_list, y_list = zip(*pt_list) min_ptx, max_ptx = min(x_list), max(x_list) # get max range for scan ln_list = [Line(line) for i, line in enumerate(line_list)] if debug: for line in line_list: draw_line(line) ln_list.sort() # begin scan # from left to right gene_list = [] # list [x, y] cnt_list = [] # not all points will affect the center point # avoid error on curve AFFECT_DIST = 30 # need MIN_SEG segments to get the mean value, in order to avoid sample insufficiency MIN_SEG = 5 cur_idx = 0 n_road = len(ln_list) pos = [0] * n_road scan_list = [cur_idx] cur_idx = 1 rm_cnt = 0 # scanline while len(scan_list) != 0: # find minx to update y minx, sel_idx = 1e10, -1 for idx in scan_list: p = pos[idx] # idx r = ln_list[idx].line # road x = r[p][0] # x if x < minx: minx, sel_idx = x, idx # check if new segment should be added if cur_idx < n_road: new_x = ln_list[cur_idx].first_x if new_x < minx: scan_list.append(cur_idx) sel_idx = cur_idx cur_idx += 1 minx = new_x if minx > max_ptx: break s, c, cnt = 0.0, 0, 0 for idx in scan_list: p = pos[idx] r = ln_list[idx].line y = r[p][1] per = min(minx - ln_list[idx].first_x, ln_list[idx].last_x - minx) / \ (ln_list[idx].last_x - ln_list[idx].first_x) w = math.pow(10, per + 0.1) - 1 if sel_idx == idx: ny = y s, c, cnt = s + ny * w, c + w, cnt + 1 elif r[p][0] - minx < AFFECT_DIST or minx - r[p - 1][0] < AFFECT_DIST: ny = calc_y(r[p - 1], r[p], minx) s, c, cnt = s + ny * w, c + w, cnt + 1 if cnt >= MIN_SEG: gene_list.append([minx, s / c]) pos[sel_idx] += 1 # check if any segment will be removed l = len(ln_list[sel_idx].line) if pos[sel_idx] == l: scan_list.remove(sel_idx) rm_cnt += 1 # print n_road, rm_cnt if len(gene_list) > 0: ref_list = mean_y_filter(gene_list) else: ref_list = None return gene_list, ref_list
def find_OF_crossing_pt(self, num_cycles=30, num_rnd_lines=20, delta=15, trace=False, path='output/', img=None): """ Ransac algorithm gets 2 frames and returns a point of infinity. :param img1: source first image, array of coordinates of points. :param img2: source second image, array of coordinates of points. :param num_cycles: number of cycles in ransac. :param num_rnd_lines: size of subset in ransac. :param delta: max distance for inliers in ransac. :param method: optical flow finding method. :param trace: boolean value trace, saving points in file. :param path: folder for tracing points. :return: point of infinity coordinates and algorithm status: np.array([[], []]), True\False """ cycle = 0 # iterator #max length of deque below ??????????????????????????????????????????????????? dist = deque() # vector characteristic for all points points_of_cross = deque() self.make_lines() # Generating img with all lines and current trace folder. if trace: out = img.copy() inliers = self.get_indexes_of_inliers() for id in inliers: point = self.get_point_by_id(id) k, b = point.get_line() x1, y1 = point.get_pt1() x2, y2 = point.get_pt2() out = draw.draw_line(out, k, b, color=draw.red) out = draw.draw_point(out, np.array([x1, y1]), color=draw.green) out = draw.draw_point(out, np.array([x2, y2]), color=draw.dark_green) cv2.imwrite(path + " all_lines.jpg", out) # Cycles of ransac while cycle < num_cycles: # Generating subset of lines subset = self.get_subset_of_rnd_lines(num_rnd_lines) # Draw current subset, if need if trace: out = img.copy() color = draw.blue for s in subset: k, b = self.get_point_by_id(s).get_line() out = draw.draw_line(out, k, b, color=color) # Trying to find current point of cross pt = self.point_of_crossing(subset) if not np.isnan(pt[0]): points_of_cross.append(pt) dist.append(self.get_sum_dist(pt, subset)) if trace: out = draw.draw_point(out, pt, color=draw.red, thickness=1, radius=10) cv2.imwrite(path + str(cycle) + ".jpg", out) # if there are not so much lines, is sufficient 1 subset(all lines) if self.get_number_of_inliers() <= num_rnd_lines: break cycle = cycle + 1 # if was a some error if len(dist) == 0: return [np.NaN, np.NaN], False # Main point of cross id_temp_point = list(dist).index(min(dist)) temp_point = points_of_cross[id_temp_point] # Marking outliers self.check_for_lines_in_interesting_area(temp_point, delta) inliers = self.get_indexes_of_inliers() pt = self.point_of_crossing(inliers) # if wasn't found point of infinity (some error in numpy.linalg.lstsq) if np.isnan(pt[0]): return pt, False # Drawing inliers and point of infinity if trace: out = img.copy() for id in inliers: k, b = self.get_point_by_id(id).get_line() out = draw.draw_line(out, k, b) out = draw.draw_point(out, pt, radius=10, thickness=1) cv2.imwrite(path + "result.jpg", out) out = img.copy() for i in self.get_indexes_of_inliers(): point = self.get_point_by_id(i) out = draw.draw_point(out, pt, color=draw.blue, thickness=1, radius=2) cv2.imwrite(path + 'unit_vector.jpg', out) return pt, True
def expose_button(self, widget, event): ''' Internal function to handle `expose-event` signal. @param widget: ColorButton instance. @param event: Expose event. ''' # Init. cr = widget.window.cairo_create() rect = widget.allocation x, y, w, h = rect.x, rect.y, rect.width, rect.height # Get color info. if widget.state == gtk.STATE_NORMAL: border_color = ui_theme.get_color("button_border_normal").get_color() background_color = ui_theme.get_shadow_color("button_background_normal").get_color_info() elif widget.state == gtk.STATE_PRELIGHT: border_color = ui_theme.get_color("button_border_prelight").get_color() background_color = ui_theme.get_shadow_color("button_background_prelight").get_color_info() elif widget.state == gtk.STATE_ACTIVE: border_color = ui_theme.get_color("button_border_active").get_color() background_color = ui_theme.get_shadow_color("button_background_active").get_color_info() elif widget.state == gtk.STATE_INSENSITIVE: border_color = ui_theme.get_color("disable_frame").get_color() disable_background_color = ui_theme.get_color("disable_background").get_color() background_color = [(0, (disable_background_color, 1.0)), (1, (disable_background_color, 1.0))] # Draw background. draw_vlinear( cr, x + 1, y + 1, w - 2, h - 2, background_color) # Draw border. cr.set_source_rgb(*color_hex_to_cairo(border_color)) draw_line(cr, x + 2, y + 1, x + w - 2, y + 1) # top draw_line(cr, x + 2, y + h, x + w - 2, y + h) # bottom draw_line(cr, x + 1, y + 2, x + 1, y + h - 2) # left draw_line(cr, x + w, y + 2, x + w, y + h - 2) # right # Draw four point. if widget.state == gtk.STATE_INSENSITIVE: top_left_point = ui_theme.get_pixbuf("button/disable_corner.png").get_pixbuf() else: top_left_point = ui_theme.get_pixbuf("button/corner.png").get_pixbuf() top_right_point = top_left_point.rotate_simple(270) bottom_right_point = top_left_point.rotate_simple(180) bottom_left_point = top_left_point.rotate_simple(90) draw_pixbuf(cr, top_left_point, x, y) draw_pixbuf(cr, top_right_point, x + w - top_left_point.get_width(), y) draw_pixbuf(cr, bottom_left_point, x, y + h - top_left_point.get_height()) draw_pixbuf(cr, bottom_right_point, x + w - top_left_point.get_width(), y + h - top_left_point.get_height()) # Draw color frame. cr.set_source_rgb(*color_hex_to_cairo("#c0c0c0")) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.stroke() # Draw color. cr.set_source_rgb(*color_hex_to_cairo(self.color)) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.fill() # Draw mask when widget is insensitive. if widget.state == gtk.STATE_INSENSITIVE: cr.set_source_rgba(*alpha_color_hex_to_cairo(ui_theme.get_alpha_color("color_button_disable_mask").get_color_info())) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.fill() return True
def draw(self, screen): draw_line(screen, self.p1, self.p2, self.color) draw_arrow(screen, (self.p1 + self.p2) * 0.5, (self.p1 + self.p2) * 0.5 + self.normal() * 10)
def generate_cave(self, entrances=[(4,4)],exits=[],overlaprooms=False): #We'll be generating the level in the following #way: # Place a small room around the entrance # Randomly place rooms # Mark chosen spot as a "landmark" # Connect landmarks via tunnels #Our map is currently all 0s #In the end, we will have a mix of numbers #0 - wall #1 - floor #2 - tunnel #3 - door self.entrances = entrances self.exits = exits #First, let's place our entrances+exits. _places = entrances[:] _places.extend(exits) for pos in _places: #We'll make a 3x3 area around it for x in xrange(-1,2): #One thing I suggest is making lines #as compact as possible. #For example, we'll be writing "entrance[0]+x" #and "entrance[1]+y" a lot in the next three lines #this can give us the impression that the line #is complicated when it's just simple addition... #Also doing more complex math OVER AND OVER #will slow things down a lot, so it's better #to just do it once and assign it to a variable #Addition is by no means complicated, but it #makes things more readable. #As a rule of thumb, I always put an underscore #before the variables I plan to throw away... _x = pos[0]+x for y in xrange(-1,2): #We need to check to see if we're drawing #inside the map first... #By the way, a '\' in Python #just lets us drop down a line in case #a line gets too lengthy... #Very handy! #Another temp variable... _y = pos[1]+y if 0<_x<self.size[0]\ and 0<_y<self.size[1]: self.map[_x][_y] = 1 if not (_x,_y) in self.walking_space: self.walking_space.append((_x,_y)) if (_x,_y) in self.walls: self.walls.remove((_x,_y)) #What we just did was "carve" out the room #Imagine these as rooms in a cave or something, #like the dungeons in Oblivion... #We also add the open space we create to a #"walking_space" list. #We'll use this later, but just know that #it marks places you could potentially walk #(it does more than just that, though!) #Now, here's where tunneling comes into play #First, we keep track of all the major "landmarks" #on our map. #These are things like doors, exits, and the center #of rooms. #We'll use these as guidelines for our tunnels... #Since we already have an entrance, add it to #the list... self.landmarks.append(pos) #We'll want to place our rooms next for i in xrange(self.max_rooms): #To prevent our rooms from being too far apart, #we want to randomly select a position and compare #it to our landmark list... _found = False _room_size = (random.randint(self.room_size[0],self.room_size[1]),\ random.randint(self.room_size[0],self.room_size[1])) #Here, we keep looking through the list of walls on the map #Technically, every wall on the map could potentially be the #cornerstone for a room, so we should check them all until we #find one. #NOTE: #As you can see, we're using a while loop and checking the #array "self.walls" #If a position is randomly chosen from this array and it turns #out to not be a good place to put the room, then we should #remove it from the array so it doesn't get checked again. #Here, I make a copy of the array... _walls = self.walls[:] #We'll be using this throughout the while loop, which #will hopefully speed things up... while not _found: _found = True #This array holds all the positions for every tile #in the room. _room = [] #Randomly select a position from our array of walls _pos = random.choice(_walls) #Remove the position from the array so it isn't checked #again. _walls.pop(_walls.index(_pos)) #Check to make sure the room will fit in this spot if _pos[0]-(_room_size[0]/2)<=0 or _pos[0]+(_room_size[0]/2)>=self.size[0]: _found=False;continue if _pos[1]-(_room_size[1]/2)<=0 or _pos[1]+(_room_size[1]/2)>=self.size[1]: _found=False;continue #Start checking to see if the room "fits" for x in xrange(-_room_size[0]/2,_room_size[0]/2): _x = _pos[0]+x for y in xrange(-_room_size[1]/2,_room_size[1]/2): _y = _pos[1]+y #ALRIGHT, IS YOUR BODY READY? #This is the last check we do to make sure the room #is okay. If we want to overlap rooms, then the next #line will always be true and the room can begin #being placed. #IF a floor tile is detected, then the loop breaks #and we restart the whole process. if not overlaprooms and not self.map[_x][_y] in [0,2]: _found = False break else: #We're okay. Add the floor tiles to the array #_room _room.append((_x,_y)) if not _found: break #We made it. #Make sure the room is of proper size and begin placing. if _found and len(_room)>=9: __room = {'name':'cave_room','walls':[],'open_walls':[],'walking_space':_room,\ 'door':None,'type':None} #Find some open walls #For every floor tile in the room... for pos in _room: #change the spot on the map to a floor tile #and add this position to the "walking_space" #array. self.map[pos[0]][pos[1]] = random.choice(var.STONE) self.walking_space.append(pos) #Remove the position from the REAL self.walls #array-- NOT the copy we made earlier if pos in self.walls: self.walls.remove(pos) #Add it to our rooms array self.rooms.append(__room) #Instead of finding the center, just find a random #spot in the array. This makes the tunnels look a #bit more natural. self.landmarks.append(random.choice(_room)) else: _found = False #Hang in there... #This is the last big part. #Now we're going to loop through all the landmarks we just #placed and connect them in the best way possible... #The following array tracks which landmarks have already been #connected. _done = [] for l1 in self.landmarks: #This is concept I use a lot in my code #It finds the nearest landmark to the one we're connecting. _lowest = {'where':None,'dist':9000} for l2 in self.landmarks: #We can't connect to ourselves! if l1 == l2 or l2 in _done: continue #Find the distance between the two landmarks. _dist = abs(l2[0]-l1[0])+abs(l2[1]-l1[1]) #If it's closer than the current one, then set _lowest #to represent that. if _dist<_lowest['dist']: _lowest['dist'] = _dist _lowest['where'] = l2 #If we couldn't connect it, then break (this is usually true #for the last room) if not _lowest['where']: break #If we allow diagonal tunnels, then randomly #choose between straight and diagonal here. if random.randint(0,1) and self.diagtunnels: _diag = True _line = draw.draw_diag_line(l1,_lowest['where']) else: _diag = False _line = draw.draw_line(l1,_lowest['where']) #Now, for every position in the line, "tunnel" the map for pos in _line: if not self.map[pos[0]][pos[1]]: #Diagonal tunnels require more space because the player #can't move like this... # #### # ##.. # #@## # #.## if _diag: for _pos in [(-1,-1),(0,-1),(1,-1),(-1,0),(0,0),(1,0),(-1,1),(0,1),(1,1)]: __pos = (pos[0]+_pos[0],pos[1]+_pos[1]) if __pos[0]<=0 or __pos[0]>=self.size[0]: continue if __pos[1]<=0 or __pos[1]>=self.size[1]: continue self.map[__pos[0]][__pos[1]] = random.choice(var.STONE) if not __pos in self.walking_space: self.walking_space.append(__pos) if __pos in self.walls: self.walls.remove(__pos) else: #Else, change the map to a tunnel tile! if pos[0]<0 or pos[0]>=self.size[0]: continue if pos[1]<0 or pos[1]>=self.size[1]: continue self.map[pos[0]][pos[1]] = random.choice(var.STONE) #Add it to the walking_space array if it isn't there already... if not pos in self.walking_space: self.walking_space.append(pos) #Remove the spot from the walls array also... if pos in self.walls: self.walls.remove(pos) #http://www.youtube.com/watch?feature=player_detailpage&v=7C7WCRoqFVs#t=103s _done.append(l1) #Place our exits for pos in entrances: self.map[pos[0]][pos[1]] = 3 for pos in exits: self.map[pos[0]][pos[1]] = 4
framethre = framethre & framethre_d framepro = frame.copy() frame_mask = frame.copy() frame_mask = frame & framethre white = (framethre != 0) white = sum(map(sum, white)) hist.append(white) cv2.imshow("input", frame) cv2.imshow("output", frame_mask) cv2.imshow("outputbin", framethre) if cv2.waitKey(1) & 0xFF == ord(' '): #cv2.imwrite("exm_input" + str(save_num) + ".jpg", frame) #cv2.imwrite("exm_output" + str(save_num) + ".jpg", framenew) #cv2.imwrite("exm_outputbin" + str(save_num) + ".jpg", framethre) #save_num = save_num + 1 break cap.release() cv2.destroyAllWindows() ret = draw_line(hist) file = open('data_escalator.txt', 'w') file.write(str(hist)) file.close()
def expose_button(self, widget, event): ''' Internal function to handle `expose-event` signal. @param widget: ColorButton instance. @param event: Expose event. ''' # Init. cr = widget.window.cairo_create() rect = widget.allocation x, y, w, h = rect.x, rect.y, rect.width, rect.height # Get color info. if widget.state == gtk.STATE_NORMAL: border_color = ui_theme.get_color( "button_border_normal").get_color() background_color = ui_theme.get_shadow_color( "button_background_normal").get_color_info() elif widget.state == gtk.STATE_PRELIGHT: border_color = ui_theme.get_color( "button_border_prelight").get_color() background_color = ui_theme.get_shadow_color( "button_background_prelight").get_color_info() elif widget.state == gtk.STATE_ACTIVE: border_color = ui_theme.get_color( "button_border_active").get_color() background_color = ui_theme.get_shadow_color( "button_background_active").get_color_info() elif widget.state == gtk.STATE_INSENSITIVE: border_color = ui_theme.get_color("disable_frame").get_color() disable_background_color = ui_theme.get_color( "disable_background").get_color() background_color = [(0, (disable_background_color, 1.0)), (1, (disable_background_color, 1.0))] # Draw background. draw_vlinear(cr, x + 1, y + 1, w - 2, h - 2, background_color) # Draw border. cr.set_source_rgb(*color_hex_to_cairo(border_color)) draw_line(cr, x + 2, y + 1, x + w - 2, y + 1) # top draw_line(cr, x + 2, y + h, x + w - 2, y + h) # bottom draw_line(cr, x + 1, y + 2, x + 1, y + h - 2) # left draw_line(cr, x + w, y + 2, x + w, y + h - 2) # right # Draw four point. if widget.state == gtk.STATE_INSENSITIVE: top_left_point = ui_theme.get_pixbuf( "button/disable_corner.png").get_pixbuf() else: top_left_point = ui_theme.get_pixbuf( "button/corner.png").get_pixbuf() top_right_point = top_left_point.rotate_simple(270) bottom_right_point = top_left_point.rotate_simple(180) bottom_left_point = top_left_point.rotate_simple(90) draw_pixbuf(cr, top_left_point, x, y) draw_pixbuf(cr, top_right_point, x + w - top_left_point.get_width(), y) draw_pixbuf(cr, bottom_left_point, x, y + h - top_left_point.get_height()) draw_pixbuf(cr, bottom_right_point, x + w - top_left_point.get_width(), y + h - top_left_point.get_height()) # Draw color frame. cr.set_source_rgb(*color_hex_to_cairo("#c0c0c0")) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.stroke() # Draw color. cr.set_source_rgb(*color_hex_to_cairo(self.color)) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.fill() # Draw mask when widget is insensitive. if widget.state == gtk.STATE_INSENSITIVE: cr.set_source_rgba(*alpha_color_hex_to_cairo( ui_theme.get_alpha_color( "color_button_disable_mask").get_color_info())) cr.rectangle(x + (w - self.color_area_width) / 2, y + (h - self.color_area_height) / 2, self.color_area_width, self.color_area_height) cr.fill() return True
def draw(self, ax): min_corner = torch.min(self.min_corner, self.max_corner) max_corner = torch.max(self.min_corner, self.max_corner) # Square 1 p1 = min_corner p2 = np.array([max_corner[0], min_corner[1], min_corner[2]]) p3 = np.array([max_corner[0], max_corner[1], min_corner[2]]) p4 = np.array([min_corner[0], max_corner[1], min_corner[2]]) # Square 2 p5 = np.array([min_corner[0], min_corner[1], max_corner[2]]) p6 = np.array([max_corner[0], min_corner[1], max_corner[2]]) p7 = max_corner p8 = np.array([min_corner[0], max_corner[1], max_corner[2]]) # Draw square 1 draw.draw_line(ax, p1, p2) draw.draw_line(ax, p2, p3) draw.draw_line(ax, p3, p4) draw.draw_line(ax, p4, p1) # Draw square 2 draw.draw_line(ax, p5, p6) draw.draw_line(ax, p6, p7) draw.draw_line(ax, p7, p8) draw.draw_line(ax, p8, p5) # Draw lines connecting the squares draw.draw_line(ax, p1, p5) draw.draw_line(ax, p2, p6) draw.draw_line(ax, p3, p7) draw.draw_line(ax, p4, p8)
def draw(self, ax): min_corner = self.min_corner() max_corner = self.max_corner() device = torchext.get_device(min_corner) # Square 1 p1 = min_corner p2 = torch.tensor([max_corner[0], min_corner[1], min_corner[2]], device=device) p3 = torch.tensor([max_corner[0], max_corner[1], min_corner[2]], device=device) p4 = torch.tensor([min_corner[0], max_corner[1], min_corner[2]], device=device) # Square 2 p5 = torch.tensor([min_corner[0], min_corner[1], max_corner[2]], device=device) p6 = torch.tensor([max_corner[0], min_corner[1], max_corner[2]], device=device) p7 = max_corner p8 = torch.tensor([min_corner[0], max_corner[1], max_corner[2]], device=device) points = translate( self.position, rotate(self.rotation, torch.stack([p1, p2, p3, p4, p5, p6, p7, p8]))).detach().cpu().numpy() p1 = points[0] p2 = points[1] p3 = points[2] p4 = points[3] p5 = points[4] p6 = points[5] p7 = points[6] p8 = points[7] # Draw square 1 draw.draw_line(ax, p1, p2) draw.draw_line(ax, p2, p3) draw.draw_line(ax, p3, p4) draw.draw_line(ax, p4, p1) # Draw square 2 draw.draw_line(ax, p5, p6) draw.draw_line(ax, p6, p7) draw.draw_line(ax, p7, p8) draw.draw_line(ax, p8, p5) # Draw lines connecting the squares draw.draw_line(ax, p1, p5) draw.draw_line(ax, p2, p6) draw.draw_line(ax, p3, p7) draw.draw_line(ax, p4, p8)
def fire(GS, p): if len(p.missles) <= 0: GS['messages'].append('red: You have no missles to shoot with!') else: rng = 4 if p.ranged_weapon: rng = p.ranged_weapon.range ms = list(filter(lambda m: utils.dist(m.pos, p.pos) <= rng and\ GS['terrain_map'].dungeon['lighted'].fov[m.pos], GS['terrain_map'].dungeon['monsters'])) ox = max(0, GS['player'].pos[0] - math.floor(WIDTH / 4)) oy = max(0, GS['player'].pos[1] - math.floor(HEIGHT / 2)) for i, m in enumerate(ms): start = (p.pos[0] - ox, p.pos[1] - oy) end = (m.pos[0] - ox, m.pos[1] - oy) draw.draw_line(GS, start, end, colors.light_blue, start_char='@', end_char=str(i)) if len(ms) > 0: key = tdl.event.wait(timeout=None, flush=True) while not ('KEY' in key.type and (key.keychar.isnumeric() or key.keychar == 'ESCAPE')): GS['messages'].append('Please type number or ESC.') draw.draw_hud_screen(GS) key = tdl.event.wait(timeout=None, flush=True) if key.keychar != 'ESCAPE': GS['messages'].append('yellow: You shoot the ' + utils.ordinal(key.keychar) + ' target!') target = ms[int(key.keychar) % len(ms)] skill = p.race.skills['range'] handicap = max(0, math.ceil(1 - skill)) + 5 tpe = '' if p.ranged_weapon: tpe = p.ranged_weapon.missle_type missle = list( filter( lambda m: not p.ranged_weapon or tpe in m.missle_type, p.missles))[-1] # Animation start = (p.pos[0] - ox, p.pos[1] - oy) end = (target.pos[0] - ox, target.pos[1] - oy) animation.FireMissleAnimation().run(GS, [missle, start, end]) cw = math.floor(p.ranged_weapon.weight / 5) * 4 if target and random.randint( 0, max(1, int(100 - p.exp * skill - handicap))) < cw + target.speed * 20 + 5: if tpe == '': target.health -= (missle.hit - 2) else: target.health -= missle.hit GS['messages'].append('yellow: You hit the ' + target.name + '.') if target.health <= 0: GS['messages'].append( 'green: Your shot hit home! The ' + target.name + ' dies.') GS['terrain_map'].dungeon['monsters'].remove(target) p.killed_monsters += 1 p.learn(GS, target) p.missles.remove(missle) missle.equipped = False GS['terrain_map'].dungeon['items'][target.pos].append( missle) else: GS['messages'].append('red: You miss the enemy.') else: GS['messages'].append('grey: Nevermind.') else: GS['messages'].append('red: There are no enemies in range.')
def __init__(self,open_side,size=(12,12)): self.size = size self.needs = ['bedroom','kitchen','bedroom'] self.rooms = [] #This will track the properties of each room self.walking_space = [] #What we're doing here is passing a blueprint along to levelgen, #which will place all the tiles for us. #We can do anything we want with the tiles, just as long as obey #the guidelines put in place by 'open_side' and 'needs' #Old housegen worked by collecting a list of needs for each #house and placing the objects randomly inside. #This works by tracking what kind of rooms each building needs. #Creating a '2d' array in Python is pretty slow... #This is a lot faster if we use Numpy self.house = numpy.zeros(self.size,dtype=numpy.int16) #int16 because we don't need floats #Just a reminder: Numpy arrays are [ROW,COLUMN] #Start things off by looping through our needs for need in self.needs: if need=='bedroom': _room_size = (5,5) elif need=='kitchen': _room_size = (5,6) #If this is the first room we place we should ensure it's near the "open" #side of the building. if not self.rooms: _pos = self.find_open_near(_room_size,open_side) else: #_pos = random.choice(self.find_open(_room_size)) _pos = self.find_open_near(_room_size,random.choice(self.rooms)['pos']) _walking = [] for x in range(_room_size[0]): if not x or x>=_room_size[0]-1: continue for y in range(_room_size[1]): if not y or y>=_room_size[1]-1: continue self.house[_pos[0]+x,_pos[1]+y] = 1 _walking.append((_pos[0]+x,_pos[1]+y)) self.walking_space.append((_pos[0]+x,_pos[1]+y)) if self.rooms: _room = self.rooms[len(self.rooms)-1] _from = random.choice(_walking) _to = random.choice(_room['walking_space']) for pos in draw.draw_line(_from,_to): self.house[pos[0],pos[1]]=1 _walking.append(pos) self.walking_space.append(pos) else: #Connect the door to our first room _to = random.choice(_walking) for pos in draw.draw_line(open_side,_to): self.house[pos[0],pos[1]]=1 self.rooms.append({'pos':_pos,'walking_space':_walking,'type':need})
def on_tick(self, sim): if self.linestyle == '-': self.handles.append(draw_line( self.last_pos, self.body.p, color=self.color, linewidth=self.linewidth)) self.last_pos = self.body.p
def draw_rectangle(cr, x, y , w, h): draw_line(cr, x -1 , y , x + w, y) # top draw_line(cr, x , y + h, x + w, y + h) # bottom draw_line(cr, x , y , x , y + h) # left draw_line(cr, x + w , y , x + w , y + h -1) # right
def draw(self): draw.draw_line((self.x1, self.y1), (self.x2, self.y2), 255*(self.lifetime-self.age)/self.lifetime, 0, 0, 2)