def snapshot(state, T, t): global img fig = pylab.figure(frameon=False, figsize=(260 / 100., 270 / 100.), dpi=100) ax = pylab.Axes(fig, [0, -0.05, 1., float(241) / float(270) - 0.05]) ax.set_axis_off() fig.add_axes(ax) if state == 1: ax.imshow(up, aspect='auto') elif state == -1: ax.imshow(down, aspect='auto') pylab.text(0.1, 1.05, 'T = ' + str(T), horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=20, color='#700000', fontweight='bold') pylab.text(0.12, 0.94, 't = ' + str(t), horizontalalignment='left', verticalalignment='bottom', transform=ax.transAxes, fontsize=20, color='#202157', fontweight='bold') fig.savefig('output/%03d.png' % img, transparent=True) img += 1 pylab.close(fig)
def snapshot(state, T, t): global img fig = pylab.figure(frameon=False, figsize=(260 / 100., 270 / 100.), dpi=100) ax = pylab.Axes(fig, [0, -0.05, 1., float(241) / float(270) - 0.05]) ax.set_axis_off() fig.add_axes(ax) if state == 1: ax.imshow(up, aspect="auto") elif state == -1: ax.imshow(down, aspect="auto") pylab.text(0.1, 1.05, "T = " + str(T), horizontalalignment="left", verticalalignment="bottom", transform=ax.transAxes, fontsize=20, color="#700000", fontweight="bold") pylab.text(0.12, 0.94, "t = " + str(t), horizontalalignment="left", verticalalignment="bottom", transform=ax.transAxes, fontsize=20, color="#202157", fontweight="bold") fig.savefig(output_dir + "/%03d.png" % img, transparent=True) img += 1 pylab.close(fig)
def drawArrowsOntoImg(image, imagePtsStart, imgPtsEnd, arrowHeadSize=0.9, fontSize=12): # draw image points into image and label the point id # image_points: array with 2 columns # point_id: list of point ids in same order as corresponding image_points file; if empty no points labeled # dpi from screen resolution fontProperties_text = {'size' : fontSize, 'family' : 'sans-serif'} matplotlib.rc('font', **fontProperties_text) fig = plt.figure(frameon=False) #dpi of screen resolution ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.axis('equal') ax.plot([p[0] for p in imagePtsStart], [p[1] for p in imagePtsStart], marker='o', ms=2, color='none', markeredgecolor='yellow', markeredgewidth=1) ax.set_axis_off() fig.add_axes(ax) scale_value = 0.25#0.1 qv = ax.quiver(imagePtsStart[:,0], imagePtsStart[:,1], (imgPtsEnd[:,0]-imagePtsStart[:,0]), (imgPtsEnd[:,1]-imagePtsStart[:,1]), #imgPtsEnd[:,0]-imagePtsStart[:,0]), (imgPtsEnd[:,1]-imagePtsStart[:,1] facecolor=['red'], linewidth=.1, width=.001, headwidth=5, headlength=5, angles='xy', scale_units='xy', scale=scale_value)#, edgecolor='') qk = ax.quiverkey(qv, arrowHeadSize, arrowHeadSize, 1, 'arrow scale 1:' + str(int(1/scale_value)), coordinates='figure', fontproperties=fontProperties_text) t = qk.text.set_color('w') ax.imshow(image, cmap='gray')#, aspect='normal') return plt
def no_ax_fig(k=1,figBaseSize=6,Gamma=1): """ Generates a figure of size (figBaseSize,Gamma*figBaseSize) with 1 axes. The axes and the box around the figure are not visible Parameters ---------- k: integer, expected Figure number. figBaseSize: integer, optional Horizontal size of the figure. Default value is 6. Gamma: real, optional Aspect ratio H/L, where H is the height of the figure and L is its horizontal length. Useful when a non-square figure is desired. Default value is 1 (squared figure). Returns ------- fig: 'Figure' ax: 'matplotlib.axes._axes.Axes' """ fig = pylab.figure(k,figsize=(figBaseSize,Gamma*figBaseSize)) ax = pylab.Axes(fig,[0,0,1,1]) # Size of canvas compared to figure ax.set_axis_off() # No Box around fig.clf() fig.add_axes(ax) for a in fig.axes: a.get_xaxis().set_visible(False) a.get_yaxis().set_visible(False) return fig,ax
def matches(im1, im2, matches, dist=None, options={}): """ show a figure with lines joining the accepted matches in im1 and im2 input: im1,im2 (images as arrays), locs1,locs2 (location of features), matchscores (as output from 'match'). """ scale = options.get("scale", 1) filename = options.get("filename", None) max_dist = options.get("max_dist", 100) line_width = options.get("line_width", 0.8) size = options.get("size", (12, 8)) separation = options.get("separation", 20) if scale != 1: s = numpy.array([scale, scale]) im1_size = numpy.array(im1.shape[1::-1] * s, dtype=numpy.uint16) im2_size = numpy.array(im2.shape[1::-1] * s, dtype=numpy.uint16) if scale < 0.5: im1_scaled = imaging.get_thumbnail(im1, size=im1_size) im2_scaled = imaging.get_thumbnail(im2, size=im2_size) else: im1_scaled = imaging.open_img(im1, size=im1_size) im2_scaled = imaging.open_img(im2, size=im2_size) im3 = append_images(im1_scaled, im2_scaled, separation) matches = [(m[0] * s, m[1] * s) for m in matches] else: im3 = append_images(im1, im2, separation) im1_scaled = im1 # Create figure fig = pylab.figure(frameon=False, figsize=size) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # Display image ax.imshow(im3) # Get colors if dist != None and len(dist) == len(matches): cs = [ getRedGreen(numpy.log(d + 1) / numpy.log(max_dist)) for d in dist ] else: cs = ['#00aaff' for m in matches] # Plot all lines offset_x = im1_scaled.shape[1] for i, ((x1, y1), (x2, y2)) in enumerate(matches): ax.plot([x1, x2 + offset_x + separation], [y1, y2], color=cs[i], lw=line_width) pylab.xlim(0, im3.shape[1]) pylab.ylim(im3.shape[0], 0) if filename != None: fig.savefig(filename, bbox_inches='tight', dpi=72)
def visualize_log(log, im1, im2, stop_at=None, scale=None, size=(14, 8)): # Prepare images if scale == None: scale = min(1.0, 600 / float(im1.shape[1])) s = numpy.array([scale, scale]) im1_size = numpy.array(im1.shape[1::-1] * s, dtype=numpy.uint16) im2_size = numpy.array(im2.shape[1::-1] * s, dtype=numpy.uint16) im1_scaled = imaging.get_thumbnail(im1, size=im1_size) im2_scaled = imaging.get_thumbnail(im2, size=im2_size) separation = 20 offset_x = im1_size[0] + separation im3 = append_images(im1_scaled, im2_scaled, separation) def translate_point(point, image="im1"): x, y = numpy.array(point) * s if image == "im1": return x, y else: return (x + offset_x, y) # Create figure fig = pylab.figure(frameon=False, figsize=size) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) # Display image ax.imshow(im3) # Plot log data for i, d in enumerate(log): # Enough? if stop_at != None and i > stop_at: break # Plot target grid ((x_min, x_max), (y_min, y_max)) = d["target_grid"] margin = d["margin"] # Add square ax.add_patch( pylab.Rectangle(translate_point((x_min + margin, y_min + margin), "im2"), (x_max - x_min - 2 * margin) * scale, (y_max - y_min - 2 * margin) * scale, fill=False)) # Add circle ax.add_patch( pylab.Circle(translate_point(d["query_pos"], "im1"), d["radius"] * scale, fill=False, linewidth=0.5)) # Add matches for pos_q, pos_t in d["matches"]: x1, x2 = numpy.array([pos_q[0], pos_t[0]]) * s y1, y2 = numpy.array([pos_q[1], pos_t[1]]) * s ax.plot([x1, x2 + offset_x], [y1, y2], color="#2595e3", lw=1) # Limit figure to area around im3 pylab.xlim(0, im3.shape[1]) pylab.ylim(im3.shape[0], 0)
def plotIRRScatterChart(simulation_no, field, yearly=False, country=None): """ Plots XY chart for correlation @field with CORRELLATION_FIELDS figures : <title, figure> dictionary ncols : number of columns of subplots wanted in the display nrows : number of rows of subplots wanted in the figure """ prefix = '' main = prefix + field real_field_shortname = addYearlyPrefix(field, yearly) figures = Database().getIterationValuesFromDb( simulation_no, [main], yearly, not_changing_fields=CORRELLATION_FIELDS.values()) cols, rows = getNumberColsRows(len(figures)) if not figures: print ValueError('No data in Database for simulation %s' % simulation_no) return None irrs = figures.pop(real_field_shortname) fig, axeslist = pylab.subplots(ncols=cols, nrows=rows) left, bottom, width, height = 0.2, 0.1, 0.6, 0.6 # margins as % of canvas size for ind, title in izip_longest(range(cols * rows), figures): obj = axeslist.ravel()[ind] if title is not None: values = figures[title] plot_title = title #titles[prefix+title] axes = pylab.Axes( obj.figure, [1, 1, 1, 1] ) # [left, bottom, width, height] where each value is between 0 and 1 obj.plot(irrs, values, 'o') obj.set_title(plot_title) obj.set_xlabel(real_field_shortname + "\n", labelpad=-2) limx, limy = getLimitValues(irrs, values) obj.set_xlim(limx) obj.set_ylim(limy) obj.figure.add_axes([12, 12, 12, 12], frameon=False) else: obj.set_axis_off() title = "Simulation %s. Scatter charts '%s'. %s" % ( simulation_no, addYearlyPrefix(field, yearly), getTitleBasedOnPeriod(yearly)) fig = pylab.gcf() fig.suptitle(title, fontsize=14) pylab.show()
def no_ax_fax(k=1, Gamma=1, fs_base=6): fig = pylab.figure(k, figsize=(fs_base * Gamma, fs_base)) ax = pylab.Axes(fig, [0, 0, 1, 1]) ax.set_axis_off() fig.clf() fig.add_axes(ax) for a in fig.axes: a.get_xaxis().set_visible(False) a.get_yaxis().set_visible(False) return fig, ax
def draw_tracks_raster(Final_Vals, image, dir_out, outputImgName, variableToDraw, cell_size, plt_title=None, log_norm=False): '''visualize''' #sort after flow velocity image_points = Final_Vals.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) #set font size fontProperties_text = {'size' : 12, 'family' : 'serif'} matplotlib.rc('font', **fontProperties_text) #draw figure fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.axis('equal') fig.add_axes(ax) transparency=.8 #set colors jet = plt.get_cmap('plasma') array_pts = np.zeros((image.shape[0] / cell_size, image.shape[1] / cell_size)) array_pts[:] = np.nan row_ind = np.asarray(image_points.y.values, dtype=np.int) - 1 col_ind = np.asarray(image_points.x.values, dtype=np.int) - 1 rowcol_ind = np.vstack((row_ind,col_ind)) rowcol_ind = rowcol_ind[rowcol_ind[:,0]>=0] rowcol_ind = rowcol_ind[rowcol_ind[:,1]>=0] row_ind = rowcol_ind[0,:] col_ind = rowcol_ind[1,:] array_pts[row_ind,col_ind] = image_points.velo.values ax.imshow(image, cmap = 'gray', extent=[0,image.shape[1],0,image.shape[0]]) ax.imshow(array_pts, cmap='plasma', extent=[0,image.shape[1],0,image.shape[0]], interpolation='bilinear', alpha=transparency) image_points = image_points.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) norm = mcolors.Normalize(min(image_points[variableToDraw]), max(image_points[variableToDraw])) sm = matplotlib.cm.ScalarMappable(cmap=jet, norm=norm) sm.set_array([]) fig.colorbar(sm, fraction=0.1, pad=0, shrink=0.5) fig.suptitle(plt_title) #save figure plt.savefig(os.path.join(dir_out, outputImgName), dpi=600)
def make_image(data, outputname, size=(20, 2), dpi=1000): fig = plt.figure() fig.set_size_inches(size) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) plt.set_cmap('jet') ax.imshow(data, aspect='equal') plt.savefig(outputname, dpi=dpi) plt.close()
def displ(image, output=None): fig = py.figure(frameon=False) fig.set_size_inches(6.5, 2.5) ax = py.Axes(fig, [0., 0., 1., 1.]) #ax.set_axis_off() fig.add_axes(ax) py.imshow(image, origin='lower', interpolation='nearest') if output == None: py.show(block=True) else: py.savefig(output, dpi=100)
def __init__(self, size=None, position=None, lambda_=None, theta=None, sigma=None, phase=None, trim=None, contrast=0.5, width=1, hide_dot=False): if not isinstance(np, ModuleType): message = """GaborPatch can not be initialized. The Python package 'Numpy' is not installed.""" raise ImportError(message) if not isinstance(pyplot, ModuleType): message = """GaborPatch can not be initialized. The Python package 'Matplotlib' is not installed.""" raise ImportError(message) fid, filename = tempfile.mkstemp( dir=stimuli.defaults.tempdir, suffix=".png") os.close(fid) Picture.__init__(self, filename, position) size = 200 diameter = 50 line_width = 20 * width inner_diameter = 5 * (int(hide_dot)-1) fig = plt.figure(frameon=False, figsize=(1, 1)) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pixel_map = np.zeros((size, size)) ax.imshow(pixel_map, cmap=plt.get_cmap('gray')) ax.add_patch(plt.Circle((size / 2, size / 2), diameter, color='w')) ax.add_patch(plt.Rectangle((size / 2 - line_width / 2, 0), line_width, size, color='k')) ax.add_patch(plt.Rectangle((0, size / 2 - line_width / 2), size, line_width, color='k')) ax.add_patch(plt.Circle((size / 2, size / 2), inner_diameter, color='w')) fig.canvas.draw() # Now we can save it to a numpy array. data = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='') data = data.reshape(fig.canvas.get_width_height()[::-1] + (3,)) #plt.show() self._pixel_array = data #save stimulus color_map = pyplot.get_cmap('gray') color_map.set_over(color="y") pyplot.imsave(fname = filename, arr = self._pixel_array, cmap = color_map, format="png", vmin=0, vmax=1) #plt.savefig(filename = filename, cmap = color_map, format="png") self._background_colour = [0, 0, 0]
def render_image(array, colorbar_limits, figsize=(3,3)): '''Create a base64 encoded version of data''' fig = pl.figure(frameon=False, figsize=figsize) ax = pl.Axes(fig, [0.,0.,1.,1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(array, cmap=pl.cm.jet, vmin=colorbar_limits[0], vmax=colorbar_limits[1]) img_data = StringIO.StringIO() fig.savefig(img_data, format='png') pl.close(fig) return _to_base64_img_src(img_data.getvalue())
def drawPointsToImg(img, points, switchCol=False): fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) fig.add_axes(ax) ax.axis('equal') ax.set_axis_off() if switchCol: ax.plot([p[0] for p in points], [p[1] for p in points], marker='o', ms=3, color='none', markeredgecolor='blue', markeredgewidth=1) else: ax.plot([p[1] for p in points], [p[0] for p in points], marker='o', ms=3, color='none', markeredgecolor='blue', markeredgewidth=1) ax.imshow(img, cmap='gray') return plt
def draw_points_onto_image(image, image_points, point_id, markSize=2, fontSize=8, switched=False): # draw image points into image and label the point id # image_points: array with 2 columns # point_id: list of point ids in same order as corresponding image_points file; if empty no points labeled # dpi from screen resolution set_markersize = markSize fontProperties_text = {'size' : fontSize, 'family' : 'serif'} matplotlib.rc('font', **fontProperties_text) fig = plt.figure(frameon=False) #dpi of screen resolution ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.axis('equal') fig.add_axes(ax) if switched: ax.plot([p[1] for p in image_points], [p[0] for p in image_points], marker='o', ms=set_markersize, color='green', markeredgecolor='green', markeredgewidth=1) else: ax.plot([p[0] for p in image_points], [p[1] for p in image_points], marker='o', ms=set_markersize, color='red', markeredgecolor='black', markeredgewidth=1, linestyle=' ') #ax.plot(image_points[:,0], image_points[:,1], "r.", markersize=set_markersize, markeredgecolor='black') if len(point_id) > 1: if not switched: for label, xl, yl in zip(point_id, image_points[:,0], image_points[:,1]): ax.annotate(str((label)), xy = (xl, yl), xytext=(xl+5, yl+1), color='blue', **fontProperties_text) else: for label, xl, yl in zip(point_id, image_points[:,1], image_points[:,0]): ax.annotate(str((label)), xy = (xl, yl), xytext=(xl+5, yl+1), color='blue', **fontProperties_text) #str(int(label) ax.imshow(image, cmap='gray')#, aspect='normal') return plt
def plot2DHist(points, name, x_dimension, y_dimension, fig): #add points to data at each corner, truncate data past corners. x = points[x_dimension] y = points[y_dimension] #truncate any data outside off -2,-2 2,2 borders index = [] for i in range(0, len(x)): if x[i] > 2 or x[i] < -2: index = numpy.append(index, i) if y[i] > 2 or y[i] < -2: index = numpy.append(index, i) x = numpy.delete(x, index) y = numpy.delete(y, index) #fix borders of histogram with edge points x = numpy.append(x, -2) y = numpy.append(y, -2) x = numpy.append(x, -2) y = numpy.append(y, 2) x = numpy.append(x, 2) y = numpy.append(y, -2) x = numpy.append(x, 2) y = numpy.append(y, 2) #pylab.axis("off") #fig = pylab.figure() dpi = fig.get_dpi() inches = 512.0 / dpi fig.set_size_inches(inches, inches) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pylab.hist2d(x, y, bins=100) pylab.set_cmap('gray') pylab.savefig(name + '.png') pylab.clf()
def AlignmentPlot(self, alignments): import pylab as plt import matplotlib.colors as colors import matplotlib.cm as cm vals = [] for align in alignments: for hsp in align.hsps: #print align.length, hsp.score, hsp.expect vals.append((align.title[:30] + '..', hsp.score, hsp.expect)) vals = sorted(vals, key=lambda x: x[2]) vals = zip(*vals[:50]) print vals f = plt.figure(figsize=(8, 10)) ax = plt.Axes(f, [.3, .05, .6, .9]) f.add_axes(ax) names = vals[0] evals = vals[1] y = range(len(names)) patches = ax.barh(y, evals, align='center') ax.set_yticks(y) ax.set_yticklabels(names) for tick in ax.yaxis.get_major_ticks(): tick.label.set_fontsize(8) # set the colors of each bar based on the weights for val, patch in zip(evals, patches): # We need to normalize the "weight" value between 0-1 # to generate an actual color... color = cm.jet(float(val) / max(evals)) print color patch.set_facecolor(color) #cb = f.colorbar(scalarMap) f.subplots_adjust(hspace=0.5) plt.show() return
def get_image(image, annList, dpi=100, **options): image = f2l(np.array(image)).squeeze().clip(0, 255) if image.max() > 1: image /= 255. # box_alpha = 0.5 # print(image.clip(0, 255).max()) color_list = colormap(rgb=True) / 255. # fig = Figure() fig = plt.figure(frameon=False) canvas = FigureCanvas(fig) fig.set_size_inches(image.shape[1] / dpi, image.shape[0] / dpi) # ax = fig.gca() ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.axis('off') fig.add_axes(ax) # im = im.clip(0, 1) # print(image) ax.imshow(image) mask_color_id = 0 for i in range(len(annList)): ann = annList[i] if "bbox" in ann: bbox = ann["bbox"] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], fill=False, edgecolor='r', linewidth=3.0, alpha=0.5)) # if show_class: if options.get( "show_text") == True or options.get("show_text") is None: score = ann["score"] or -1 ax.text(bbox[0], bbox[1] - 2, "%.1f" % score, fontsize=14, family='serif', bbox=dict(facecolor='g', alpha=1.0, pad=0, edgecolor='none'), color='white') # show mask if "segmentation" in ann: mask = ann2mask(ann)["mask"] img = np.ones(image.shape) # category_id = ann["category_id"] # mask_color_id = category_id - 1 # color_list = ["r", "g", "b","y", "w","orange","purple"] # color_mask = color_list[mask_color_id % len(color_list)] color_mask = color_list[mask_color_id % len(color_list), 0:3] mask_color_id += 1 # print("color id: %d - category_id: %d - color mask: %s" # %(mask_color_id, category_id, str(color_mask))) w_ratio = .4 for c in range(3): color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio for c in range(3): img[:, :, c] = color_mask[c] e = mask contour, hier = cv2.findContours(e.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) for c in contour: polygon = Polygon(c.reshape((-1, 2)), fill=True, facecolor=color_mask, edgecolor="white", linewidth=1.5, alpha=0.7) ax.add_patch(polygon) canvas.draw() # draw the canvas, cache the renderer width, height = fig.get_size_inches() * fig.get_dpi() # image = np.fromstring(canvas.tostring_rgb(), dtype='uint8') fig_image = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) plt.close() # print(fig_image) return fig_image
def processImage(args): # load the image and compute the ratio of the old height # to the new height, clone it, and resize it image = cv2.imread(args["image"]) ratio = image.shape[0] / 500.0 orig = image.copy() image = imutils.resize(image, height=500) edged = cv2.Canny(image, 75, 200) # res = np.hstack((gray,eqgray)) # find the contours in the edged image, keeping only the # largest ones, and initialize the screen contour (cnts, _) = cv2.findContours(edged.copy(), cv2.RETR_LIST, cv2.CHAIN_APPROX_SIMPLE) # sort by perimeter first and then area cnts = sorted(cnts, key=lambda x: cv2.arcLength(x, False), reverse=True)[:3] contour = sorted(cnts, key=lambda x: cv2.contourArea(x, False), reverse=True)[0] def removeInlier(points, closeLine=False): initial_area = cv2.contourArea(points) new_contour = points ratios = [] for i in range(len(points)): # new_contour = points.pop(i) new_contour = np.delete(new_contour, i, 0) new_area = cv2.contourArea(new_contour) ratios += [new_area / initial_area] new_contour = points index = np.argmax(ratios) return np.delete(points, index, 0) # approximate the contour peri = cv2.arcLength(contour, True) approx = cv2.approxPolyDP(contour, 0.02 * peri, True) approx = cv2.convexHull(approx) approx = approx.reshape((len(approx), 2)) while len(approx) > 4: approx = removeInlier(approx) # apply the four point transform to obtain a top-down # view of the original image warped = four_point_transform(orig, approx.reshape(4, 2) * ratio) if args["bw"] == "true": warped = cv2.cvtColor(warped, cv2.COLOR_BGR2GRAY) warped = threshold_adaptive(warped, 40, offset=7) warped = warped.astype("uint8") * 255 else: b, g, r = cv2.split(warped) # get b,g,r warped = cv2.merge([r, g, b]) # switch it to rgb final = imutils.resize(warped, height=650) sheet_ratio = final.shape[0] / float(final.shape[1]) fig = plt.figure(frameon=False) if str(args["a4"]) == "true": fig.set_size_inches(11.69, 8.27) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) else: fig.set_size_inches(3, 3 / sheet_ratio) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) if args["bw"] == "true": ax.imshow(final, aspect='auto', cmap=plt.get_cmap('gray')) else: ax.imshow(final, aspect='auto') format = str(args["format"]) path = str(args["out"]) filename = str(args["name"]).split(".")[0] plt.savefig(os.path.join(path, filename + "." + format), format=format, dpi=int(args["dpi"])) if args["koriginal"] == "true": orig_path = args["image"] orig_format = orig_path.split(".")[-1] shutil.copyfile(orig_path, os.path.join(path, filename + "." + orig_format))
self.draw(x, y, z, image, w) images[b_idx] = image return images def create_z(STACK_NPZ_FILENAME,DATA_DIR ): res = preprocess_images(DATA_DIR) np.savez_compressed(STACK_NPZ_FILENAME, **res) if __name__ == "__main__": import pylab sim = EmpiricalSim(64,6400,load_AS()) #img = for (idx,z) in enumerate(np.linspace(-500,500,9)): fig = pylab.figure(frameon=False) fig.set_size_inches(1,1) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pylab.imshow((sim.draw(3200,3200,z, np.zeros((64,64)), 1500.0))[:,:], interpolation="none", cmap="inferno") pylab.savefig("z_stack_{}.png".format(idx),dpi=512) for (idx,x) in enumerate(np.linspace(2700.0,3700.0,3)): fig = pylab.figure(frameon=False) fig.set_size_inches(1,1) ax = pylab.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) pylab.imshow((sim.draw(x,3200,0.0, np.zeros((64,64)), 1500.0))[:,:], interpolation="none", cmap="inferno") pylab.savefig("x_{}.png".format(idx),dpi=512) dense = np.random.randn(64,64)
fig_size = [fig_width, fig_height] params = { 'axes.labelsize': 10, 'text.fontsize': 8, 'legend.fontsize': 8, 'xtick.labelsize': 8.5, 'ytick.labelsize': 5.5, 'figure.figsize': fig_size, 'font.family': 'serif' } pl.rcParams.update(params) pl.clf() pl.figure() fig = pl.figure() axes = pl.Axes(fig, [.2, .2, .7, .7]) fig.add_axes(axes) axes.yaxis.set_major_formatter(formatter) pl.xlabel(r'$k [h^{-1} Mpc]$') pl.ylabel('P(k)') stef = np.loadtxt('/disk1/mjw/HOD_MockRun/Stefano/pk_06z09_H2/ps_1.txt') #pl.plot(stef[:,0], stef[:,1], label='Stefano, 2Mpc') # pl.plot(stef[:,0], stef[:,1], label='Stefano') data = np.loadtxt( '/disk1/mjw/HOD_MockRun/Data/Del2k/midK_Del2k_HODmocks_Mesh_4.00_CicWf_kInterval_0.01_001.dat' ) # pl.loglog(data[:,0], data[:,2], label='4 Mpc mesh')
def main(args): """fuckometer-graph.py: Makes graphs of fuckometer data. Usage: ./fuckometer-graph.py fuckometer.log 1008 -o fuckometer-7d.png Options: -o F --out Save graph to file F. -n N --last Only show the last N entries. -c --conky Format graph for use in conky. """ import time import os show_avg = True conky_mode = False conky_scale = 1.0 linecolor = '#aa4444' avgcolor = linecolor avgalpha = 0.33333 shade = '#000000' last = 0 sourcefiles = [] destfile = '/tmp/fuckometer.png' i = 0 while i < len(args): a = args[i] if a in ('-h', '--help'): return usage() elif a in ('-o', '--out'): i += 1 a = args[i] destfile = a elif a in ('-n', '--last'): i += 1 a = args[i] last = int(a) elif a in ('-c', '--conky'): conky_mode = True conky_scale = 0.4 pl.rcParams['axes.facecolor'] = 'black' pl.rcParams['figure.facecolor'] = 'black' pl.rcParams['figure.edgecolor'] = 'black' pl.rcParams['savefig.edgecolor'] = 'black' pl.rcParams['savefig.facecolor'] = 'black' pl.rcParams['savefig.pad_inches'] = 0.0 pl.rcParams['savefig.transparent'] = True #print(pl.rcParams) linecolor = '#ff0066' avgcolor = '#aa0000' avgalpha = 0.66666 shade = '#ffffff' else: try: last = int(a) except ValueError: sourcefiles.append(a) i += 1 for path in sourcefiles: if not os.path.exists(path): continue title = os.path.basename(path) points = [] start = None fp = open(path, "rb") if last: source = fp.readlines()[-last:] else: source = fp for line in source: # allow commenting out lines, # in case there's bad data to manually edit out # or context to edit in if line.startswith('#'): continue parts = line.split() when = time.strptime(' '.join(parts[0:2]), "%Y-%m-%d %H:%M:%S") # don't change date until 6am after midnight when = time.localtime(time.mktime(when) - (6*60*60)) # well, this is convoluted... 1 + days since 0001-01-01 # (not sure if it does time of day or just date) #mplwhen = mpl.dates.datestr2num(time.strftime('%m/%d/%Y %H:%M', when)) #when = mplwhen #mplwhen = mpl.dates.datestr2num(time.strftime('%m/%d/%Y', when)) mplwhen = mpl.dates.datestr2num(time.strftime('%Y-%m-%d %H:%M', when)) #when = mplwhen + (when[3]/24.0/365.24) + (when[4]/24.0/60.0/365.24) + (when[5]/24.0/60.0/60.0/365.24) when = mplwhen value = float(parts[2]) points.append((when, value)) points = [(when, value) for when,value in points] times = [t for t,s in points] values = [s for t,s in points] # show dates as dates #fmt = '%Y-%m-%d %H:%M' #fmt = '%Y-%m-%d' #fmt = '%m-%d' fmt = '%a' pl.gca().xaxis.set_major_formatter(mpl.dates.DateFormatter(fmt)) #locator = mpl.dates.AutoDateLocator #formatter = mpl.dates.AutoDateFormatter(locator) #pl.gca().xaxis.set_major_formatter(formatter) #pl.gca().xaxis.set_major_locator(mpl.dates.MonthLocator()) #pl.gcf().autofmt_xdate() # tilt the labels so more can fit if show_avg: # show average value over time... # (kinda sucks; needs to be time-based instead of sample-based) def end_weighted_mean(data): """weighted average, most-recent weighs more""" if not data: return 0 if len(data) == 1: return data[0] weighted = [(x*(i+0.5))/(len(data)/2.0) for (i,x) in enumerate(data)] result = sum(weighted) / float(len(weighted)) return result def mean(data): result = sum(data) / float(len(data)) return result samples = 6 def avg_value(n): #func = end_weighted_mean func = mean if n == 0: return values[n] elif n < samples: #return end_weighted_mean(values[:n+1]) return func(values[:n+1]) else: #return end_weighted_mean(values[n-samples:n+1]) return func(values[n-samples:n+1]) avgs = [avg_value(n+3) for n in range(len(values))] pl.plot(times, avgs, label=title + ' (avg)', color=avgcolor, alpha=avgalpha, linewidth=8*conky_scale) pl.plot(times, values, label=title, color=linecolor, linewidth=2*conky_scale) # shade every other day begin = times[0] end = times[-1] span = end - begin alpha = 0.05 if span > 0.1: #print('%.2f days spanned.' % (span)) # ensure today is never shaded odd = 0 if span % 2 > 1: odd = 1 #print('Odd.') # kludge: was backward when 0.01 < fpart(span) < 0.49 if span % 1 < 0.5: odd -= 1 #print('Odder.') # add a grey background to yesterday and every 2 days before for offset in range(odd, int(math.ceil(span)+1), 2): left = math.floor(begin) + offset right = left + 1 pl.axvspan(left, right, facecolor=shade, alpha=alpha, ymax=1.0, ymin=0.0) #pl.xlabel('date'); pl.ylabel('fuckometer') #pl.legend(loc=0) # get rid of the effing padding fig = pl.gcf() fig.set_frameon(False) bbox_inches = 'tight' pad_inches = 0.05 granularity = 2.0 # change image size based on the amount of data if len(values) < 500: fig.set_size_inches(4,3) else: fig.set_size_inches(8,3) fig.tight_layout(pad=0.0) if conky_mode: scale = 0.2125 # 85x63 pixels fig.set_size_inches(scale*4,scale*3) # scale almost as wide as possible granularity = 1.0 # get rid of as much padding as possible fig.axes[0].get_xaxis().set_visible(False) fig.axes[0].get_yaxis().set_visible(False) ax = pl.Axes(fig, [0,0,1,1]) bbox_inches = 0.0 pad_inches = 0.0 # https://stackoverflow.com/a/47999122 fig.subplots_adjust(left=0.01, bottom=0.03, right=1-0.02, top=1-0.03, wspace=0, hspace=0) # adjust boundaries highest = max(values) lowest = min(values) highest = highest + (granularity - (highest % granularity)) lowest = lowest - (lowest % granularity) pl.ylim((lowest, highest)) #pl.ylim((0, 100)) pl.xlim((min(times), max(times))) pl.savefig(destfile, bbox_inches=bbox_inches, pad_inches=pad_inches)
# save the output: savetracksmat = ('meantracks_' + infile).replace('.tif', '.mat') spio.savemat(savetracksmat, { 'meantracks_r': meantracks_r, 'meantracks_g': meantracks_g }) # used to plot matplotlib figures with no boundaries. width = float(n_cols) height = float(n_rows) # visualize the tracks along with first frame, you might notice 'contamination' of tracks, we can clean with up with post track filtering fig = plt.figure() fig.set_size_inches(width / height, 1, forward=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) ax.imshow(vidstack[0]) plot_tracks(meantracks_r, ax, color='r', lw=.2) plot_tracks(meantracks_g, ax, color='g', lw=.2) ax.set_xlim([0, n_cols]) ax.set_ylim([n_rows, 0]) ax.grid('off') ax.axis('off') fig.savefig(('tracksimg-no-filt_' + infile).replace('.tif', '.png'), dpi=height) plt.show() """ 4. Post Filtering of Superpixel Tracks. """
def pretty_vis(image, annList, show_class=False, alpha=0.0, dpi=100, **options): import cv2 from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas from matplotlib.patches import Polygon from matplotlib.figure import Figure from . import ann_utils as au # print(image) # if not image.as > 1: # image = image.astype(float)/255. image = f2l(image).squeeze().clip(0, 255) if image.max() > 1: image /= 255. # box_alpha = 0.5 # print(image.clip(0, 255).max()) color_list = colormap(rgb=True) / 255. # fig = Figure() fig = plt.figure(frameon=False) canvas = FigureCanvas(fig) fig.set_size_inches(image.shape[1] / dpi, image.shape[0] / dpi) # ax = fig.gca() ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.axis('off') fig.add_axes(ax) # im = im.clip(0, 1) # print(image) ax.imshow(image) # Display in largest to smallest order to reduce occlusion # areas = (boxes[:, 2] - boxes[:, 0]) * (boxes[:, 3] - boxes[:, 1]) # sorted_inds = np.argsort(-areas) mask_color_id = 0 for i in range(len(annList)): ann = annList[i] # bbox = boxes[i, :4] # score = boxes[i, -1] # bbox = au.ann2bbox(ann)["shape"] # score = ann["score"] # if score < thresh: # continue # show box (off by default, box_alpha=0.0) if "bbox" in ann: bbox = ann["bbox"] ax.add_patch( plt.Rectangle((bbox[0], bbox[1]), bbox[2], bbox[3], fill=False, edgecolor='r', linewidth=3.0, alpha=0.5)) # if show_class: # if options.get("show_text") == True or options.get("show_text") is None: # score = ann["score"] or -1 # ax.text( # bbox[0], bbox[1] - 2, # "%.1f" % score, # fontsize=14, # family='serif', # bbox=dict(facecolor='g', alpha=1.0, pad=0, edgecolor='none'), # color='white') # show mask if "segmentation" in ann: mask = au.ann2mask(ann)["mask"] img = np.ones(image.shape) # category_id = ann["category_id"] # mask_color_id = category_id - 1 # color_list = ["r", "g", "b","y", "w","orange","purple"] # color_mask = color_list[mask_color_id % len(color_list)] color_mask = color_list[mask_color_id % len(color_list), 0:3] mask_color_id += 1 # print("color id: %d - category_id: %d - color mask: %s" # %(mask_color_id, category_id, str(color_mask))) w_ratio = .4 for c in range(3): color_mask[c] = color_mask[c] * (1 - w_ratio) + w_ratio for c in range(3): img[:, :, c] = color_mask[c] e = mask contour, hier = cv2.findContours(e.copy(), cv2.RETR_CCOMP, cv2.CHAIN_APPROX_NONE) for c in contour: polygon = Polygon(c.reshape((-1, 2)), fill=True, facecolor=color_mask, edgecolor="white", linewidth=1.5, alpha=0.7) ax.add_patch(polygon) canvas.draw() # draw the canvas, cache the renderer width, height = fig.get_size_inches() * fig.get_dpi() # image = np.fromstring(canvas.tostring_rgb(), dtype='uint8') fig_image = np.fromstring(canvas.tostring_rgb(), dtype='uint8').reshape(int(height), int(width), 3) plt.close() # print(fig_image) return fig_image
parser.add_argument("-i", "--interactive", dest="int", action="store_true") parser.add_argument("-o", "--output", type=str) parser.set_defaults(show=True) parser.add_argument("path", type=str, help="path to scanned music") args = parser.parse_args() score = metaomr.open(args.path) if args.page is None: if args.output: from matplotlib.backends.backend_pdf import PdfPages import pylab as p with PdfPages(args.output) as pdf: for page in score: page.process() p.figure(figsize=page.orig_size) ax = p.Axes(p.gcf(),[0,0,1,1],yticks=[],xticks=[],frame_on=False) p.gcf().delaxes(p.gca()) p.gcf().add_axes(ax) page.show() pdf.savefig() p.close() else: for page in score: page.process() if args.show: page.show() else: page = score[args.page] page.layout() if args.show: page.show()
def comparePDFs(pairlist, labels = [], rmin = None, rmax = None, show = True, maglim = None, mag = 5, rw = None, legend = True): """Plot two PDFs on top of each other and difference curve. pairlist -- iterable of (r, gr) pairs to plot labels -- iterable of names for the pairs. If this is not the same length as the pairlist, a legend will not be shown (default []). rmin -- The minimum r-value to plot. If this is None (default), the lower bound of the PDF is not altered. rmax -- The maximum r-value to plot. If this is None (default), the upper bound of the PDF is not altered. show -- Show the plot (True) maglim -- Point after which to magnify the signal by mag. If None (default), no magnification will take place. mag -- Magnification factor (default 5) rw -- Rw value to display on the plot, if any. legend -- Display the legend (default True). The second PDF will be shown as blue circles below and the first as a red line. The difference curve will be in green and offset for clarity. """ rfit, grfit = pairlist[0] rdat, grdat = pairlist[1] labeldata = labels[1] labelfit = labels[0] # View min and max rvmin = max(rfit[0], rdat[0]) rvmin = rmin or rvmin rvmax = min(rfit[-1], rdat[-1]) rvmax = rmax or rfit[-1] gap = 2 - len(labels) labels = list(labels) labels.extend([""] * gap) # Put gr1 on the same grid as rdat gtemp = numpy.interp(rdat, rfit, grfit) # Calculate the difference diff = grdat - gtemp # Put rw in the label labeldiff = "difference" if len(labels) < 3 else labels[2] if rw is not None: labeldiff += " (Rw = %.3f)"%rw # Magnify if necessary if maglim is not None: grfit = grfit.copy() grfit[rfit > maglim] *= mag sel = rdat > maglim grdat = grdat.copy() grdat[sel] *= mag diff[sel] *= mag gtemp[sel] *= mag # Determine the offset for the difference curve. sel = numpy.logical_and( rdat <= rvmax, rdat >= rvmin) ymin = min(min(grdat[sel]), min(gtemp[sel])) ymax = max(diff[sel]) offset = -1.1*(ymax - ymin) # Set up the plot _configure() # Scale the x-limit based on the r-extent of the signal. This gives a nice # density of PDF peaks. rlim = rvmax - rvmin scale = rlim / 25.0 # Set a reasonable minimum of .8 and maximum of 1 scale = min(1, max(scale, 0.8)) figsize = [13.5, 4.5] figsize[0] *= scale fig = pylab.figure(1, figsize = figsize) # Get the margins based on the figure size lm = 0.12 / scale bm = 0.20 / scale rm = 0.02 / scale tm = 0.15 / scale axes = pylab.Axes(fig, [lm, bm, 1 - lm - rm, 1 - bm - tm]) fig.add_axes(axes) pylab.minorticks_on() pylab.plot(rdat, grdat, label = labeldata, marker = 'o', markerfacecolor = 'white', markeredgecolor = 'blue', markersize = 7, markeredgewidth = 0.75) pylab.plot(rfit, grfit, label = labelfit, linestyle = 'solid', linewidth = 2, color = 'red') pylab.plot(rdat, offset*numpy.ones_like(diff), linestyle = '--', linewidth = 1, color = 'black', dashes = (15, 15), aa = False) diff += offset pylab.plot(rdat, diff, label = labeldiff, linestyle = 'solid', linewidth = 1.5, color = 'green') if maglim is not None: # Add a line for the magnification cutoff pylab.axvline(maglim, 0, 1, linestyle = '--', color = 'black', linewidth = 1.5, dashes = (14, 7)) # FIXME - look for a place to put the maglim xpos = (rvmax*0.85 + maglim) / 2 / (rvmax - rvmin) if xpos <= 0.9: pylab.figtext(xpos, 0.7, "x%.1f"%mag, backgroundcolor='w') # Get a tight view pylab.xlim(rvmin, rvmax) ymin = min(diff[sel]) ymax = max(max(grdat[sel]), max(gtemp[sel])) yspan = ymax - ymin # Give a small boarder to the plot gap = 0.05 * yspan ymin -= gap ymax += gap pylab.ylim(ymin, ymax) # Make labels and legends pylab.xlabel("r $(\AA)$") pylab.ylabel("G $(\AA^{-1})$") #pylab.legend(loc = 0) if legend: pylab.legend(bbox_to_anchor=(0.005, 1.02, 0.99, .10), loc=3, ncol=3, mode="expand", borderaxespad=0) if show: pylab.show() return
def draw_tracks_raster(Final_Vals, image, dir_out, outputImgName, variableToDraw, cell_size, plt_title=None, log_norm=False): '''visualize''' #sort after flow velocity image_points = Final_Vals.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) #set font size fontProperties_text = {'size' : 12, 'family' : 'serif'} matplotlib.rc('font', **fontProperties_text) #draw figure fig = plt.figure(frameon=False) #dpi of screen resolution ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.axis('equal') fig.add_axes(ax) # edgecolor='black' # markeredgewidths=0 # markersize=10 transparency=.8 #set colors jet = plt.get_cmap('plasma') # cNorm = colors.SymLogNorm(linthresh=0.003, linscale=1, # vmin=image_points['velo'].min(), vmax=image_points['velo'].max()) # if log_norm: # cNorm = colors.LogNorm(vmin=image_points[variableToDraw].min(), vmax=image_points[variableToDraw].max()) # else: # cNorm = colors.Normalize(vmin=image_points[variableToDraw].min(), vmax=image_points[variableToDraw].max()) # scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) #add points # point_n = 0 # while point_n < image_points.shape[0]: # plt.plot(image_points.x.values[point_n], image_points.y[point_n], marker='s', ms=markersize, # color=scalarMap.to_rgba(image_points[variableToDraw][point_n]), # lw=0, markeredgecolor=edgecolor, markeredgewidth=markeredgewidths, alpha=transparency) # point_n = point_n + 1 array_pts = np.zeros((image.shape[0] / cell_size, image.shape[1] / cell_size)) array_pts[:] = np.nan row_ind = np.asarray(image_points.y.values, dtype=np.int) - 1 col_ind = np.asarray(image_points.x.values, dtype=np.int) - 1 rowcol_ind = np.vstack((row_ind,col_ind)) rowcol_ind = rowcol_ind[rowcol_ind[:,0]>=0] rowcol_ind = rowcol_ind[rowcol_ind[:,1]>=0] row_ind = rowcol_ind[0,:] col_ind = rowcol_ind[1,:] array_pts[row_ind,col_ind] = image_points.velo.values #pts[:,2].flatten() #ax.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB), aspect='normal') ax.imshow(image, cmap = 'gray', extent=[0,image.shape[1],0,image.shape[0]])#, aspect='normal') ax.imshow(array_pts, cmap='plasma', extent=[0,image.shape[1],0,image.shape[0]], interpolation='bilinear', alpha=transparency) image_points = image_points.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) # cmap = mcolors.LinearSegmentedColormap.from_list('my_cmap', scalarMap.to_rgba(image_points[variableToDraw])) norm = mcolors.Normalize(min(image_points[variableToDraw]), max(image_points[variableToDraw])) sm = matplotlib.cm.ScalarMappable(cmap=jet, norm=norm) #cmap=cmap sm.set_array([]) fig.colorbar(sm, fraction=0.1, pad=0, shrink=0.5) fig.suptitle(plt_title) #save figure plt.savefig(os.path.join(dir_out, outputImgName), dpi=600)
def draw_tracks(Final_Vals, image, dir_out, outputImgName, variableToDraw, log_norm=False, label_data=False, variableToLabel=None): try: '''visualize''' #sort after flow velocity image_points = Final_Vals.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) #set colors jet = plt.get_cmap('Spectral') if log_norm: cNorm = colors.LogNorm(vmin=image_points[variableToDraw].min(), vmax=image_points[variableToDraw].max()) else: cNorm = colors.Normalize(vmin=image_points[variableToDraw].min(), vmax=image_points[variableToDraw].max()) scalarMap = cmx.ScalarMappable(norm=cNorm, cmap=jet) #set font size fontProperties_text = {'size' : 12, 'family' : 'serif'} matplotlib.rc('font', **fontProperties_text) #draw figure fig = plt.figure(frameon=False) ax = plt.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() ax.axis('equal') fig.add_axes(ax) image_points = image_points.sort_values('id') image_points = image_points.reset_index(drop=True) #add arrows if len(image_points['id']) > 1: point_n = 0 label_criteria = 0 while point_n < image_points.shape[0]: try: if label_data: label, xl, yl, arr_x, arr_y = image_points[variableToLabel][point_n], image_points['x'][point_n], image_points['y'][point_n], image_points['x_tr'][point_n], image_points['y_tr'][point_n] else: xl, yl, arr_x, arr_y = image_points['x'][point_n], image_points['y'][point_n], image_points['x_tr'][point_n], image_points['y_tr'][point_n] ax.arrow(xl, yl, arr_x-xl, arr_y-yl, color=scalarMap.to_rgba(image_points[variableToDraw][point_n]), head_width = 3, head_length=3, width=1.5) # arr_x-xl, arr_y-yl point_n = point_n + 1 except Exception as e: point_n = point_n + 1 if label_data: if label_criteria == 0: ax.annotate(str("{0:.2f}".format(label)), xy = (xl, yl), color='black', **fontProperties_text) if point_n == image_points.shape[0]: continue if label_data: label_next = image_points[variableToLabel][point_n] if int(label_next) == label: label_criteria = 1 else: label_criteria = 0 ax.imshow(image, cmap = 'gray') image_points = image_points.sort_values(variableToDraw) image_points = image_points.reset_index(drop=True) norm = mcolors.Normalize(min(image_points[variableToDraw]), max(image_points[variableToDraw])) sm = matplotlib.cm.ScalarMappable(cmap=jet, norm=norm) sm.set_array([]) fig.colorbar(sm, fraction=0.1, pad=0, shrink=0.5) #save figure plt.savefig(os.path.join(dir_out, outputImgName), dpi=600) except Exception as e: print(e)
def read(file, sym, minimum, maximum, step): data = ic.columnfile('%s.gff' % file) #grain sizes if "grainno" not in data.titles: data.addcolumn(data.grain_id, 'grainno') if "grainvolume" in data.titles: scale = max(data.grainvolume**0.3333) data.addcolumn(data.grainvolume**0.3333 / scale * 100, 'size') else: data.addcolumn(100. * np.ones(data.nrows), 'size') rodx = [] rody = [] rodz = [] if "rodx" not in data.titles: for i in range(data.nrows): U = np.array([[data.U11[i], data.U12[i], data.U13[i]], [data.U21[i], data.U22[i], data.U23[i]], [data.U31[i], data.U32[i], data.U33[i]]]) rod = tools.u_to_rod(U) rodx.append(rod[0]) rody.append(rod[1]) rodz.append(rod[2]) data.addcolumn(np.array(rodx), 'rodx') data.addcolumn(np.array(rody), 'rody') data.addcolumn(np.array(rodz), 'rodz') if sym == "standard": #grain colours, so that all orientations in Cubic space are allowed maxhx = 62.8 * 3.14 / 180 minhx = -62.8 * 3.14 / 180 maxhy = 62.8 * 3.14 / 180 minhy = -62.8 * 3.14 / 180 maxhz = 62.8 * 3.14 / 180 minhz = -62.8 * 3.14 / 180 rr = data.rodx**2 + data.rody**2 + data.rodz**2 rr = np.sqrt(rr) theta = 2 * np.arctan(rr) r1 = data.rodx / rr r2 = data.rody / rr r3 = data.rodz / rr # normalise colours red = (r1 * theta - minhx) / (maxhx - minhx) green = (r2 * theta - minhy) / (maxhy - minhy) blue = (r3 * theta - minhz) / (maxhz - minhz) elif sym == "orthorhombic": # Fill orthorhombic stereographic triangle red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(1.0)) ax = pl.Axes(fig, [.2, .2, .7, .7]) ax.set_axis_off() fig.add_axes(ax) #plot triangle xa = np.zeros((101)) ya = np.zeros((101)) for i in range(101): xa[i] = np.cos(i * np.pi / 200.) ya[i] = np.sin(i * np.pi / 200.) pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, 1], [0, 0], 'black', linewidth=2) #lower line pl.plot([0, 0], [1, 0], 'black', linewidth=2) #left line pl.text(-0.02, -0.04, '[001]') pl.text(0.95, -0.04, '[100]') pl.text(-0.02, 1.01, '[010]') # Grains for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) axis = abs(U[2, :]) colour = np.zeros((3)) colour[0] = (2 * np.arcsin(abs(axis[2])) / np.pi)**1 colour[1] = (2 * np.arcsin(abs(axis[0])) / np.pi)**1 colour[2] = (2 * np.arcsin(abs(axis[1])) / np.pi)**1 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) X = axis[0] / (1 + axis[2]) Y = axis[1] / (1 + axis[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "cubic": # Fill cubic stereographic triangle red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(.9)) ax = pl.Axes(fig, [.2, .2, .7, .7]) ax.set_axis_off() fig.add_axes(ax) #plot triangle xa = np.zeros((21)) ya = np.zeros((21)) for i in range(21): ua = np.array([i / 20., 1., 1.]) UA = np.linalg.norm(ua) za = ua[2] + UA xa[i] = ua[1] / za ya[i] = ua[0] / za pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2) #lower line pl.plot([xa[20], 0], [ya[20], 0], 'black') # upper line pl.text(-0.01, -0.02, '[100]') pl.text(xa[0] - 0.01, -0.02, '[110]') pl.text(xa[-1] - 0.01, ya[-1] + 0.005, '[111]') # Grains for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) axis = abs(U[2, :]) colour = np.zeros((3)) for j in range(3): for k in range(j + 1, 3): if (axis[j] > axis[k]): colour[0] = axis[j] axis[j] = axis[k] axis[k] = colour[0] rr = np.sqrt(axis[0] * axis[0] / ((axis[2] + 1)) / ((axis[2] + 1)) + (axis[1] / (axis[2] + 1) + 1) * (axis[1] / (axis[2] + 1) + 1)) if axis[1] == 0: beta = 0 else: beta = np.arctan(axis[0] / axis[1]) colour[0] = ((np.sqrt(2.0) - rr) / (np.sqrt(2.0) - 1))**.5 colour[1] = ((1 - 4 * beta / np.pi) * ((rr - 1) / (np.sqrt(2.0) - 1)))**.5 colour[2] = (4 * beta / np.pi * ((rr - 1) / (np.sqrt(2.0) - 1)))**.5 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) X = axis[1] / (1 + axis[2]) Y = axis[0] / (1 + axis[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "hexagonal": ## Fill hexagonal stereographic triangle A = np.array([[0, 1, 0], [0, -np.sqrt(3), 1], [1, 0, 0]]) a0 = 1. / np.sqrt(3.) a1 = 1. a2 = 1. red = [] green = [] blue = [] fig = pl.figure(10, frameon=False, figsize=pl.figaspect(0.5)) ax = pl.Axes(fig, [0.2, .2, 0.6, 0.6]) ax.set_axis_off() fig.add_axes(ax) ## Plot triangle ya = np.array(list(range(51))) / 100. xa = np.sqrt(1 - ya**2) pl.plot(xa, ya, 'black') # Curved edge pl.plot([0, xa[0]], [0, 0.0001], 'black', linewidth=2) #lower line pl.plot([xa[-1], 0], [ya[-1], 0], 'black') # upper line ## Label crystalographic directions pl.text(-0.01, -0.02, '[0001]') pl.text(xa[0] - 0.03, -0.02, '[2-1-10]') pl.text(xa[-1] - 0.03, ya[-1] + 0.005, '[10-10]') ## Grains r = symmetry.rotations(6) for i in range(data.nrows): U = tools.rod_to_u([data.rodx[i], data.rody[i], data.rodz[i]]) square = 1 angle = 0 frac = 1. / np.sqrt(3.) for k in range(len(r)): g = np.dot(U, r[k]) a = np.arccos((np.trace(g) - 1) / 2) if g[2, 2] > 0: uvw = g[2, :] else: uvw = -g[2, :] ## needed to switch these indices to get correct color and inv pf location switch1 = uvw[0] switch2 = uvw[1] uvw[0] = switch2 uvw[1] = switch1 x = uvw[0] / (1 + uvw[2]) y = uvw[1] / (1 + uvw[2]) f = y / x s = x * x + y * y ## Finds r (symmetry) which plots grain into triangle if f <= frac and s <= square and x >= 0 and y >= 0: angle = a frac = f square = s UVW = uvw X = x Y = y colour = np.dot(np.transpose(A), np.transpose(UVW))**0.7 colour[0] = colour[0] / a2 colour[1] = colour[1] / a1 colour[2] = colour[2] / a0 mx = max(colour) colour = colour / mx red.append(colour[0]) green.append(colour[1]) blue.append(colour[2]) pl.plot(X, Y, 'o', color=colour) pl.xlim() elif sym == "e11": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps11_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse strain:", np.sum(data.grainvolume * data.eps11_s) / np.sum(data.grainvolume)) elif sym == "e22": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps22_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse strain:", np.sum(data.grainvolume * data.eps22_s) / np.sum(data.grainvolume)) elif sym == "e33": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps33_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "axial strain:", np.sum(data.grainvolume * data.eps33_s) / np.sum(data.grainvolume)) elif sym == "e12": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps12_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps12_s) / np.sum(data.grainvolume)) elif sym == "e13": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps13_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps13_s) / np.sum(data.grainvolume)) elif sym == "e23": try: colourbar(minimum, maximum, step, 'e-3') norm = colors.normalize(minimum * 1e-3, maximum * 1e-3) except: colourbar(-1, 1, 1, 'e-3') norm = colors.normalize(-1e-3, 1e-3) color = cm.jet(norm(data.eps23_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear strain:", np.sum(data.grainvolume * data.eps23_s) / np.sum(data.grainvolume)) elif sym == "s33": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig33_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "axial stress:", np.sum(data.grainvolume * data.sig33_s) / np.sum(data.grainvolume), "MPa") elif sym == "s11": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig11_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse s11 stress:", np.sum(data.grainvolume * data.sig11_s) / np.sum(data.grainvolume), "MPa") elif sym == "s22": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 150, 50, 'MPa') norm = colors.normalize(-50, 150) color = cm.jet(norm(data.sig22_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "transverse s22 stress:", np.sum(data.grainvolume * data.sig22_s) / np.sum(data.grainvolume), "MPa") elif sym == "s12": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig12_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s12 stress:", np.sum(data.grainvolume * data.sig12_s) / np.sum(data.grainvolume), "MPa") elif sym == "s13": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig13_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s13 stress:", np.sum(data.grainvolume * data.sig13_s) / np.sum(data.grainvolume), "MPa") elif sym == "s23": try: colourbar(minimum, maximum, step, 'MPa') norm = colors.normalize(minimum, maximum) except: colourbar(-50, 50, 50, 'MPa') norm = colors.normalize(-50, 50) color = cm.jet(norm(data.sig23_s)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print( "shear s23 stress:", np.sum(data.grainvolume * data.sig23_s) / np.sum(data.grainvolume), "MPa") elif sym == "latt_rot": norm = colors.normalize(0, 0.5) color = cm.jet(norm(data.latt_rot)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] colourbar(0.0, 0.5, 0.1, 'deg') elif sym == "tz": norm = colors.normalize(-0.1, 0.1) color = cm.jet(norm(data.tz)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] elif sym == "vol": norm = colors.normalize(0, 10) color = cm.jet(norm(data.grainvolume / data.d_grainvolume)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] elif sym == "tth": norm = colors.normalize(0.007, 0.009) color = cm.jet(norm(data.sig_tth / data.grainvolume**.2)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print(min(data.sig_tth / data.grainvolume**.2), max(data.sig_tth / data.grainvolume**.2)) # pl.figure(8) # pl.plot(np.log(data.grainvolume),np.log(data.sig_tth),'.') elif sym == "eta": norm = colors.normalize(0.08, 0.15) color = cm.jet(norm(data.sig_eta / data.grainvolume**.2)) red = color[:, 0] green = color[:, 1] blue = color[:, 2] print(min(data.sig_eta / data.grainvolume**.2), max(data.sig_eta / data.grainvolume**.2)) # pl.figure(8) # pl.plot(np.log(data.grainvolume),np.log(data.sig_eta),'.') else: np.random.seed(0) red = np.random.rand(data.nrows) np.random.seed(1) green = np.random.rand(data.nrows) np.random.seed(2) blue = np.random.rand(data.nrows) data.addcolumn(red, 'red') data.addcolumn(green, 'green') data.addcolumn(blue, 'blue') return (data)
'green': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'blue': ((0.0, 0.0, 0.0), (1.0, 1.0, 1.0)), 'alpha': ((0.0, 1.0, 1.0), (0.5, 0.0, 0.0), (1.0, 1.0, 1.0)) } grayAlpha = LinearSegmentedColormap('gAlpha', cdict) it = 0 for i in range(0, t, 5): #for i in range(t-1,-1,-5): print 'Frame {} of {}'.format(i, t) #cLim = pow(1./(1 + i),0.7) cLim = 0.3 fig = pl.figure() # img = pl.imshow(data[:,:,i],interpolation='nearest') fig.set_size_inches(10, 3) ax = pl.Axes(fig, [0., 0., 1., 1.]) ax.set_axis_off() fig.add_axes(ax) mod = ax.imshow(model) # cbar = fig.colorbar(mod, # ax=ax, # orientation='horizontal', # shrink=0.8, # pad=0.01, # aspect=18.0) # ax.plot([200,600], [250,250], color='c', lw=50, alpha=0.3) # ax.xaxis.tick_top() # ax.xaxis.set_label_position('top') img = ax.imshow(data[:, :, i], interpolation='nearest', cmap=grayAlpha) img.set_clim([-cLim, cLim]) #ax.annotate('$P$',xy=(5,30),fontsize=30, color='white')