def example_image(graph, filename, layout='spring', edge_labels=False, node_labels=False, show=False): """Generates example image with graph. Uses nx.draw_networkx_* methods, and matplotlib to draw and save the image. """ # positions for all nodes pos = LAYOUT_DICT[layout](graph) # configure the image plt.figure(figsize=(2, 2)) plt.axis('off') # draw all of the things! nx.draw_networkx_nodes(graph, pos, nodelist=graph.nodes(), node_color='r') nx.draw_networkx_edges(graph, pos, width=1.0, alpha=0.5, arrows=True) if node_labels: nlabels = {node: str(node) for node in graph.nodes()} nx.draw_networkx_labels(graph, pos, nlabels, font_size=16) if edge_labels: elabels = {edge: str(idx) for idx, edge in enumerate(graph.edges())} nx.draw_networkx_edge_labels(graph, pos, elabels) # place the file where it belongs path = os.path.join(os.environ['ERDOS_PATH'], "content/images", filename) plt.savefig(path) if show: plt.show()
def f(self, **kwargs): kwargs['always_apply'] = True print(kwargs) aug = self.tfms(**kwargs) # Just copy all images, next step will be for continious albus image = aug(image=self.image.copy())['image'] plt.figure(figsize=(10, 10)) plt.imshow(image) plt.axis('off') plt.show()
def plotMagnitudePhaseImage(self, image): mag = absolute(image).astype('float') phase = angle(image).astype('float') plt.subplot(211) plt.imshow(mag, cmap = cm.Greys_r) plt.axis('off') plt.subplot(212) plt.imshow(phase, cmap = cm.Greys_r) plt.axis('off') plt.show()
def Brightness_map(image, image_name): # map = (image[:, :, 0] + image[:, :, 1] + image[:, :, 2]) / 3 map = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY) map = map.reshape(image.shape[0] * image.shape[1], 1) km = KMeans(n_clusters=16).fit(map) map = km.labels_.reshape(image.shape[0], image.shape[1]) plt.imshow(map / map.max(), cmap='gray') plt.axis('off') plt.savefig(image_name + '_brightness_map') np.save(image_name + '_brightness_map.npy', map)
def saveMagPhaseImage(self, image, filename): mag = absolute(image).astype('float') phase = angle(image).astype('float') plt.subplot(211) plt.imshow(mag, cmap=cm.Greys_r) plt.title('Magnitude') plt.axis('off') plt.subplot(212) plt.imshow(phase, cmap=cm.Greys_r) plt.title('Phase') plt.axis('off') plt.savefig(filename)
def texture_ID(image, map, image_name): for ch in range(3): channel = map[:, :, ch, :] channel = channel.reshape(image.shape[0] * image.shape[1], map.shape[-1]) km = KMeans(n_clusters=64).fit(channel) T_channel = km.labels_.reshape(image.shape[0], image.shape[1]) image[:, :, ch] = T_channel plt.imshow(image/image.max()) plt.axis('off') plt.savefig(image_name + '_texture_map') np.save(image_name + '_texture_map.npy', image)
def save_plot(filter_bank, name): rows , cols = filter_bank.shape[0:2] plt.figure() sub = 1 for row in range(rows): for col in range(cols): plt.subplot(rows, cols, sub) plt.imshow(filter_bank[row][col], cmap='gray') plt.axis('off') sub += 1 plt.savefig(name)
def Color_map(image, image_name): for ch in range(3): channel = image[:, :, ch] channel = channel.reshape(image.shape[0] * image.shape[1], 1) km = KMeans(n_clusters=16).fit(channel) T_channel = km.labels_.reshape(image.shape[0], image.shape[1]) image[:, :, ch] = T_channel plt.imshow(image / image.max()) plt.axis('off') plt.savefig(image_name + '_color_map') np.save(image_name + '_color_map.npy', image)
def Gradient(image_name, map_name): mask_filters = Half_disk_masks(3, 8, plot=False) map = np.load(image_name + '_' + map_name + '_map.npy') # plt.imshow(map / map.max(), cmap='gray') # plt.savefig(image_name + '_map') gradients = [] for row in range(3): for col in range(4): left_mask = mask_filters[row][2 * col] right_mask = mask_filters[row][2 * col + 1] chi_sqr_dist = map * 0 k = map.max() + 1 for bin in range(k): bin_chi_dist = map * 0 temp = np.sign(-1 * (map - bin)) + 1 g_i = cv2.filter2D(temp, -1, left_mask) h_i = cv2.filter2D(temp, -1, right_mask) num = np.square(h_i - g_i) denom = 1. / (g_i + h_i + 0.000005) bin_chi_dist = np.multiply(num, denom) # for x in range(temp.shape[0]): # for y in range(temp.shape[1]): # for z in range(temp.shape[2]): # if g_i[x][y][z] + h_i[x][y][z] != 0: # bin_chi_dist[x][y][z] = (g_i[x][y][z] - h_i[x][y][z]) ** 2 / (g_i[x][y][z] + h_i[x][y][z]) chi_sqr_dist = chi_sqr_dist + bin_chi_dist / k gradients.append(chi_sqr_dist) gradient_map = np.mean(np.array(gradients), axis=0) if map_name == 'brightness': plt.imshow(gradient_map / gradient_map.max(), cmap='gray') else: plt.imshow(gradient_map / gradient_map.max()) plt.axis('off') plt.savefig(image_name + '_' + map_name + '_gradient_map') np.save(image_name + '_' + map_name + '_gradient.npy', gradient_map)
def augmentation_visualize_and_save(config, images, images_names, path, times: int = 2): """ Visualization of image enhancements. :param config: configuration from yaml file. :param images: images to be augmented. :param images_names: corresponding names of the images. :param path: the root where the augmented pictures will be saved. :param times: how many times each image getting augmented. :return: """ rows = len(images) cols = times + 1 for (index, image), name in zip(enumerate(images), images_names): plt.subplot(rows, cols, index * cols + 1) plt.axis('off') plt.title(name) _image = bgr2rgb_using_opencv(image) plt.imshow(_image) for col in range(1, cols): plt.subplot(rows, cols, index * cols + col + 1) plt.axis('off') plt.title("Augmented NO. " + str(col)) # augment image augmented_image = augment_image_using_imgaug(_image, config) plt.imshow(augmented_image) # Save the full figure isExists = os.path.exists(path) if not isExists: os.makedirs(path) now_time = datetime.datetime.now().strftime('%Y%m%d_%H%M%S') savefig(os.path.join(path, "%s_Comp.png" % now_time), dpi=600) # Clear the current figure plt.clf() plt.cla() plt.close()
def example_pic(): """Generate the example graph picture.""" # create graph from edge list graph = nx.Graph([(0, 1), (0, 2), (1, 3), (3, 0)]) # positions for all nodes pos = nx.spring_layout(graph) # each node is labaled by its own name labels = {node: str(node) for node in graph.node.keys()} # configure the image plt.figure(figsize=(2, 2)) plt.axis('off') # draw all of the things! nx.draw_networkx_nodes(graph, pos, nodelist=[0, 1, 2, 3], node_color='r') nx.draw_networkx_edges(graph, pos, width=1.0, alpha=0.5) nx.draw_networkx_labels(graph, pos, labels, font_size=16) # place the file where it belongs path = os.path.join(os.environ['ERDOS_PATH'], "content/images", "nodes_edges_example.png") plt.savefig(path)
def saveMagPhaseImage2(self, image1, image2, filename): mag = absolute(image1).astype('float') phase = angle(image1).astype('float') mag2 = absolute(image2).astype('float') phase2 = angle(image2).astype('float') plt.subplot(221) plt.imshow(mag, cmap=cm.Greys_r) plt.title('Magnitude') plt.axis('off') plt.subplot(222) plt.imshow(phase, cmap=cm.Greys_r) plt.title('Phase') plt.axis('off') plt.subplot(223) plt.imshow(mag2, cmap=cm.Greys_r) plt.title('Magnitude') plt.axis('off') plt.subplot(224) plt.imshow(phase2, cmap=cm.Greys_r) plt.title('Phase') plt.axis('off') plt.savefig(filename)
def saveWaterFatImage(self, filename): mag = np.absolute(self.water).astype('float') phase = np.angle(self.water).astype('float') mag2 = np.absolute(self.fat).astype('float') phase2 = np.angle(self.fat).astype('float') plt.subplot(221) plt.imshow(mag, cmap=cm.Greys_r) plt.title('Water Magnitude') plt.axis('off') plt.subplot(222) plt.imshow(phase, cmap=cm.Greys_r) plt.title('Water Phase') plt.axis('off') plt.subplot(223) plt.imshow(mag2, cmap=cm.Greys_r) plt.title('Fat Magnitude') plt.axis('off') plt.subplot(224) plt.imshow(phase2, cmap=cm.Greys_r) plt.title('Fat Phase') plt.axis('off') plt.show()
from IPython.display import display from matplotlib.pylab import plt data = pd.read_csv('house3.csv') data['total_price'] = data['price'] * data['area'] / 10000 data_mean = data.groupby('district')['price'].mean() data_count = data.groupby('district')['price'].count() #柱状图分析各区的二手房的房价 plt.figure(figsize=(10, 6)) plt.rc('font', family='SimHei', size=13) plt.title(u'各区域的平均二手房房价') plt.xlabel(u'南京城区') plt.ylabel(u'平均房价') plt.bar(data_mean.index, data_count.values, color='g') plt.show() plt.figure(figsize=(10, 10)) plt.rc('font', family='SimHei', size=13) explode = [0] * len(data_count) explode[9] = 0.1 plt.pie(data_count, radius=2, autopct='%1.f%%', shadow=True, labels=data_mean.index, explode=explode) plt.axis('equal') plt.show()
# Calculate color percentages groups = code.get_groups() groups.sort() counts = code.get_color_percentages(groups, vectors) # Save to file vectors.to_csv("color-vectors.csv") counts.to_csv("color-percentages.csv") # Generate 2d plot of all colors plt.figure(figsize=(20, 12)) plt.scatter(vectors["x_dim"], vectors["y_dim"], c=vectors[[0, 1, 2]].to_numpy() / 255) plt.title("CodeArt Color Map, All Groups") plt.axis("off") plt.savefig("colormap-2d.png") # We'll also save a gif import imageio images = [] # Generate a plot for each color for group in groups: colors = vectors[[0, 1, 2]] / 255 # Alpha layer (between 0 and 1 for matplotlib) based on year colors['alphas'] = counts.loc[:, "%s-percent" % group].tolist() plt.figure(figsize=(20, 12))
text = '' for i in range(0, len(f)): with open('D:\\视频\\tim专属文件\\yellow\\' + f[i], encoding='ansi') as x: for line in x.readlines(): line = line.strip('\n') line = line.replace('<br /><br /> ', '') line = line.replace('<br /> ', '') line = line.replace( '<br /><br /><br /><br /><br /><br /><br /><br />', '') line = line.replace('<BR> ', '') line = line.replace('<br /><br />', '') line = line.replace('<BR>', '') line = line.replace('nbsp', '') line = line.replace('br', '') print(0) text += ' '.join(jieba.cut(line)) a = Image.open('C:\\Users\\2271057973\\Pictures\\Saved Pictures\\太极.png') mask = np.array(a) wordcloud = WordCloud(font_path='./font/simhei.ttf', background_color='white', mask=mask, max_font_size=120, min_font_size=5).generate(text) plt.imshow(wordcloud) plt.axis('off') plt.show() wordcloud.to_file('C:\\Users\\2271057973\\Desktop\\2.png')
def plot(self, **kwargs): """A wrapper function for plotting a NetworkX graph This function will draw a provided NetworkX graph using either the spring layout algorithm, or by the positions provided. Parameters ---------- pos: dict, optional, default: networkx.drawing.layout.spring_layout A dictionary of the network's neurons as keys and their (x, y) coordinates as corresponding values. nodelist: list, optional, default: self.neurons Draw only specified neurons (nodes). node_size: int or list, optional, default: 300 The size of the plotted neurons in the network. node_color: (color string, or array of floats), optional, default: 'r' Can either be a single color format string (default=’r’), or a sequence of colors with the same length as nodelist. If numeric values are specified they will be mapped to colors using the cmap and vmin, vmax parameters. See matplotlib.scatter for more details. cmap: Matplotlib colormap, optional, default: None Colormap for mapping intensities of nodes. alpha: float, optional, default: 1.0 The transparency of the nodes. node_borders: (None, scalar, or sequence), optional, default: 'black' The color(s) of the node borders. edgelist: (collection of edge tuples), optional, default: self.connections Draw only specified edges. By default, the edges between all nodes will be drawn. If `[]` (i.e. empty list), then the edges between all nodes will be omitted from the figure. edge_alpha: float, optional, default is 1.0 The transparency of the edges. edge_color: (color string, or array of floats), default: 'r' Can either be a single color format string, or a sequence of colors with the same length as edgelist. If numeric values are specified they will be mapped to colors using the edge_cmap and edge_vmin, edge_vmax parameters. edge_cmap : Matplotlib colormap, optional, default: None Colormap for mapping intensities of edges. width: float, optional, default: 1.0 The width of the edges. labels: bool, optional, default: True If False, then omit node labels and edge labels. font_size: int, optional, default: 10 The size of the font for text labels. figsize: tuple, optional, default: (20, 20) The size of the network figure to be plotted. savefig: bool, optional, default: False When True, the plotted figure will be saved to the current working directory, in PDF format, at the default (or specified) DPI. dpi: int, optional, default: 600 The amount of dots per inch to use when saving the figure. In accordance with Nature's guidelines, the default is 600. Source: https://www.nature.com/nature/for-authors/final-submission title: str, optional, default: None The title of the plotted graph/network. Returns ------- pos: dict A dictionary of the network's neurons as keys and their (x, y) coordinates as corresponding values. """ # Get positions for all nodes pos = kwargs.get("pos", None) if pos is None: print( "A neuron position dictionary was not provided! The spring_layout function will be used to plot the network.", file=sys.stderr) pos = nx.spring_layout(self.network, weight="weight") # Size of the plot plt.figure(figsize=kwargs.get("figsize", (20, 20))) # Nodes cmap = kwargs.get("cmap", None) alpha = kwargs.get("alpha", 1.0) node_size = kwargs.get("node_size", 600) nodelist = kwargs.get("nodelist", self.neurons) node_color = kwargs.get("node_color", 'r') node_borders = kwargs.get("node_borders", "black") nx.draw_networkx_nodes(self.network, pos, nodelist=nodelist, alpha=alpha, node_size=node_size, cmap=cmap, node_color=node_color, edgecolors=node_borders) # Draw edges width = kwargs.get("width", 1.0) edge_alpha = kwargs.get("edge_alpha", 1.0) edge_color = kwargs.get("edge_color", 'r') edge_cmap = kwargs.get("edge_cmap", None) edgelist = kwargs.get("edgelist", self.connections) nx.draw_networkx_edges(self.network, pos, edgelist=edgelist, alpha=edge_alpha, width=width, edge_color=edge_color, edge_cmap=edge_cmap) # Draw labels if kwargs.get("labels", True): nx.draw_networkx_labels(self.network, pos, font_size=kwargs.get("font_size", 10)) plt.title(kwargs.get("title", None)) plt.axis("off") if kwargs.get("savefig", False): plt.savefig(kwargs.get("title", "my_neuron_network.pdf"), format="pdf", dpi=kwargs.get("dpi", 600)) plt.show() return pos
new_controller('example_configuration.cnf', 'example_controller.py', 'PIDAW', param) # Create a motor object for simulation motor = DC_Motor(configfile='model.cnf', controlmodule='example_controller') # Simulate the system with an alternating step reference ref, u, x, y = motor.simulate(30, 'steps') # Visualize simulation t = np.array([ii * motor.h for ii in range(len(u[0, :]))]) plt.figure(1) plt.step(t, u[0]) limits = np.array(plt.axis()) * np.array([1., 1., 1.1, 1.1]) plt.axis(limits) plt.title('Control signal(s)') plt.figure(2) plt.step(t, np.transpose(x)) limits = np.array(plt.axis()) * np.array([1., 1., 1.1, 1.1]) plt.axis(limits) plt.title('System states') plt.figure(3) plt.step(t, ref[0]) plt.step(t, x[0]) limits = np.array(plt.axis()) * np.array([1., 1., 1.1, 1.1]) plt.axis(limits) plt.title('Theta and reference')
y = [count[w] / tot for w in count] plt.plot(x, y, label="N={}".format(k)) return x, y def exact(): W = Lea.fastMax(W0 + U, 0) for k in range(1, 21): if k % 5 == 0: plt.plot(W.support(), W.pmf(), label="k={}".format(k)) W = Lea.fastMax(W + U, 0) return W.support(), W.pmf() plt.figure() plt.axis([0, 20, 0, 0.3]) plt.title("Exact") xex, yex = exact() plt.legend() tikz_save('waiting_time_1.tex', figureheight='5cm', figurewidth='5cm') plt.close() plt.figure() plt.axis([0, 20, 0, 0.3]) plt.title("Simulation") xsim, ysim = simulate() plt.legend() tikz_save('waiting_time_2.tex', figureheight='5cm', figurewidth='5cm') plt.close() plt.figure()
'sat_lim_min': -10 } new_controller('example_configuration.cnf', 'example_controller.py', 'PIDAW', param) # Create a motor object for simulation motor = DC_Motor(configfile='model.cnf', controlmodule='example_controller') # Simulate the system with an alternating step reference ref, u, x, y = motor.simulate(30, 'steps') # Visualize simulation t = np.array([ii * motor.h for ii in range(len(u[0,:]))]) plt.figure(1); plt.step(t, u[0]) limits = np.array(plt.axis())*np.array([1.,1.,1.1,1.1]) plt.axis(limits) plt.title('Control signal(s)') plt.figure(2); plt.step(t, np.transpose(x)) limits = np.array(plt.axis())*np.array([1.,1.,1.1,1.1]) plt.axis(limits) plt.title('System states') plt.figure(3); plt.step(t, ref[0]) plt.step(t, x[0]) limits = np.array(plt.axis())*np.array([1.,1.,1.1,1.1]) plt.axis(limits) plt.title('Theta and reference')