def triangle(p1, p2, p3, color='r'): t = patches.Polygon(xy=[p1, p2, p3], fc=color) ax.add_patch(t)
def draw_layout(path_to_image, annotation, height, hide=False, **kwargs): """ Visualizes the AI2D layout annotation on the original input image. Parameters: path_to_image: Path to the original AI2D diagram image. annotation: A dictionary containing AI2D annotation. height: Target height of the image. hide: A Boolean indicating whether to draw annotation or not. Optional parameters: dpi: An integer indicating the resolution to use. point: A list of layout elements to draw. Returns: An image with the AI2D annotation overlaid. """ # Load the diagram image and make a copy img, r = resize_img(path_to_image, height) # Change from BGR to RGB colourspace img = img[:, :, ::-1] # Create a matplotlib Figure fig, ax = plt.subplots(1) plt.tight_layout(pad=0) # Add the image to the axis ax.imshow(img) # Hide grid and axes plt.axis('off') # Check if the annotation should be hidden if hide: # Save figure to file, read the file using OpenCV and remove the file plt.savefig('temp.png') img = cv2.imread('temp.png') os.remove('temp.png') return img # Draw blobs try: for b in annotation['blobs']: # Define default colour for blobs blob_color = 'orangered' # Check if some annotation should be highlighted if kwargs and 'point' in kwargs: # Continue if the blob is not in the list of elements to draw if b not in kwargs['point']: continue # Check if some annotation should be highlighted in different colors if kwargs and 'highlight' in kwargs: # Check that kwargs['highlight'] is a dictionary assert type(kwargs['highlight']) == dict # Assign highlights to a dictionary highlights = kwargs['highlight'] # Loop over colours and elements for color, elements in highlights.items(): # If match is found, set colour and highlight to True if b in elements: blob_color = color highlight = True break else: highlight = False # If no element is to be highlighted, continue to next item if not highlight: continue # Get blob ID blob_id = annotation['blobs'][b]['id'] # Assign the blob points into a variable and convert into numpy # array points = np.array(annotation['blobs'][b]['polygon'], np.int32) # Scale the coordinates according to the ratio; convert to int points = np.round(points * r, decimals=0).astype('int') # Creat arrow polygon blob = patches.Polygon(points, closed=True, fill=False, alpha=1, color=blob_color) # Add arrow to the image ax.add_patch(blob) # Add artist for patch ax.add_artist(blob) # Get centroid cx, cy = np.round(points.mean(axis=0), decimals=0).astype('int')[:2] # If highlights have been requested, skip annotations and continue if 'highlight' in kwargs: continue # Annotate the blob ann = ax.annotate(blob_id, (cx, cy), color='white', fontsize=10, ha='center', va='center') # Add a box around the annotation ann.set_bbox(dict(alpha=1, color=blob_color, pad=0)) # Skip if there are no blobs to draw except KeyError: pass # Draw arrows try: for a in annotation['arrows']: # Define default colour for arrows arrow_color = 'mediumseagreen' # Check if some annotation should be highlighted if kwargs and 'point' in kwargs: # Continue if the blob is not in the list of elements to draw if a not in kwargs['point']: continue # Check if some annotation should be highlighted in different colors if kwargs and 'highlight' in kwargs: # Check that kwargs['highlight'] is a dictionary assert type(kwargs['highlight']) == dict # Assign highlights to a dictionary highlights = kwargs['highlight'] # Loop over colours and elements for color, elements in highlights.items(): # If match is found, set colour and highlight to True if a in elements: arrow_color = color highlight = True break else: highlight = False # If no element is to be highlighted, continue to next item if not highlight: continue # Get arrow ID arrow_id = annotation['arrows'][a]['id'] # Assign the points into a variable points = np.array(annotation['arrows'][a]['polygon'], np.int32) # Scale the coordinates according to the ratio; convert to int points = np.round(points * r, decimals=0).astype('int') # Create an arrow polygon arrow = patches.Polygon(points, closed=True, fill=False, alpha=1, color=arrow_color) # Add arrow to the image ax.add_patch(arrow) # Add artist for patch ax.add_artist(arrow) # Get centroid cx, cy = np.round(points.mean(axis=0), decimals=0).astype('int')[:2] # If highlights have been requested, skip annotations and continue if 'highlight' in kwargs: continue # Annotate the arrow ann = ax.annotate(arrow_id, (cx, cy), color='white', fontsize=10, ha='center', va='center') # Add a box around the annotation ann.set_bbox(dict(alpha=1, color=arrow_color, pad=0)) # Skip if there are no arrows to draw except KeyError: pass # Draw text blocks try: for t in annotation['text']: # Define default colour for text blocks text_color = 'dodgerblue' # Check if some annotation should be highlighted if kwargs and 'point' in kwargs: # Continue if the blob is not in the list of elements to draw if t not in kwargs['point']: continue # Check if some annotation should be highlighted in different colors if kwargs and 'highlight' in kwargs: # Check that kwargs['highlight'] is a dictionary assert type(kwargs['highlight']) == dict # Assign highlights to a dictionary highlights = kwargs['highlight'] # Loop over colours and elements for color, elements in highlights.items(): # If match is found, set colour and highlight to True if t in elements: text_color = color highlight = True break else: highlight = False # If no element is to be highlighted, continue to next item if not highlight: continue # Get text ID text_id = annotation['text'][t]['id'] # Get the start and end points of the rectangle and cast # them into tuples for drawing. rect = np.array(annotation['text'][t]['rectangle'], np.int32) # Get start and end coordinates, convert to int and cast into tuple startx, starty = np.round(rect[0] * r, decimals=0).astype('int') endx, endy = np.round(rect[1] * r, decimals=0).astype('int') # Calculate bounding box width and height width = endx - startx height = endy - starty # Define a rectangle and add to batch rectangle = patches.Rectangle((startx, starty), width, height, fill=False, alpha=1, color=text_color, edgecolor=None) # Add patch to the image ax.add_patch(rectangle) # Add artist object for rectangle ax.add_artist(rectangle) # Get starting coordinates x, y = rectangle.get_xy() # Get coordinates for the centre; adjust positioning cx = (x + rectangle.get_width() / 2.0) cy = (y + rectangle.get_height() / 2.0) # If highlights have been requested, skip annotations and continue if 'highlight' in kwargs: continue # Add annotation to the text box ann = ax.annotate(text_id, (cx, cy), color='white', fontsize=10, ha='center', va='center') # Add a box around the annotation ann.set_bbox(dict(alpha=1, color=text_color, pad=0)) # Skip if there are no text boxes to draw except KeyError: pass # If requested, draw arrowheads if kwargs and 'arrowheads' in kwargs: # Define colour for arrowheads arrowhead_color = 'darkorange' try: for ah in annotation['arrowHeads']: # Get arrowhead ID arrowhead_id = annotation['arrowHeads'][ah]['id'] # Get the start and end points of the rectangle and cast them # into tuples for drawing. rect = np.array(annotation['arrowHeads'][ah]['rectangle'], np.int32) # Get start and end coordinates, convert to int and cast into # tuple startx, starty = np.round(rect[0] * r, decimals=0).astype('int') endx, endy = np.round(rect[1] * r, decimals=0).astype('int') # Calculate bounding box width and height width = endx - startx height = endy - starty # Define a rectangle and add to batch rectangle = patches.Rectangle((startx, starty), width, height, fill=False, alpha=1, color=arrowhead_color, edgecolor=None) # Add patch to the image ax.add_patch(rectangle) # Add artist object for rectangle ax.add_artist(rectangle) # Get starting coordinates x, y = rectangle.get_xy() # Get coordinates for the centre; adjust positioning cx = (x + rectangle.get_width() / 2.0) cy = (y + rectangle.get_height() / 2.0) # If highlights have been requested, skip annotations and # continue if 'highlight' in kwargs: continue # Add annotation to the text box ann = ax.annotate(arrowhead_id, (cx, cy), color='white', fontsize=10, ha='center', va='center') # Add a box around the annotation ann.set_bbox(dict(alpha=1, color=arrowhead_color, pad=0)) # Skip if there are no arrowheads to draw except KeyError: pass # Check if a high-resolution image has been requested if kwargs and 'dpi' in kwargs: # Save figure to file in the requested resolution plt.savefig('temp.png', dpi=kwargs['dpi']) img = cv2.imread('temp.png') os.remove('temp.png') return img # Save figure to file, read the file using OpenCV and remove the file plt.savefig('temp.png') img = cv2.imread('temp.png') os.remove('temp.png') # Close the plot plt.close() # Return the annotated image return img
def draw_multi_bbox(img, bb8_pred, bb8_gt, save_path): img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) _, ax = plt.subplots(1) # print(bb8_pred.shape) ax.imshow(img) num = bb8_pred.shape[0] for i in range(num): ax.add_patch( patches.Polygon(xy=bb8_pred[i, 0][[0, 1, 7, 2, 0, 3, 6, 1]], fill=False, linewidth=1, edgecolor='b')) ax.add_patch( patches.Polygon(xy=bb8_pred[i, 0][[5, 4, 6, 3, 5, 2, 7, 4]], fill=False, linewidth=1, edgecolor='b')) # if corners_targets is not None: ax.add_patch( patches.Polygon(xy=bb8_gt[i, 0][[0, 1, 7, 2, 0, 3, 6, 1]], fill=False, linewidth=1, edgecolor='r')) ax.add_patch( patches.Polygon(xy=bb8_gt[i, 0][[5, 4, 6, 3, 5, 2, 7, 4]], fill=False, linewidth=1, edgecolor='r')) # ax.plot(x=bb8_pred[0,0,:,0],y=bb8[0,0,:,1]) plt.savefig(save_path) plt.close() # root_path='./../datasets/ycb_video/data/models' # objs=os.listdir(root_path) # for obj in objs: # print(obj) # path=os.path.join(root_path,obj,'textured.obj') # box=get_obb(path) # img=cv2.imread('./../datasets/ycb_video/data/train_data/0000049-color.png') # draw_bbox(img,box[None,None,...],box) # # save_path=os.path.join(root_path,obj,'diameter.txt') # # with open(save_path,'w') as fp: # # fp.write(str(diameter)) # # fp.close # print(box) # break # root_dir='./../datasets/ycb_video/data' # obj_name='025_mug' # img_name='0000001-color.png' # img=cv2.imread(os.path.join(root_dir,'test_data',img_name)) # pose_gt, model,_,K,_=get_info(root_dir,obj_name,14,img_name) # box=get_obb(model) # box_2d=project_K(box,pose_gt,K) # draw_bbox(img,box_2d[None,None,...],box_2d[None,None,...]) # def vis(root_dir,obj_id,img_name): # obj = {1: "002_master_chef_can", # 2: "003_cracker_box", # 3: "004_sugar_box", # 4: "005_tomato_soup_can", # 5: "006_mustard_bottle", # 6: "007_tuna_fish_can", # 7: "008_pudding_box", # 8:"009_gelatin_box", # 9:"010_potted_meat_can", # 10:"011_banana", # 11:"019_pitcher_base", # 12:"021_bleach_cleanser", # 13:"024_bowl", # 14:"025_mug", # 15:"035_power_drill", # 16:"036_wood_block", # 17:"037_scissors", # 18:"040_large_marker", # 19:"051_large_clamp", # 20:"052_extra_large_clamp", # 21:"061_foam_brick"}
def __plot(self): """ Start the simulation - plot/visualize robot motion """ # Main plot function calls self.__line, = plt.plot(self.__x_gt[0, 0], self.__x_gt[1, 0], 'o') plt.axis('equal') axes = plt.axes(xlim=(-0.5, 2), ylim=(0, 2.5)) axes.set_aspect('equal') # Viewing angle visualization distance = 100 cosx = np.cos(self.__view_half_angle) sinx = np.sin(self.__view_half_angle) self.__view_lines_1, = plt.plot( [self.__x_gt[0, 0], self.__x_gt[0, 0] + distance * cosx], [self.__x_gt[1, 0], self.__x_gt[1, 0] + distance * sinx], 'r-') self.__view_lines_2, = plt.plot( [self.__x_gt[0, 0], self.__x_gt[0, 0] + distance * cosx], [self.__x_gt[1, 0], self.__x_gt[1, 0] - distance * sinx], 'r-') # plt.hold(True) # Drawing of robot (building drawing objects for it) self.__bot_parts = [0 for i in range(len(self.__shapes))] for s in range(len(self.__shapes)): self.__bot_parts[s] = patches.Polygon(self.__shapes[s], fill=True, facecolor='b', edgecolor='k') axes.add_patch(self.__bot_parts[s]) self.__bot_parts_est = [0 for i in range(len(self.__shapes))] for s in range(len(self.__shapes)): self.__bot_parts_est[s] = patches.Polygon(self.__shapes[s], fill=False, facecolor='w', edgecolor='k') axes.add_patch(self.__bot_parts_est[s]) # Drawing of the map (building drawing objects) # Obstacles self.__obstacles = [0 for i in range(np.sum(self.__occupancy_map))] obs_iter = 0 for r in range(self.__occupancy_map.shape[0]): for c in range(self.__occupancy_map.shape[1]): if self.__occupancy_map[r, c]: self.__obstacles[obs_iter] = patches.Rectangle( (c * self.__x_spacing, r * self.__y_spacing), self.__x_spacing, self.__y_spacing, fill=True, facecolor='r', edgecolor='k') axes.add_patch(self.__obstacles[obs_iter]) obs_iter += 1 # Markers self.__markers = [0 for i in range(len(self.markers_flipped))] self.__markers_dir = [0 for i in range(len(self.markers_flipped))] for m in range(len(self.markers_flipped)): angle = (self.markers_flipped[m][2] / np.pi) * 180.0 R = np.array([[ np.cos(self.markers_flipped[m][2]), -np.sin(self.markers_flipped[m][2]) ], [ np.sin(self.markers_flipped[m][2]), np.cos(self.markers_flipped[m][2]) ]]) offset = np.array([[self.__marker_width, self.__marker_height]]).T rotated_offset = np.dot(R, offset) self.__markers[m] = patches.Rectangle( (self.markers_flipped[m][0] - rotated_offset[0] / 2., self.markers_flipped[m][1] - rotated_offset[1] / 2.), self.__marker_width, self.__marker_height, angle=(self.markers_flipped[m][2] / np.pi) * 180.0, fill=True, facecolor='r', edgecolor='k') dir_offset = np.array([[-self.__marker_width, 0.04]]).T rotated_dir_offset = np.dot(R, dir_offset) self.__markers_dir[m] = patches.Rectangle( (self.markers_flipped[m][0] - rotated_dir_offset[0] / 2., self.markers_flipped[m][1] - rotated_dir_offset[1] / 2.), self.__marker_width * 0.5, 0.04, angle=(self.markers_flipped[m][2] / np.pi) * 180.0, fill=True, facecolor='r', edgecolor='k') axes.add_patch(self.__markers[m]) axes.add_patch(self.__markers_dir[m]) # Trail points of path self.__history_x = np.zeros((1, self.__lag_len)) self.__history_y = np.zeros((1, self.__lag_len)) self.__trails = [ plt.plot(hx, hy, 'k')[0] for hx, hy in zip(self.__history_x, self.__history_y) ]
import matplotlib.pyplot as plt import matplotlib.patches as mp import math import random import sympy # Define "template" O = [0,0] A = [random.randrange(-5,0,1), random.randrange(0,5,1)] B = [random.randrange(0,5,1), random.randrange(0,5,1)] C = [random.randrange(0,5,1), random.randrange(-5,0,1)] D = [random.randrange(-5,0,1), random.randrange(-5,0,1)] points = [A,B,C,D] #print(points) polygon = mp.Polygon((points), closed = True,fill=None,edgecolor="r", alpha=0.9) # Random transformation # 1. Rotation theta = random.randrange(-360,360) print('randomly generated theta is: ', theta) #theta is clockwise rotation theta = math.radians(theta) rotA = [A[0]*math.cos(theta)+A[1]*math.sin(theta), -A[0]*math.sin(theta)+A[1]*math.cos(theta)] rotB = [B[0]*math.cos(theta)+B[1]*math.sin(theta), -B[0]*math.sin(theta)+B[1]*math.cos(theta)] rotC = [C[0]*math.cos(theta)+C[1]*math.sin(theta), -C[0]*math.sin(theta)+C[1]*math.cos(theta)] rotD = [D[0]*math.cos(theta)+D[1]*math.sin(theta), -D[0]*math.sin(theta)+D[1]*math.cos(theta)] rotpoints = [rotA,rotB,rotC,rotD] rotpolygon = mp.Polygon((rotpoints),closed=True,fill=None,edgecolor="b",alpha = 0.4) #print(rotpoints) # 2. Translation
val1 = 7 * np.tanh((lon1 + 124.1) / .1) val1[val1 > 3] = np.NaN ax[2].plot(lon1, val1, linewidth=1.5, color='r') val1 = 5 - 7 * np.tanh((lon1 + 124.3) / .05) val1[val1 < 3] = np.NaN ax[2].plot(lon1, val1, linewidth=1.5, color='b') val1 = 15 - 18 * np.tanh((lon1 + 124.2) / .1) val1[val1 < 3] = np.NaN ax[2].plot(lon1, val1, linewidth=1.5, color='b') ax[2].text(-124.78, 90.3, 'c)') #%% for ax1 in ax: #Coast h = grd['h'][:, 223] h[np.isnan(h)] = 3. h = np.concatenate(([10e3], h, [10e3])) hlon = np.concatenate(([-135.], grd['lon'][:, 0], [-120.])) p = patch.Polygon(np.column_stack((hlon, h)), facecolor=(.5, .6, .5), edgecolor=None, closed=True) p.set_zorder(20) ax1.add_patch(p) #%% Save fig.subplots_adjust(bottom=.02, top=.98) fig.savefig('hypo.pdf')
def movie_cherns_varyloc(ccoll, title='Chern number calculation for varied positions', filename='chern_varyloc', rootdir=None, exten='.png', max_boxfrac=None, max_boxsize=None, xlabel=None, ylabel=None, step=0.5, fracsteps=False, framerate=3): """Plot the chern as a function of space for each haldane_lattice examined Parameters ---------- ccoll : ChernCollection instance The collection of varyloc chern calcs to make into a movie title : str title of the movie filename : str the name of the files to save rootdir : str or None The cproot directory to use (usually self.cp['rootdir']) exten : str (.png, .jpg, etc) file type extension max_boxfrac : float Fraction of spatial extent of the sample to use as maximum bound for kitaev sum max_boxsize : float or None If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize xlabel : str label for x axis ylabel : str label for y axis step : float (default=1.0) how far apart to sample kregion vertices in varyloc fracsteps : bool framerate : int The framerate at which to save the movie max_boxfrac : float Fraction of spatial extent of the sample to use as maximum bound for kitaev sum max_boxsize : float or None If None, uses max_boxfrac * spatial extent of the sample asmax_boxsize """ rad = 1.0 divgmap = cmaps.diverging_cmap(250, 10, l=30) # plot it for hlat_name in ccoll.cherns: hlat = ccoll.cherns[hlat_name][0].haldane_lattice if hlat.lp['shape'] == 'square': # get extent of the network from Bounding box Radius = np.abs(hlat.lp['BBox'][0, 0]) else: # todo: allow different geometries pass # Initialize the figure h_mm = 90 w_mm = 120 # To get space between subplots, figure out how far away ksize region needs to be, based on first chern # Compare max ksize to be used with spatial extent of the lattice. If comparable, make hspace large. # Otherwise, use defaults ksize = ccoll.cherns[hlat_name][0].chern_finsize[:, 2] cgll = ccoll.cherns[hlat_name][0].haldane_lattice.lattice maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]), np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1])) if max_boxsize is not None: ksize = ksize[ksize < max_boxsize] else: if max_boxfrac is not None: max_boxsize = max_boxfrac * maxsz ksize = ksize[ksize < max_boxsize] else: ksize = ksize max_boxsize = np.max(ksize) if max_boxsize > 0.9 * maxsz: center0_frac = 0.3 center2_frac = 0.75 elif max_boxsize > 0.65 * maxsz: center0_frac = 0.35 center2_frac = 0.72 elif max_boxsize > 0.55 * maxsz: center0_frac = 0.375 center2_frac = 0.71 else: center0_frac = 0.4 center2_frac = 0.7 fig, ax = initialize_1p5panelcbar_fig(Wfig=w_mm, Hfig=h_mm, wsfrac=0.4, wssfrac=0.4, center0_frac=center0_frac, center2_frac=center2_frac) # dimensions of video in pixels final_h = 720 final_w = 960 actual_dpi = final_h / (float(h_mm) / 25.4) # Add the network to the figure hlat = ccoll.cherns[hlat_name][0].haldane_lattice netvis.movie_plot_2D(hlat.lattice.xy, hlat.lattice.BL, 0 * hlat.lattice.BL[:, 0], None, None, ax=ax[0], fig=fig, axcb=None, xlimv='auto', ylimv='auto', climv=0.1, colorz=False, ptcolor=None, figsize='auto', colormap='BlueBlackRed', bgcolor='#ffffff', axis_off=True, axis_equal=True, lw=0.2) # Add title if title is not None: ax[0].annotate(title, xy=(0.5, .95), xycoords='figure fraction', horizontalalignment='center', verticalalignment='center') if xlabel is not None: ax[0].set_xlabel(xlabel) if ylabel is not None: ax[0].set_xlabel(ylabel) # Position colorbar sm = plt.cm.ScalarMappable(cmap=divgmap, norm=plt.Normalize(vmin=-1, vmax=1)) # fake up the array of the scalar mappable. sm._A = [] cbar = plt.colorbar(sm, cax=ax[1], orientation='horizontal', ticks=[-1, 0, 1]) ax[1].set_xlabel(r'$\nu$') ax[1].xaxis.set_label_position("top") ax[2].axis('off') # Add patches (rectangles from cherns at each site) to the figure print 'Opening hlat_name = ', hlat_name done = False ind = 0 while done is False: rectps = [] colorL = [] for chernii in ccoll.cherns[hlat_name]: # Grab small, medium, and large circles ksize = chernii.chern_finsize[:, 2] if max_boxsize is not None: ksize = ksize[ksize < max_boxsize] else: if max_boxfrac is not None: cgll = chernii.haldane_lattice.lattice maxsz = max(np.max(cgll.xy[:, 0]) - np.min(cgll.xy[:, 0]), np.max(cgll.xy[:, 1]) - np.min(cgll.xy[:, 1])) max_boxsize = max_boxfrac * maxsz ksize = ksize[ksize < max_boxsize] else: ksize = ksize max_boxsize = np.max(ksize) # print 'ksize = ', ksize # print 'max_boxsize = ', max_boxsize xx = float(chernii.cp['poly_offset'].split('/')[0]) yy = float(chernii.cp['poly_offset'].split('/')[1]) nu = chernii.chern_finsize[:, -1] rad = step rect = plt.Rectangle((xx-rad*0.5, yy-rad*0.5), rad, rad, ec="none") colorL.append(nu[ind]) rectps.append(rect) p = PatchCollection(rectps, cmap=divgmap, alpha=1.0, edgecolors='none') p.set_array(np.array(np.array(colorL))) p.set_clim([-1., 1.]) # Add the patches of nu calculations for each site probed ax[0].add_collection(p) # Draw the kitaev cartoon in second axis with size ksize[ind] polygon1, polygon2, polygon3 = kfns.get_kitaev_polygons(ccoll.cp['shape'], ccoll.cp['regalph'], ccoll.cp['regbeta'], ccoll.cp['reggamma'], ksize[ind]) patchlist = [] patchlist.append(patches.Polygon(polygon1, color='r')) patchlist.append(patches.Polygon(polygon2, color='g')) patchlist.append(patches.Polygon(polygon3, color='b')) polypatches = PatchCollection(patchlist, cmap=cm.jet, alpha=0.4, zorder=99, linewidths=0.4) colors = np.linspace(0, 1, 3)[::-1] polypatches.set_array(np.array(colors)) ax[2].add_collection(polypatches) ax[2].set_xlim(ax[0].get_xlim()) ax[2].set_ylim(ax[0].get_ylim()) # Save the plot # make index string indstr = '_{0:06d}'.format(ind) hlat_cmesh = kfns.get_cmeshfn(ccoll.cherns[hlat_name][0].haldane_lattice.lp, rootdir=rootdir) specstr = '_Nks' + '{0:03d}'.format(len(ksize)) + '_step' + sf.float2pstr(step) \ + '_maxbsz' + sf.float2pstr(max_boxsize) outdir = hlat_cmesh + '_' + hlat.lp['LatticeTop'] + '_varyloc_stills' + specstr + '/' fnout = outdir + filename + specstr + indstr + exten print 'saving figure: ' + fnout le.ensure_dir(outdir) fig.savefig(fnout, dpi=actual_dpi*2) # Save at lower res after antialiasing f_img = Image.open(fnout) f_img.resize((final_w, final_h), Image.ANTIALIAS).save(fnout) # clear patches p.remove() polypatches.remove() # del p # Update index ind += 1 if ind == len(ksize): done = True # Turn into movie imgname = outdir + filename + specstr movname = hlat_cmesh + filename + specstr + '_mov' subprocess.call(['./ffmpeg', '-framerate', str(int(framerate)), '-i', imgname + '_%06d' + exten, movname + '.mov', '-vcodec', 'libx264', '-profile:v', 'main', '-crf', '12', '-threads', '0', '-r', '30', '-pix_fmt', 'yuv420p'])
def plot_and_save_project_maps(db, nb_days, start, tasks_states, locked_tasks, project_data_dir, cartong_logo, legend, events): """ Plot and for each day the map with locked task and the map with the states changed :param db: Database of the project :param nb_days: Number of days of the project (there will 2*nb_days images) :param start: Start date of the project :param tasks_states: Dictionary of a list of task state for day, indexed by task id :param locked_tasks: List given the set of locked tasks for each day :param project_data_dir: Directory of the project in which images will be saved :param cartong_logo: Image of the CartONG logo displayed in top and left of each image :param legend: Image of the legend displayed in bottom and left of each image :param events: Dataframe of the events to add in the title OR None :return: """ print('Plot and save project maps') for day in tqdm(range(nb_days + 1)): for plot_lock in [True, False]: fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(10, 10), dpi=100, sharex=True) for feature in db.get_task_features(): # Plot borders arr = np.array( feature['geometry']['coordinates'][0][0]).transpose() plt.plot(arr[0], arr[1], color='black') # Plot locking or state task_id = feature['properties']['taskId'] state = tasks_states[task_id][day] if plot_lock and task_id in locked_tasks[day]: ax.add_patch( patches.Polygon(arr.transpose(), color=(159 / 255., 188 / 255., 247 / 255.))) # blue continue if state == 1: ax.add_patch( patches.Polygon(arr.transpose(), color=(254 / 255., 231 / 255., 156 / 255.))) # yellow continue if state == 2: ax.add_patch( patches.Polygon(arr.transpose(), color=(245 / 255., 156 / 255., 178 / 255.))) # pink continue if state == 3: ax.add_patch( patches.Polygon(arr.transpose(), color=(152 / 255., 203 / 255., 151 / 255.))) # green continue if state == 4: ax.add_patch( patches.Polygon(arr.transpose(), color=(152 / 255., 152 / 255., 151 / 255.))) # black continue # Plot priority area if db.get_priority_area() is not None: for priority_area in db.get_priority_area(): ax.add_patch( patches.Polygon(priority_area['coordinates'][0], fill=False, color='r', lw=2)) str_day_title = (start + pd.Timedelta(days=day)).strftime('%d-%m-%Y') if events is not None and day in events.index: str_day_title = str_day_title + ' ' + events.loc[day, 'event'] project_id = db.get_project_id() title = '\n'.join( textwrap.wrap(db.get_project_name() + ' #' + str(project_id), 50)) + '\n' + str_day_title ax.set_title(title, fontsize=16) ax.axis('off') # Same scale in both axis xlim = ax.get_xlim() ylim = ax.get_ylim() xscale = xlim[1] - xlim[0] yscale = ylim[1] - ylim[0] if xscale > yscale: ax.set_ylim([ ylim[0] - (xscale - yscale) / 2, ylim[1] + (xscale - yscale) / 2 ]) else: ax.set_xlim([ xlim[0] - (yscale - xscale) / 2, xlim[1] + (yscale - xscale) / 2 ]) # Save plot str_day_file = (start + pd.Timedelta(days=day)).strftime('%Y-%m-%d') suffix = '_2' if not plot_lock else '' file_path = os.path.join(project_data_dir, str_day_file + suffix + '.png') plt.savefig(file_path, dpi=100) plt.close() # Add CartONG logo im = Image.open(file_path) im.paste(cartong_logo, (0, 0)) im.paste(legend, (0, 1000 - legend.size[1])) im.save(file_path)
boxColors = ['darkkhaki', 'royalblue'] numBoxes = 4 medians = list(range(numBoxes)) for i in range(numBoxes): box = bp['boxes'][i] boxX = [] boxY = [] for j in range(5): boxX.append(box.get_xdata()[j]) boxY.append(box.get_ydata()[j]) boxCoords = list(zip(boxX, boxY)) # Alternate between Dark Khaki and Royal Blue k = i % 2 boxPolygon = mpatches.Polygon(boxCoords, facecolor=boxColors[k]) hist_dist_ax.add_patch(boxPolygon) # Now draw the median lines back over what we just filled in med = bp['medians'][i] medianX = [] medianY = [] for j in range(2): medianX.append(med.get_xdata()[j]) medianY.append(med.get_ydata()[j]) plt.plot(medianX, medianY, 'k') medians[i] = medianY[0] # Set the axes ranges and axes labels hist_dist_ax.set_xlim(0.5, numBoxes + 0.5) top = centers_distances.max() * 1.2 bottom = 0
def plotar_estrutura_otimizada(self, tecnica_otimizacao: int, rmin: float = 0, tipo_cmap: str = 'binary', visualizar_areas_barras=False): """Exibe a malha final gerada. cmad jet ou binary""" logger.info('Criando o desenho da malha final') plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['font.family'] = 'Calibri' # Resultados finais rho_final = self.dados.rhos_iteracao_final() results_gerais_finais = self.dados.resultados_gerais_iteracao_final() fig, ax = plt.subplots() win = plt.get_current_fig_manager() win.window.state('zoomed') ax.axis('equal') xmin, ymin, xmax, ymax = self.dados.poligono_dominio_estendido.bounds dx = xmax - xmin dy = ymax - ymin plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx) plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy) elementos_poli = [] elementos_barra = [] x_bar_max = 0 if self.dados.tem_barras(): x_bar_max = max(rho_final[self.dados.num_elementos_poli::]) for j, el in enumerate(self.dados.elementos): if j < self.dados.num_elementos_poli: if tipo_cmap == 'jet': elementos_poli.append( patches.Polygon(self.dados.nos[el], linewidth=0, fill=True, facecolor=cm.jet(rho_final[j]))) else: elementos_poli.append( patches.Polygon(self.dados.nos[el], linewidth=0, fill=True, facecolor=cm.binary(rho_final[j]))) else: verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]] codes = [path.Path.MOVETO, path.Path.LINETO] rho = 15 * rho_final[j] / x_bar_max # rho = 6 if rho_final[j] > 0 else 0 if rho > 0: if tipo_cmap == 'jet': elementos_barra.append( patches.PathPatch(path.Path(verts, codes), linewidth=rho, edgecolor='black')) else: elementos_barra.append( patches.PathPatch(path.Path(verts, codes), linewidth=rho, edgecolor='red')) # Enumerar os pontos if self.dados.tem_barras(): if visualizar_areas_barras: for i in range(self.dados.num_elementos_poli, self.dados.num_elementos): if rho_final[i] > 0: # Centro da barra nos_barra_i = self.dados.nos[self.dados.elementos[i]] c = (nos_barra_i[0] + nos_barra_i[1]) / 2 cor = 'white' if tipo_cmap == 'jet' else 'blue' ax.text(c[0], c[1], f'{rho_final[i] / x_bar_max:.2E}', ha="center", va="center", size=0.05 * min(dx, dy), color=cor) # Desenhar o domÃnio do desenho # contorno = self.dados.poligono_dominio_estendido.boundary.coords[:] # linhas_cont = [] # for lin in contorno: # linhas_cont.append(patches.PathPatch(path.Path(lin, [path.Path.MOVETO, path.Path.LINETO]), # linewidth=1, edgecolor='black')) # Adicionar marcador do diâmetro mÃnimo dos elementos path_diam_verts = [[xmax - rmin * 2 - 0.01 * dx, ymax - 0.01 * dx], [xmax - 0.01 * dx, ymax - 0.01 * dx]] path_diam_codes = [path.Path.MOVETO, path.Path.LINETO] path_diam = path.Path(path_diam_verts, path_diam_codes) ax.add_patch(patches.PathPatch(path_diam, linewidth=2, color='magenta')) ax.add_collection(PatchCollection(elementos_poli, match_original=True)) if self.dados.tem_barras(): ax.add_collection( PatchCollection(elementos_barra, match_original=True)) # ax.add_collection(PatchCollection(linhas_cont, match_original=True)) plt.axis('off') plt.grid(b=None) # TÃtulo # Fixos di = f'Di: {results_gerais_finais[5]:.2f}%' els = f'NumElems: {len(self.dados.elementos)}' vf = f'vol: {results_gerais_finais[4]:.4f}%' # Variáveis rmin = '' tecnica_otm = 'Técnica: ' if tecnica_otimizacao == 0: tecnica_otm += 'Sem filtro' else: rmin = f'rmin: {rmin}' if tecnica_otimizacao in OC.TECNICA_OTM_EP_LINEAR: tecnica_otm += 'Linear ' elif tecnica_otimizacao in OC.TECNICA_OTM_EP_HEAVISIDE: tecnica_otm += 'Heaviside ' else: raise ValueError( f'A técnica de otimização "{tecnica_otimizacao}" não é válida!' ) if tecnica_otimizacao in OC.TECNICA_OTM_EP_DIRETO: tecnica_otm += 'direto' elif tecnica_otimizacao in OC.TECNICA_OTM_EP_INVERSO: tecnica_otm += 'inverso' else: raise ValueError( f'A técnica de otimização "{tecnica_otimizacao}" não é válida!' ) plt.title(f'{tecnica_otm} {els} {vf} {di} {rmin}') plt.show()
def plotar_tensoes(self): """Exibe a malha final gerada. cmad jet ou binary""" plt.rcParams['pdf.fonttype'] = 42 plt.rcParams['font.family'] = 'Calibri' # Resultados finais tensoes = self.dados.ler_arquivo_entrada_dados_numpy(22) tensoes_norm = np.full(len(tensoes), 0.5) rho_final = self.dados.rhos_iteracao_final() for i, rho_i in enumerate(rho_final): if i < self.dados.num_elementos_poli: if abs(rho_i) > 1e-9: if tensoes[i] >= 0: tensoes_norm[i] = 1 else: tensoes_norm[i] = 0 else: if tensoes[i] >= 0: tensoes_norm[i] = 1 else: tensoes_norm[i] = 0 fig, ax = plt.subplots() win = plt.get_current_fig_manager() win.window.state('zoomed') ax.axis('equal') xmin, ymin, xmax, ymax = self.dados.poligono_dominio_estendido.bounds dx = xmax - xmin dy = ymax - ymin plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx) plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy) elementos_poli = [] elementos_barra = [] x_bar_max = max(rho_final[self.dados.num_elementos_poli::] ) if self.dados.tem_barras() else 0 for j, el in enumerate(self.dados.elementos): if j < self.dados.num_elementos_poli: elementos_poli.append( patches.Polygon(self.dados.nos[el], linewidth=0, fill=True, facecolor=cm.seismic(tensoes_norm[j]))) else: verts = [self.dados.nos[el[0]], self.dados.nos[el[1]]] codes = [path.Path.MOVETO, path.Path.LINETO] rho = 15 * rho_final[j] / x_bar_max # rho = 3 if rho_final[j] > 0 else 0 if rho > 0: elementos_barra.append( patches.PathPatch(path.Path(verts, codes), linewidth=rho, edgecolor=cm.seismic( tensoes_norm[j]))) ax.add_collection(PatchCollection(elementos_poli, match_original=True)) ax.add_collection(PatchCollection(elementos_barra, match_original=True)) plt.axis('off') plt.grid(b=None) plt.title(f'Tensões nos elementos') plt.show()
def plotar_estrutura_deformada(self, escala=1): """Exibe a malha final gerada""" logger.debug('Plotando a estrutura deformada') # Leitura dos dados importantes nos = self.dados.nos poli = self.dados.poligono_dominio_estendido vetor_elementos = self.dados.elementos fig, ax = plt.subplots() win = plt.get_current_fig_manager() win.window.state('zoomed') ax.axis('equal') xmin, ymin, xmax, ymax = poli.bounds dx = xmax - xmin dy = ymax - ymin plt.xlim(xmin - 0.1 * dx, xmax + 0.1 * dx) plt.ylim(ymin - 0.1 * dy, ymax + 0.1 * dy) nos_def = self.posicao_nos_deslocados(escala) elementos_poli_original = [] elementos_poli_deformado = [] elementos_barra = [] for el in vetor_elementos: if len(el) == 2: verts = [nos_def[el[0]], nos_def[el[1]]] codes = [path.Path.MOVETO, path.Path.LINETO] elementos_barra.append( patches.PathPatch(path.Path(verts, codes), linewidth=1, edgecolor='purple')) elif len(el) > 2: elementos_poli_original.append( patches.Polygon(self.dados.nos[el], linewidth=0.7, edgecolor=(0, 0, 0, 0.5), facecolor='None', linestyle='--')) elementos_poli_deformado.append( patches.Polygon(nos_def[el], linewidth=0.7, edgecolor='black', facecolor=(76 / 255, 191 / 255, 63 / 255, 0.4))) # Desenhar as cargas esc = min(dx, dy) dict_forcas = Estrutura.converter_vetor_forcas_em_dict(self.dados) dict_apoios = Estrutura.converter_vetor_apoios_em_dict(self.dados) for no in dict_forcas: for i, cg in enumerate(dict_forcas[no]): if cg != 0: delta_x, delta_y = (0.1 * esc, 0) if i == 0 else (0, 0.1 * esc) delta_x = -delta_x if i == 0 and cg < 0 else delta_x delta_y = -delta_y if i == 1 and cg < 0 else delta_y ax.add_patch( patches.Arrow(nos_def[no, 0], nos_def[no, 1], delta_x, delta_y, facecolor='blue', edgecolor='blue', width=0.01 * esc, linewidth=1)) # Desenhar os apoios path_apoios = [] for no in dict_apoios: for i, ap in enumerate(dict_apoios[no]): if ap != 0: p0 = nos[no] if i == 0: p1 = np.array([p0[0] - 0.025 * esc, p0[1]]) else: p1 = np.array([p0[0], p0[1] - 0.025 * esc]) path_apoios.append( path.Path([p0, p1], [path.Path.MOVETO, path.Path.LINETO])) ax.add_collection( PathCollection(path_apoios, linewidths=2, edgecolors='red')) ax.add_collection( PatchCollection(elementos_poli_original, match_original=True)) ax.add_collection( PatchCollection(elementos_poli_deformado, match_original=True)) ax.add_collection(PatchCollection(elementos_barra, match_original=True)) plt.axis('off') plt.grid(b=None) plt.title(f'Estrutura original deformada escala: {escala}') plt.show()
def generator(input_size=512, batch_size=32, background_ratio=3. / 8, random_scale=np.array([0.5, 1, 2.0, 3.0]), vis=False): image_list = np.array(get_images()) print('{} training images in {}'.format(image_list.shape[0], FLAGS.training_data_path)) index = np.arange(0, image_list.shape[0]) while True: np.random.shuffle(index) images = [] score_maps = [] for i in index: try: im_fn = image_list[i] im = cv2.imread(im_fn) # print im_fn h, w, _ = im.shape txt_fn = im_fn.replace( os.path.basename(im_fn).split('.')[1], 'txt') if not os.path.exists(txt_fn): continue text_polys, text_tags = load_annoataion(txt_fn) text_polys, text_tags = check_and_validate_polys( text_polys, text_tags, (h, w)) # if text_polys.shape[0] == 0: # continue # random scale this image rd_scale = np.random.choice(random_scale) im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale) text_polys *= rd_scale # print rd_scale # random crop a area from image if np.random.rand() < background_ratio: # crop background im = crop_area(im, text_polys, text_tags, crop_background=True) if im is None: # cannot find background continue else: im = crop_area(im, text_polys, text_tags, crop_background=False) if im is None: continue if vis: fig, axs = plt.subplots(1, 1) # axs[0].imshow(im[:, :, ::-1]) # axs[0].set_xticks([]) # axs[0].set_yticks([]) # for poly in text_polys: # poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) # poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) # axs[0].add_artist(Patches.Polygon( # poly * 4, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) # axs[0].text(poly[0, 0] * 4, poly[0, 1] * 4, '{:.0f}-{:.0f}'.format(poly_h * 4, poly_w * 4), # color='purple') # axs[1].imshow(score_map) # axs[1].set_xticks([]) # axs[1].set_yticks([]) axs.imshow(im[:, :, ::-1]) axs.set_xticks([]) axs.set_yticks([]) for poly in text_polys: poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) axs.add_artist( Patches.Polygon(poly, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) axs.text(poly[0, 0], poly[0, 1], '{:.0f}-{:.0f}'.format(poly_h, poly_w), color='purple') #axs[0, 0].imshow(im[:, :, ::-1]) #axs[0, 0].set_xticks([]) #axs[0, 0].set_yticks([]) #for poly in text_polys: #poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) #poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) #axs[0, 0].add_artist(Patches.Polygon( #poly, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) #axs[0, 0].text(poly[0, 0], poly[0, 1], '{:.0f}-{:.0f}'.format(poly_h, poly_w), color='purple') plt.tight_layout() plt.show() plt.close() images.append(im[:, :, ::-1].astype(np.float32)) #score_maps.append(score_map[::4, ::4, np.newaxis].astype(np.float32)) if len(images) == batch_size: yield images, score_maps images = [] score_maps = [] except Exception as e: import traceback traceback.print_exc() continue
def select_area(file, figa, axa2, store, store_short, im_ix, pixsize=1, count=0): """ Select and measures areas while true :param file: :param figa: :param axa2: :param store: :param store_short: :param im_ix: :param pixsize: :param count: :return: """ color_spread1 = np.linspace(0.05, 0.95, 10) farba = [cm.Set1(x) for x in color_spread1] ph = [] ph_count = 0 # figa.canvas.manager.window.deiconify() # figa.canvas.manager.window.tkraise() figa.suptitle(file) axa2.set_title( 'Select corners of the area you are interested in. Press ENTER when done' ) x = np.asarray(figa.ginput(n=-1, timeout=0)) """ conversion to polar coordinates and sort, convert back""" x = list(tuple(map(tuple, x))) cent = (sum([xx[0] for xx in x]) / len(x), sum([xx[1] for xx in x]) / len(x)) # sort by polar angle x.sort(key=lambda xx: math.atan2(xx[1] - cent[1], xx[0] - cent[0])) x = np.array(x) ph.append( axa2.add_patch( mpatch.Polygon(x, facecolor=farba[count % len(farba)], alpha=0.2))) # figa.canvas.manager.window.iconify() axa2.set_title('Are you happy? Press Y to store data or N to drop them') happiness = input( 'Are you happy? Press Y to store data or N to drop them\n') if happiness == 'y': axa2.set_title('STORING data') p = mpath.Path(x) surface_area = measure_surface(p, im_ix, pixsize) print('Area size [um2]: ', surface_area) store, store_short = store_area(store, store_short, file, x, surface_area, parallel=count) axa2.set_title('Do you wish to mark features inside area? Y or N') mark_yesno = input( 'Do you wish to mark features inside area? Y or N\n') if mark_yesno == 'y': # figa.canvas.manager.window.deiconify() # figa.canvas.manager.window.tkraise() features = mark_features(figa, axa2, colore=farba[count % len(farba)], drawn_path=p) store, store_short = store_features(store, store_short, file, features, surface_area, parallel=count) # figa.canvas.manager.window.iconify() del x, p, surface_area elif happiness == 'n': axa2.set_title('DELETING data') ph[ph_count].remove() del x return store, store_short, count, figa, axa2
ax.add_feature(cfeature.LAND, color='silver', zorder=0) ax.add_feature(cfeature.LAKES, color='white', zorder=1) for i in range(0, len(shapefile.shapes())): shape = shapefile.shape(i) record = shapefile.record(i) color = color_assignment(record) # if a shape has multiple parts make each one a separate patch if len(shape.parts) > 1: for j in range(0, len(shape.parts)): start_index = shape.parts[j] # the last part uses the remaining points and doesn't require and end_index if (j is (len(shape.parts) - 1)): patch = mpatches.Polygon(shape.points[start_index:], facecolor=color, edgecolor='black', linewidth=0.5, transform=ccrs.PlateCarree(), zorder=2) else: end_index = shape.parts[j + 1] patch = mpatches.Polygon(shape.points[start_index:end_index], facecolor=color, edgecolor='black', linewidth=0.5, transform=ccrs.PlateCarree(), zorder=2) ax.add_patch(patch) else: patch = mpatches.Polygon(shape.points, facecolor=color, edgecolor='black',
def __init__(self, name, type, x, y, x_extent, y_extent, z_extent, global_transform=0): self.name = name self.type = type self.x_og = x self.y_og = y self.x_pos, self.y_pos = rotate_origin_only(x, y, global_transform) self.x_extent = x_extent self.y_extent = y_extent self.z_extent = z_extent # will be probably stay unused for a while (unless side views are needed) self.global_transform = global_transform if global_transform != 0: self.coords = np.zeros([4, 2]) self.coords[0][0] = x self.coords[0][1] = y self.coords[1][0] = x + x_extent self.coords[1][1] = y self.coords[2][0] = x + x_extent self.coords[2][1] = y + y_extent self.coords[3][0] = x self.coords[3][1] = y + y_extent self.coords_transformed = rotate_via_numpy(self.coords, self.global_transform) self.boundaries = [] self.calc_boundaries(global_transform) if type == 'rect': if global_transform == 0: self.patch = patches.Rectangle((self.x_pos, self.y_pos), self.x_extent, self.y_extent, edgecolor='none', linewidth=1.5, fill=1, facecolor=[0, 0, 0, 0.5], alpha=0.4) else: self.patch = patches.Polygon(self.coords_transformed, True, edgecolor='none', linewidth=1.5, fill=1, facecolor=[0, 0, 0, 0.5], alpha=0.4) elif type == 'cyld': self.patch = patches.Ellipse((self.x_pos, self.y_pos), self.x_extent, self.y_extent, angle=global_transform, edgecolor='none', linewidth=1.5, fill=1, facecolor=[0, 0, 0, 0.5], alpha=0.4)
def __roll_support_patch(self, max_val): """ :param max_val: max scale of the plot """ radius = PATCH_SIZE * max_val count = 0 for node in self.system.supports_roll: direction = self.system.supports_roll_direction[count] rotate = self.system.supports_roll_rotate[count] x1 = np.cos(np.pi) * radius + node.vertex.x + radius # vertex.x z1 = np.sin(np.pi) * radius + node.vertex.y # vertex.y x2 = (np.cos(np.radians(90)) * radius + node.vertex.x + radius ) # vertex.x + radius z2 = np.sin( np.radians(90)) * radius + node.vertex.y # vertex.y + radius x3 = (np.cos(np.radians(270)) * radius + node.vertex.x + radius ) # vertex.x + radius z3 = np.sin( np.radians(270)) * radius + node.vertex.y # vertex.y - radius triangle = np.array([[x1, z1], [x2, z2], [x3, z3]]) if node.id in self.system.inclined_roll: angle = self.system.inclined_roll[node.id] triangle = rotate_xy(triangle, angle + np.pi * 0.5) support_patch = plt.Polygon(triangle, color="r", zorder=9) self.one_fig.add_patch(support_patch) self.one_fig.plot( triangle[1:, 0] - 0.5 * radius * np.sin(angle), triangle[1:, 1] - 0.5 * radius * np.cos(angle), color="r", ) if not rotate: rect_patch = mpatches.RegularPolygon( (node.vertex.x, node - node.vertex.y), numVertices=4, radius=radius, orientation=angle, color="r", zorder=9, fill=False, ) self.one_fig.add_patch(rect_patch) elif direction == 2: # horizontal roll support_patch = mpatches.RegularPolygon( (node.vertex.x, node.vertex.y - radius), numVertices=3, radius=radius, color="r", zorder=9, ) self.one_fig.add_patch(support_patch) y = -node.vertex.z - 2 * radius self.one_fig.plot( [node.vertex.x - radius, node.vertex.x + radius], [y, y], color="r") if not rotate: rect_patch = mpatches.Rectangle( (node.vertex.x - radius / 2, -node.vertex.z - radius / 2), radius, radius, color="r", zorder=9, fill=False, ) self.one_fig.add_patch(rect_patch) elif direction == 1: # vertical roll # translate the support to the node support_patch = mpatches.Polygon(triangle, color="r", zorder=9) self.one_fig.add_patch(support_patch) y = node.vertex.y - radius self.one_fig.plot( [ node.vertex.x + radius * 1.5, node.vertex.x + radius * 1.5 ], [y, y + 2 * radius], color="r", ) if not rotate: rect_patch = mpatches.Rectangle( (node.vertex.x - radius / 2, -node.vertex.z - radius / 2), radius, radius, color="r", zorder=9, fill=False, ) self.one_fig.add_patch(rect_patch) count += 1
def gotoScan(self, scanIndex): # clear scans if self.collection1 != None: self.collection1.remove() self.collection1 = None if self.collection2 != None: self.collection2.remove() self.collection2 = None if self.collection3 != None: self.collection3.remove() self.collection3 = None # clear texts for text in self.texts: text.remove() self.texts = [] if len(rectangles[scanIndex])>100 or len(sectors[scanIndex])>100: print "cowardly returns" return # les rectangles de recherche patches = [] for rectangle in rectangles[scanIndex]: x1, y1 = self.convertLocalToAbs( rectangle.x1, rectangle.y1, rectangle.index ) x2, y2 = self.convertLocalToAbs( rectangle.x2, rectangle.y2, rectangle.index ) m=mpatches.Rectangle( xy = (x1, y1), width=x2-x1, height=y2-y1, ec="none", fill=False) patches.append(m) self.texts.append( self.ax.text( (x1+x2)/2.0, (y1+y2)/2.0, rectangle.name, fontsize=12, color='blue')) #collection = PatchCollection(patches, facecolors = ("gray",), edgecolors=("blue",) ) #collection = PatchCollection(patches, edgecolors=("blue",) ) collection = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.3) colors = numpy.linspace(0, 1, len(patches)) collection.set_array(numpy.array(colors)) self.collection2 = self.ax.add_collection(collection) # les secteurs patches = [] for sector in sectors[scanIndex]: index = sector.index x0 = self.posScrutators[index][0] y0 = self.posScrutators[index][1] ''' theta0 = -pi/2 if index==2: theta0 = pi/2 ''' theta0 = thetaScrutateurs[index] x1 = x0 + sector.rmin * cos(sector.thetamin+theta0) y1 = y0 + sector.rmin * sin(sector.thetamin+theta0) x2 = x0 + sector.rmax * cos(sector.thetamin+theta0) y2 = y0 + sector.rmax * sin(sector.thetamin+theta0) x3 = x0 + sector.rmax * cos(sector.thetamax+theta0) y3 = y0 + sector.rmax * sin(sector.thetamax+theta0) x4 = x0 + sector.rmin * cos(sector.thetamax+theta0) y4 = y0 + sector.rmin * sin(sector.thetamax+theta0) x, y = self.convertLocalToAbs( numpy.array([x1, x2, x3, x4, x1]) , numpy.array([y1, y2, y3, y4, y1]) , sector.index ) m=mpatches.Polygon( numpy.transpose(numpy.array([x,y])), animated = True) patches.append(m) self.texts.append( self.ax.text( x[0], y[0], sector.name, fontsize=12, color='blue')) #colors = numpy.linspace(0, 1, len(patches)) #collection = PatchCollection(patches, cmap=plt.cm.cool, alpha=0.3) collection = PatchCollection(patches, cmap=plt.cm.Greys, alpha=0.3) #colors = numpy.linspace(0, 1, len(patches)) #collection.set_array(numpy.array(colors)) self.collection3 = self.ax.add_collection(collection) # les scans patches = [] for i in range(0,6): # ATTENTION SCAN A L'ENVERS !!!!!!!!!!!!!! ======> x, y = self.singleScanPlot(clusters[scanIndex][i].x, -clusters[scanIndex][i].y, i ) m=mpatches.Polygon( numpy.transpose(numpy.array([x,y])), animated = True) patches.append(m) collection = PatchCollection(patches, cmap=plt.cm.hsv, alpha=0.3) colors = numpy.linspace(0, 1, len(patches)) collection.set_array(numpy.array(colors)) self.collection1 = self.ax.add_collection(collection) plt.title('Scan %03d' % scanIndex)
def generator(input_size=512, batch_size=32, background_ratio=3. / 8, random_scale=np.array([0.5, 1, 2.0, 3.0]), vis=False): image_list = np.array(get_images()) print('{} training images in {}'.format(image_list.shape[0], FLAGS.training_data_path)) index = np.arange(0, image_list.shape[0]) while True: np.random.shuffle(index) images = [] image_fns = [] score_maps = [] geo_maps = [] training_masks = [] for i in index: try: im_fn = image_list[i] im = cv2.imread(im_fn) # print im_fn h, w, _ = im.shape txt_fn = im_fn.replace( os.path.basename(im_fn).split('.')[1], 'txt') txt_fn = os.path.dirname(txt_fn) + "/gt_" + os.path.basename( txt_fn) if not os.path.exists(txt_fn): print('text file {} does not exists'.format(txt_fn)) continue text_polys, text_tags = load_annoataion(txt_fn) text_polys, text_tags = check_and_validate_polys( text_polys, text_tags, (h, w)) # if text_polys.shape[0] == 0: # continue # random scale this image rd_scale = np.random.choice(random_scale) im = cv2.resize(im, dsize=None, fx=rd_scale, fy=rd_scale) text_polys *= rd_scale # print rd_scale # random crop a area from image if np.random.rand() < background_ratio: # crop background im, text_polys, text_tags = crop_area(im, text_polys, text_tags, crop_background=True) if text_polys.shape[0] > 0: # cannot find background continue # pad and resize image new_h, new_w, _ = im.shape max_h_w_i = np.max([new_h, new_w, input_size]) im_padded = np.zeros((max_h_w_i, max_h_w_i, 3), dtype=np.uint8) im_padded[:new_h, :new_w, :] = im.copy() im = cv2.resize(im_padded, dsize=(input_size, input_size)) score_map = np.zeros((input_size, input_size), dtype=np.uint8) geo_map_channels = 5 if FLAGS.geometry == 'RBOX' else 8 geo_map = np.zeros( (input_size, input_size, geo_map_channels), dtype=np.float32) training_mask = np.ones((input_size, input_size), dtype=np.uint8) else: im, text_polys, text_tags = crop_area( im, text_polys, text_tags, crop_background=False) if text_polys.shape[0] == 0: continue h, w, _ = im.shape # pad the image to the training input size or the longer side of image new_h, new_w, _ = im.shape max_h_w_i = np.max([new_h, new_w, input_size]) im_padded = np.zeros((max_h_w_i, max_h_w_i, 3), dtype=np.uint8) im_padded[:new_h, :new_w, :] = im.copy() im = im_padded # resize the image to input size new_h, new_w, _ = im.shape resize_h = input_size resize_w = input_size im = cv2.resize(im, dsize=(resize_w, resize_h)) resize_ratio_3_x = resize_w / float(new_w) resize_ratio_3_y = resize_h / float(new_h) text_polys[:, :, 0] *= resize_ratio_3_x text_polys[:, :, 1] *= resize_ratio_3_y new_h, new_w, _ = im.shape score_map, geo_map, training_mask = generate_rbox( (new_h, new_w), text_polys, text_tags) if vis: fig, axs = plt.subplots(3, 2, figsize=(20, 30)) # axs[0].imshow(im[:, :, ::-1]) # axs[0].set_xticks([]) # axs[0].set_yticks([]) # for poly in text_polys: # poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) # poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) # axs[0].add_artist(Patches.Polygon( # poly * 4, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) # axs[0].text(poly[0, 0] * 4, poly[0, 1] * 4, '{:.0f}-{:.0f}'.format(poly_h * 4, poly_w * 4), # color='purple') # axs[1].imshow(score_map) # axs[1].set_xticks([]) # axs[1].set_yticks([]) axs[0, 0].imshow(im[:, :, ::-1]) axs[0, 0].set_xticks([]) axs[0, 0].set_yticks([]) for poly in text_polys: poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) axs[0, 0].add_artist( Patches.Polygon(poly, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) axs[0, 0].text(poly[0, 0], poly[0, 1], '{:.0f}-{:.0f}'.format(poly_h, poly_w), color='purple') axs[0, 1].imshow(score_map[::, ::]) axs[0, 1].set_xticks([]) axs[0, 1].set_yticks([]) axs[1, 0].imshow(geo_map[::, ::, 0]) axs[1, 0].set_xticks([]) axs[1, 0].set_yticks([]) axs[1, 1].imshow(geo_map[::, ::, 1]) axs[1, 1].set_xticks([]) axs[1, 1].set_yticks([]) axs[2, 0].imshow(geo_map[::, ::, 2]) axs[2, 0].set_xticks([]) axs[2, 0].set_yticks([]) axs[2, 1].imshow(training_mask[::, ::]) axs[2, 1].set_xticks([]) axs[2, 1].set_yticks([]) plt.tight_layout() plt.show() plt.close() images.append(im[:, :, ::-1].astype(np.float32)) image_fns.append(im_fn) score_maps.append(score_map[::4, ::4, np.newaxis].astype(np.float32)) geo_maps.append(geo_map[::4, ::4, :].astype(np.float32)) training_masks.append( training_mask[::4, ::4, np.newaxis].astype(np.float32)) if len(images) == batch_size: yield images, image_fns, score_maps, geo_maps, training_masks images = [] image_fns = [] score_maps = [] geo_maps = [] training_masks = [] except Exception as e: import traceback traceback.print_exc() continue
# Add the patch to the Axes ax.add_patch(rect) # Create mask mnew = cv2.resize(mask, (int(w), int(h))) ret, thresh = cv2.threshold(mnew*255, 127, 255, 0) border = cv2.copyMakeBorder(thresh.astype('int32'), 1, 1, 1, 1, cv2.BORDER_CONSTANT, value=0 ) contours, hierarchy = cv2.findContours(border, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE, offset=(-1, -1)) # Move mask to ROI position for cnt in contours: cnt[:,0][:,0] += int(x1) cnt[:,0][:,1] += int(y1) poly = patches.Polygon(cnt[:,0], closed=True, edgecolor='r', facecolor=np.array(cls_color)/255, alpha=0.6) ax.add_patch(poly) ax.text(x1, y1, "{}:{:.2f}".format(cls_name, score * 100), family="sans-serif", bbox={"facecolor": "black", "alpha": 0.8, "pad": 0.7, "edgecolor": "none"}, verticalalignment="top", horizontalalignment="center", color="w", zorder=10,) fig.tight_layout() plt.axis('off') plt.savefig(os.path.join(outdir, img_name[:-4] + ".png")) print("{} instances detected".format(count))
def generator(FLAGS, input_size=512, background_ratio=3. / 8, is_train=True, idx=None, random_scale=np.array([0.5, 1, 2.0, 3.0]), vis=False): image_list = np.array(get_images(FLAGS.training_data_path)) if not idx is None: image_list = image_list[idx] #print('{} training images in {}'.format( # image_list.shape[0], FLAGS.training_data_path)) index = np.arange(0, image_list.shape[0]) epoch = 1 while True: np.random.shuffle(index) images = [] image_fns = [] score_maps = [] geo_maps = [] overly_small_text_region_training_masks = [] text_region_boundary_training_masks = [] for i in index: try: im_fn = image_list[i] im = cv2.imread(im_fn) h, w, _ = im.shape txt_fn = get_text_file(im_fn) if not os.path.exists(txt_fn): if not FLAGS.suppress_warnings_and_error_messages: print('text file {} does not exists'.format(txt_fn)) continue text_polys, text_tags = load_annotation(txt_fn) text_polys, text_tags = check_and_validate_polys( FLAGS, text_polys, text_tags, (h, w)) # random scale this image rd_scale = np.random.choice(random_scale) x_scale_variation = np.random.randint(-10, 10) / 100. y_scale_variation = np.random.randint(-10, 10) / 100. im = cv2.resize(im, dsize=None, fx=rd_scale + x_scale_variation, fy=rd_scale + y_scale_variation) text_polys[:, :, 0] *= rd_scale + x_scale_variation text_polys[:, :, 1] *= rd_scale + y_scale_variation # random crop a area from image if np.random.rand() < background_ratio: # crop background im, text_polys, text_tags = crop_area(FLAGS, im, text_polys, text_tags, crop_background=True) if text_polys.shape[0] > 0: # cannot find background continue # pad and resize image im, _, _ = pad_image(im, FLAGS.input_size, is_train) im = cv2.resize(im, dsize=(input_size, input_size)) score_map = np.zeros((input_size, input_size), dtype=np.uint8) geo_map_channels = 5 if FLAGS.geometry == 'RBOX' else 8 geo_map = np.zeros( (input_size, input_size, geo_map_channels), dtype=np.float32) overly_small_text_region_training_mask = np.ones( (input_size, input_size), dtype=np.uint8) text_region_boundary_training_mask = np.ones( (input_size, input_size), dtype=np.uint8) else: im, text_polys, text_tags = crop_area( FLAGS, im, text_polys, text_tags, crop_background=False) if text_polys.shape[0] == 0: continue h, w, _ = im.shape im, shift_h, shift_w = pad_image(im, FLAGS.input_size, is_train) im, text_polys = resize_image(im, text_polys, FLAGS.input_size, shift_h, shift_w) new_h, new_w, _ = im.shape score_map, geo_map, overly_small_text_region_training_mask, text_region_boundary_training_mask = generate_rbox( FLAGS, (new_h, new_w), text_polys, text_tags) if vis: fig, axs = plt.subplots(3, 2, figsize=(20, 30)) axs[0, 0].imshow(im[:, :, ::-1]) axs[0, 0].set_xticks([]) axs[0, 0].set_yticks([]) for poly in text_polys: poly_h = min(abs(poly[3, 1] - poly[0, 1]), abs(poly[2, 1] - poly[1, 1])) poly_w = min(abs(poly[1, 0] - poly[0, 0]), abs(poly[2, 0] - poly[3, 0])) axs[0, 0].add_artist( Patches.Polygon(poly, facecolor='none', edgecolor='green', linewidth=2, linestyle='-', fill=True)) axs[0, 0].text(poly[0, 0], poly[0, 1], '{:.0f}-{:.0f}'.format(poly_h, poly_w), color='purple') axs[0, 1].imshow(score_map[::, ::]) axs[0, 1].set_xticks([]) axs[0, 1].set_yticks([]) axs[1, 0].imshow(geo_map[::, ::, 0]) axs[1, 0].set_xticks([]) axs[1, 0].set_yticks([]) axs[1, 1].imshow(geo_map[::, ::, 1]) axs[1, 1].set_xticks([]) axs[1, 1].set_yticks([]) axs[2, 0].imshow(geo_map[::, ::, 2]) axs[2, 0].set_xticks([]) axs[2, 0].set_yticks([]) axs[2, 1].imshow(training_mask[::, ::]) axs[2, 1].set_xticks([]) axs[2, 1].set_yticks([]) plt.tight_layout() plt.show() plt.close() im = (im / 127.5) - 1. images.append(im[:, :, ::-1].astype(np.float32)) image_fns.append(im_fn) score_maps.append(score_map[::4, ::4, np.newaxis].astype(np.float32)) geo_maps.append(geo_map[::4, ::4, :].astype(np.float32)) overly_small_text_region_training_masks.append( overly_small_text_region_training_mask[::4, ::4, np.newaxis].astype( np.float32)) text_region_boundary_training_masks.append( text_region_boundary_training_mask[::4, ::4, np.newaxis].astype( np.float32)) if len(images) == FLAGS.batch_size: yield [ np.array(images), np.array(overly_small_text_region_training_masks), np.array(text_region_boundary_training_masks), np.array(score_maps) ], [np.array(score_maps), np.array(geo_maps)] images = [] image_fns = [] score_maps = [] geo_maps = [] overly_small_text_region_training_masks = [] text_region_boundary_training_masks = [] except Exception as e: import traceback if not FLAGS.suppress_warnings_and_error_messages: traceback.print_exc() continue epoch += 1
for node in noc_graph.nodes: if node.block_type == 'SB': x, y = node.position patch = pch.Rectangle((x - EDGE_WIDTH/2, y - EDGE_WIDTH/2), EDGE_WIDTH, EDGE_WIDTH, facecolor=COLORS[node.block_type], edgecolor=COLORS[node.block_type], zorder=10) ax.add_patch(patch) # draw the floorplan list_of_basis = nx.cycle_basis(noc_graph) list_of_basis = sorted(list_of_basis, key=lambda base : len(base)) i = 0 for base_cycle in list_of_basis[::-1]: coords = list(map(lambda node: [node.position[0], node.position[1]], base_cycle)) #print(coords) color = (random.random(), random.random(), random.random()) #patch = pch.Polygon(coords, zorder=0, color=COLORS[i]) patch = pch.Polygon(coords, zorder=0, color=RESOURCE_COLOR) i += 1 i %= len(COLORS) ax.add_patch(patch) # draw edges weights = nx.get_edge_attributes(noc_graph, 'weight') types = nx.get_edge_attributes(noc_graph, 'edge_type') for edge in noc_graph.edges: horizontal_edge = edge[0].position[1] == edge[1].position[1] color = WIRE_COLOR if types[edge] == 'SYNC' else GRLS_COLOR color = WIRE_COLOR if horizontal_edge: sorted(edge, key=lambda sw: sw.position[0]) xy = (edge[0].position[0] - EDGE_WIDTH / 2, edge[0].position[1] - EDGE_WIDTH / 2) width = edge[1].position[0] - edge[0].position[0] + EDGE_WIDTH
def ex_tutorial_zonal_statistics(): # check for GEOS enabled GDAL if not wradlib.util.has_geos(): print("NO GEOS support within GDAL, aborting...") return # Get RADOLAN grid coordinates grid_xy_radolan = wradlib.georef.get_radolan_grid(900, 900) x_radolan = grid_xy_radolan[:, :, 0] y_radolan = grid_xy_radolan[:, :, 1] # create radolan projection osr object proj_stereo = wradlib.georef.create_osr("dwd-radolan") # create Gauss Krueger zone 2 projection osr object proj_gk = osr.SpatialReference() proj_gk.ImportFromEPSG(31466) # transform radolan polar stereographic projection to GK2 xy = wradlib.georef.reproject(grid_xy_radolan, projection_source=proj_stereo, projection_target=proj_gk) # Open shapefile (already in GK2) shpfile = os.path.dirname(__file__) + '/' + "data/agger/agger_merge.shp" dataset, inLayer = wradlib.io.open_shape(shpfile) cats, keys = wradlib.georef.get_shape_coordinates(inLayer) # Read and prepare the actual data (RADOLAN) f = os.path.dirname( __file__) + '/' + "data/radolan/raa01-sf_10000-1406100050-dwd---bin.gz" data, attrs = wradlib.io.read_RADOLAN_composite(f, missing=np.nan) sec = attrs['secondary'] data.flat[sec] = np.nan # Reduce grid size using a bounding box (to enhancing performance) bbox = inLayer.GetExtent() buffer = 5000. bbox = dict(left=bbox[0] - buffer, right=bbox[1] + buffer, bottom=bbox[2] - buffer, top=bbox[3] + buffer) mask, shape = wradlib.zonalstats.mask_from_bbox(xy[..., 0], xy[..., 1], bbox) xy_ = np.vstack((xy[..., 0][mask].ravel(), xy[..., 1][mask].ravel())).T data_ = data[mask] ########################################################################### # Approach #1: Assign grid points to each polygon and compute the average. # # - Uses matplotlib.path.Path # - Each point is weighted equally (assumption: polygon >> grid cell) # - this is quick, but theoretically dirty ########################################################################### t1 = dt.datetime.now() # Create instance of type ZonalDataPoint from source grid and catchment array zd = wradlib.zonalstats.ZonalDataPoint(xy_, cats, srs=proj_gk, buf=500.) # dump to file (for later use - see below) zd.dump_vector('test_zonal_points_cart') # Create instance of type GridPointsToPoly from zonal data object obj1 = wradlib.zonalstats.GridPointsToPoly(zd) isecs1 = obj1.zdata.isecs # for plotting (see below) t2 = dt.datetime.now() # Compute stats for target polygons avg1 = obj1.mean(data_.ravel()) var1 = obj1.var(data_.ravel()) t3 = dt.datetime.now() # Create instance of type GridPointsToPoly from zonal data file (much faster) obj1 = wradlib.zonalstats.GridPointsToPoly('test_zonal_points_cart') t4 = dt.datetime.now() print("Approach #1 computation time:") print("\tCreate object from scratch: %f seconds" % (t2 - t1).total_seconds()) print("\tCreate object from dumped file: %f seconds" % (t4 - t3).total_seconds()) print("\tCompute stats using object: %f seconds" % (t3 - t2).total_seconds()) # PLOTTING Approach #1 # Just a test for plotting results with zero buffer zd2 = wradlib.zonalstats.ZonalDataPoint(xy_, cats, buf=0) # Create instance of type GridPointsToPoly from zonal data object obj2 = wradlib.zonalstats.GridPointsToPoly(zd2) isecs2 = obj2.zdata.isecs # Illustrate results for an example catchment i i = 6 # try e.g. 48, 100 fig = plt.figure() ax = fig.add_subplot(111, aspect="equal") # Target polygon patches trg_patches = [patches.Polygon(item, True) for item in obj1.zdata.trg.data] trg_patch = [trg_patches[i]] p = PatchCollection(trg_patch, facecolor="None", edgecolor="black", linewidth=2) ax.add_collection(p) # pips sources = obj1.zdata.src.data plt.scatter(sources[:, 0], sources[:, 1], s=200, c="grey", edgecolor="None", label="all points") plt.scatter(isecs2[i][:, 0], isecs2[i][:, 1], s=200, c="green", edgecolor="None", label="buffer=0 m") plt.scatter(isecs1[i][:, 0], isecs1[i][:, 1], s=50, c="red", edgecolor="None", label="buffer=500 m") bbox = wradlib.zonalstats.get_bbox(cats[i][:, 0], cats[i][:, 1]) plt.xlim(bbox["left"] - 2000, bbox["right"] + 2000) plt.ylim(bbox["bottom"] - 2000, bbox["top"] + 2000) plt.legend() plt.title("Catchment #%d: Points considered for stats" % i) # Plot average rainfall and original data testplot(trg_patches, avg1, xy, data, title="Catchment rainfall mean (GridPointsToPoly)") testplot(trg_patches, var1, xy, data, levels=np.arange(0, np.max(var1), 1.), title="Catchment rainfall variance (GridPointsToPoly)") ########################################################################### # Approach #2: Compute weighted mean based on fraction of source polygons in target polygons # # - This is more accurate (no assumptions), but probably slower... ########################################################################### # Create vertices for each grid cell (MUST BE DONE IN NATIVE RADOLAN COORDINATES) grdverts = wradlib.zonalstats.grid_centers_to_vertices( x_radolan[mask], y_radolan[mask], 1., 1.) # And reproject to Cartesian reference system (here: GK2) grdverts = wradlib.georef.reproject(grdverts, projection_source=proj_stereo, projection_target=proj_gk) t1 = dt.datetime.now() # Create instance of type ZonalDataPoly from source grid and catchment array zd = wradlib.zonalstats.ZonalDataPoly(grdverts, cats, srs=proj_gk) # dump to file zd.dump_vector('test_zonal_poly_cart') # Create instance of type GridPointsToPoly from zonal data object obj3 = wradlib.zonalstats.GridCellsToPoly(zd) t2 = dt.datetime.now() # Compute stats for target polygons avg3 = obj3.mean(data_.ravel()) var3 = obj3.var(data_.ravel()) t3 = dt.datetime.now() # Create instance of type GridCellsToPoly from zonal data file obj3 = wradlib.zonalstats.GridCellsToPoly('test_zonal_poly_cart') t4 = dt.datetime.now() print("Approach #2 computation time:") print("\tCreate object from scratch: %f seconds" % (t2 - t1).total_seconds()) print("\tCreate object from dumped file: %f seconds" % (t4 - t3).total_seconds()) print("\tCompute stats using object: %f seconds" % (t3 - t2).total_seconds()) # PLOTTING Approach #2 # Target polygon patches trg_patches = [patches.Polygon(item, True) for item in obj3.zdata.trg.data] # Plot average rainfall and original data testplot(trg_patches, avg3, xy, data, title="Catchment rainfall mean (GridCellsToPoly)") testplot(trg_patches, var3, xy, data, levels=np.arange(0, np.max(var3), 1.), title="Catchment rainfall variance (GridCellsToPoly)") # Illustrate results for an example catchment i i = 6 # try any index between 0 and 13 fig = plt.figure() ax = fig.add_subplot(111, aspect="equal") # Grid cell patches src_index = obj3.zdata.get_source_index(i) grd_patches = [ patches.Polygon(item) for item in obj3.zdata.src.get_data_by_idx(src_index) ] p = PatchCollection(grd_patches, facecolor="None", edgecolor="black") ax.add_collection(p) # Target polygon patches trg_patch = [trg_patches[i]] p = PatchCollection(trg_patch, facecolor="None", edgecolor="red", linewidth=2) ax.add_collection(p) # View the actual intersections isecs = obj3.zdata.get_isec(i) isec_patches = wradlib.zonalstats.numpy_to_pathpatch(isecs) colors = 100 * np.linspace(0, 1., len(isec_patches)) p = PatchCollection(isec_patches, cmap=plt.cm.jet, alpha=0.5) p.set_array(np.array(colors)) ax.add_collection(p) bbox = wradlib.zonalstats.get_bbox(cats[i][:, 0], cats[i][:, 1]) plt.xlim(bbox["left"] - 2000, bbox["right"] + 2000) plt.ylim(bbox["bottom"] - 2000, bbox["top"] + 2000) plt.draw() # Compare estimates maxlim = np.max(np.concatenate((avg1, avg3))) fig = plt.figure(figsize=(14, 8)) ax = fig.add_subplot(111, aspect="equal") plt.scatter(avg1, avg3, edgecolor="None", alpha=0.5) plt.xlabel("Average of points in or close to polygon (mm)") plt.ylabel("Area-weighted average (mm)") plt.xlim(0, maxlim) plt.ylim(0, maxlim) plt.plot([-1, maxlim + 1], [-1, maxlim + 1], color="black") plt.show()
def to_patches_polygon(self): """Return a corresponding patches.Polygon instance.""" self.angular_sort_vertices() return patches.Polygon(self.vertices)
def plot_hotspot(ax, blade_num, patch, title, ft=6, title_posi=-0.06, line_width=1.0): #patch format (((0,0),'R'),...) ax.axis('off') fontdict = {'fontsize': ft} ax.set_title(title, fontdict, position=(0.5, title_posi)) basic = ['K', 'R', 'H'] acid = ['D', 'E'] aromatic = ['F', 'W', 'Y'] polar = ['S', 'T', 'N', 'Q'] branch_phobic = ['V', 'L', 'I', 'M', 'A'] special_branch = ['P', 'G'] sulf = ['C'] res_hash = {'K':0,'R':0,'H':0,'D':1,'E':1,'F':2,'W':2,'Y':2,'S':3,'T':3,\ 'N':3,'Q':3,'V':4,'L':4,'I':4,'M':4,'A':4,'C':5,'P':6,'G':7,'*':8} res_hash = {'K':0,'R':0,'H':0,'D':8,'E':8,'F':8,'W':8,'Y':0,'S':0,'T':0,\ 'N':8,'Q':8,'V':8,'L':8,'I':8,'M':8,'A':8,'C':8,'P':8,'G':8,'*':8} res_hash = {'K':0,'R':0,'H':0,'D':8,'E':8,'F':1,'W':1,'Y':1,'S':2,'T':2,\ 'N':8,'Q':8,'V':8,'L':8,'I':8,'M':8,'A':8,'C':8,'P':8,'G':8,'*':8} colors = { 0: 'blue', 1: 'red', 2: 'green', 3: 'white', 4: 'purple', 5: 'brown', 6: 'yellow', 7: 'cyan', 8: 'none' } color_in = {} color_out = {} for i in range(blade_num): color_in[i] = 'none' for i in range(blade_num * 2): color_out[i] = 'none' text_in_num = [] text_out_num = [] text_in = [] text_out = [] for i, p in enumerate(patch): b = p[0][0] r = p[0][1] if r == 0: text_in_num.append(b) text_in.append(p[1]) color_in[b] = colors.get(res_hash.get(p[1], 8), 'none') else: text_out.append(p[1]) text_out_num.append(b * 2 + r - 1) color_out[b * 2 + r - 1] = colors.get(res_hash.get(p[1], 8), 'none') num_in = blade_num blade_bet = np.pi * 2 / num_in theta_in = [blade_bet * i for i in range(num_in)] r_in = 0.2 area_in = 0.064 center_in = [] for i in range(num_in): center_in.append(polar_to_rect(theta_in[i], r_in)) circ = patches.Circle(center_in[i], area_in, alpha=0.6, color=color_in[i], transform=ax.transAxes) ax.add_patch(circ) num_out = blade_num * 2 blade_bet = np.pi * 2 / num_out theta_out = [blade_bet * (i - 0.50) for i in range(num_out)] r_out = 0.4 area_out = 0.064 center_out = [] colors = ['blue', 'purple'] for i in range(num_out): center_out.append(polar_to_rect(theta_out[i], r_out)) circ = patches.Circle(center_out[i], area_out, alpha=0.6, color=color_out[i], transform=ax.transAxes) ax.add_patch(circ) for i, n in enumerate(text_in_num): ax.text(center_in[n][0], center_in[n][1], text_in[i], transform=ax.transAxes, horizontalalignment='center', verticalalignment='center', **fontdict) for i, n in enumerate(text_out_num): ax.text(center_out[n][0], center_out[n][1], text_out[i], transform=ax.transAxes, horizontalalignment='center', verticalalignment='center', **fontdict) for i in range(num_in): a = center_in[i] b = center_out[i * 2] c = center_out[i * 2 + 1] vx = [(a[0], a[1]), (b[0], b[1]), (c[0], c[1])] trip = patches.Polygon(vx, alpha=0.9, ls='dotted', lw=line_width, fill=False, facecolor='none', transform=ax.transAxes) ax.add_patch(trip)
def makeseg(self, startx, starty, endx, endy):#Make a segment return patches.Polygon(np.array([[startx, starty], [endx, endy]]), edgecolor=self.colour, facecolor='none', linewidth=self.linewidth, closed=False)
def createPdf(doc, pdfName): if not pdfName: return foun = doc.Foun fig = plt.figure() b = foun.Shape.BoundBox XMIN, YMIN, XMAX, YMAX = b.XMin, b.YMin, b.XMax, b.YMax XMIN -= .2 * abs(XMIN) YMIN -= .2 * abs(YMIN) XMAX += .2 * abs(XMAX) YMAX += .2 * abs(YMAX) x_max = [XMAX] x_min = [XMIN] y_max = [YMAX] y_min = [YMIN] bbbox = 500 ax1 = fig.add_subplot(111, aspect='equal') plt.axis('off') for e in foun.Shape.Edges: if e.BoundBox.ZLength == 0 and e.Vertexes[0].Z == 0: v1, v2 = e.Vertexes xy = [[v1.X, v1.Y], [v2.X, v2.Y]] p = patches.Polygon(xy, edgecolor='black', linewidth=.5, closed=False) ax1.add_patch(p) text_ratio = f'' for o in doc.Objects: if not (hasattr(o, 'ViewObject') and o.ViewObject.Visibility): continue if 'Punch' in o.Name: color = o.ViewObject.ShapeColor[:-1] for f in o.faces: if f.ViewObject.isVisible(): xy = [] for v in f.Shape.Vertexes: if v.Z == 0: xy.append([v.X, v.Y]) p = patches.Polygon(xy, edgecolor='black', linewidth=.4, linestyle='--', closed=False) ax1.add_patch(p) xy = [] for f in o.Shape.Faces: b = f.BoundBox if b.ZLength == 0 and b.ZMax == 0: xmin, ymin = b.XMin, b.YMin p = patches.Rectangle((xmin, ymin), o.bx, o.by, facecolor=color, edgecolor='black', linewidth=.3) ax1.add_patch(p) text_ratio += f'{o.number}:{o.Location}, ratio = {o.Ratio}\n' c = o.text.Placement.Base ha = 'right' va = 'center' if o.Location in ('Corner2', 'Edge2', 'Corner3', 'Interier'): ha = 'left' if o.Location in ('Corner3', 'Edge3', 'Corner4', 'Interier'): va = 'bottom' ax1.annotate(f'{o.Location}\n{o.Ratio}', (c.x, c.y), color=color, fontsize=4, ha=ha, va=va, rotation=0, annotation_clip=False) elif 'sketch' in o.Name: for g in o.Geometry: if hasattr(g, 'StartPoint'): v1 = g.StartPoint v2 = g.EndPoint xy = [[v1.x, v1.y], [v2.x, v2.y]] p = patches.Polygon(xy, edgecolor='grey', facecolor='white', linewidth=.2, linestyle='-.', closed=False) ax1.add_patch(p) elif hasattr(g, 'Center'): v = g.Location x, y = v.x, v.y r = g.Radius p = patches.Circle([x, y], r, facecolor='white', edgecolor='black', linewidth=.3) ax1.add_patch(p) # XMIN = x - 2 * r # YMAX = y + 2 * r b = o.Shape.BoundBox y_max.append(b.YMax) x_min.append(b.XMin) if 'x' in o.Name: x_max.append(b.XMax) elif 'y' in o.Name: y_min.append(b.YMin) elif 'Shape' in o.Name: v1, v2 = o.Shape.Vertexes xy = [[v1.X, v1.Y], [v2.X, v2.Y]] p = patches.Polygon(xy, edgecolor='grey', facecolor='white', linewidth=.2, linestyle='-.', closed=False) ax1.add_patch(p) elif 'Text' in o.Name: if len(o.Text) > 1: continue v = o.Placement.Base x, y = v.x, v.y ax1.annotate(o.Text[0], (x, y), color='black', fontsize=6, ha='center', va='center', rotation=0, annotation_clip=False) XMIN = min(x_min) - bbbox XMAX = max(x_max) + bbbox YMIN = min(y_min) - bbbox YMAX = max(y_max) + bbbox ax1.set_ylim(YMIN, YMAX) ax1.set_xlim(XMIN, XMAX) FreeCAD.Console.PrintMessage("Saving pdf file...") fig.savefig(pdfName, orientation='portrait', papertype='a4', bbox_inches='tight', dpi=600) FreeCAD.Console.PrintMessage("Pdf file saved as: " + pdfName) plt.close()
def cs_patch(): return patches.Polygon([[x_roi[0], y_level], [x_roi[1], y_level]], closed=False, color='r', lw=1)
def bbox_polygon(bbox): bx, by, bw, bh = bbox.xywh poly = np.array([[bx, by], [bx, by + bh], [bx + bw, by + bh], [bx + bw, by]]) return patches.Polygon(poly)
from matplotlib import pyplot as plt from matplotlib import patches as pt interceptors = [(8.62, 1.92), (0.44, 3.68), (8.59, 9.29), (8.64, 4.74), (2.32, 7.25), (9.96, 1.09), (9.1, 5.35), (3.83, 2.39), (1.51, 5.73), (5.97, 3.17)] imp = [(3.83, 2.39), (5.97, 3.17)] opt = [(3.83, 2.39), (5.97, 3.17), (8.64, 4.74), (9.1, 5.35), (8.62, 1.92), (2.32, 7.25), (1.51, 5.73), (0.44, 3.68)] fig, ax = plt.subplots() x1 = [i[0] * 10 for i in interceptors] y1 = [i[1] * 10 for i in interceptors] x2 = [i[0] * 10 for i in imp] y2 = [i[1] * 10 for i in imp] x3 = [i[0] * 10 for i in opt] y3 = [i[1] * 10 for i in opt] plt.xlabel('x co-ordinate (km)') plt.ylabel('y co-ordinate (km)') plt.title('All Interceptors (Blue)', color='blue') plt.scatter(x1, y1, s=100, marker='x') plt.title('Optimal Interceptors (Green)', color='green') plt.scatter(x3, y3, s=100, color='green', marker='x') plt.title('Minimum Interceptors (Red)', color='red') plt.scatter(x2, y2, s=100, color='red', marker='x') plt.grid() ax.add_patch(pt.Polygon(interceptors, True)) plt.savefig('7.png')