def __init__(self): x, y = np.ogrid[-2*np.pi:2*np.pi:256j, -2*np.pi:2*np.pi:256j] self.img_data = np.sin(x)*y #self.img_mask = np.zeros((len(x), len(y[0]), 4), dtype=np.uint8) #self.img_mask[:, :, 3] = 255 self.img_index = np.array(list((np.broadcast(y, x)))) plotdata = ArrayPlotData(img_data=self.img_data, mask_data=self.img_data) plot1 = Plot(plotdata, padding=10) img_plot = plot1.img_plot("img_data", xbounds=(np.min(x), np.max(x)), ybounds=(np.min(y), np.max(y)))[0] self.lasso = LassoSelection(img_plot) img_plot.tools.append(self.lasso) self.ll = LassoOverlay(img_plot, lasso_selection=self.lasso) img_plot.overlays.append(self.ll) self.lasso.on_trait_change(self._selection_changed, 'selection_completed') plot2 = Plot(plotdata, padding=10) plot2.img_plot("mask_data") self.plot = HPlotContainer(plot1, plot2) self.plot1 = plot1 self.plot2 = plot2 self.plotdata = plotdata
def slice_plot( self, anat, coefs, **traits ): p = Plot( self.plot_data, default_origin = 'bottom left' ) p2 = Plot( self.plot_data, default_origin = 'bottom left' ) p.x_axis.visible = False; p2.x_axis.visible = False p.y_axis.visible = False; p2.y_axis.visible = False bounds = self.plot_data.get_data(anat).shape asp = float( bounds[1] ) / float( bounds[0] ) p.img_plot( anat, # xbounds = np.linspace( 0, 1, bounds[1] + 1 ), # ybounds = np.linspace( 0, 1, bounds[0] + 1 ), colormap = chaco_colormaps.gray ) p2.img_plot( coefs, # xbounds = np.linspace( 0, 1, bounds[1] + 1 ), # ybounds = np.linspace( 0, 1, bounds[0] + 1 ), # bgcolor = 'transparent', colormap = self.cmap, interpolation = 'nearest') # p.aspect_ratio = asp; p2.aspect_ratio = asp p.aspect_ratio = asp; p2.aspect_ratio = asp subplot = OverlayPlotContainer( ) subplot.add( p ) subplot.add( p2 ) return subplot
def _stage_map_default(self): # RGBA maps rep_map = array_to_rgba(self.PMap.stage_repr_map, cmap=cm.hot) cov_map = array_to_rgba(self.PMap.stage_coverage_map, cmap=cm.gray) # Data sources and plot object data = ArrayPlotData(fields_x=self.fdata['x'], fields_y=self.fdata['y'], fields_z=self.fdata['peak'], rep=rep_map, cov=cov_map) p = Plot(data) # Plot the field centers p.plot(('fields_x', 'fields_y', 'fields_z'), name='centers', type='cmap_scatter', marker='dot', marker_size=5, color_mapper=copper, line_width=1, fill_alpha=0.6) # Plot the representation and coverage maps p.img_plot('rep', name='rep', xbounds=(0, self.PMap.W), ybounds=(0, self.PMap.H), origin='top left') p.img_plot('cov', name='cov', xbounds=(0, self.PMap.W), ybounds=(0, self.PMap.H), origin='top left') # Start with only the representation map visible p.plots['cov'][0].visible = False p.plots['centers'][0].visible = False # Plot tweaks p.aspect_ratio = 1.0 p.y_axis.title = 'Y (cm)' p.x_axis.title = 'X (cm)' p.x_axis.orientation = 'bottom' p.title = 'Stage Maps' return p
def get_colorbar_plot(self, bounds=(0,1)): """ Create a colorbar plot to be added to a plot-container Arguments: bounds -- (min, max) tuple sets the intensity range for the colormap Returns a Chaco2 Plot object containing the colorbar. """ cb_rgba = array_to_rgba( N.repeat(N.linspace(1, 0, num=1024)[:,N.newaxis], 20, axis=1), cmap=self.get_colormap_object()) if self._cbar_orientation is 'h': cb_rgba = cb_rgba.T[::-1] data = ArrayPlotData(colorbar=cb_rgba) # Create the plot object cb = Plot(data, width=self._cbar_width, resizable=self._cbar_orientation, padding_left=0, padding_top=0) cb.img_plot('colorbar', name='colorbar', xbounds=bounds, ybounds=bounds, origin='top left') # Plot tweaks if self._cbar_orientation is 'v': cb.x_axis.visible = False cb.y_axis.orientation = 'right' else: cb.y_axis.visible = False cb.x_axis.orientation = 'bottom' return cb
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, MAX_FREQ, num=MAX_FREQN) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(MAX_FREQN) obj.spectrum_data.set_data("amplitude", empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 150.0 # spectrum amplitude maximum obj.spectrum_plot.index_axis.title = "Frequency (hz)" obj.spectrum_plot.value_axis.title = "Amplitude" # Time Series plot times = linspace(0.0, float(TIME_NUM_SAMPLES) / SAMPLING_RATE, num=TIME_NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(TIME_NUM_SAMPLES) obj.time_data.set_data("amplitude", empty_amplitude) obj.time_data.set_data("amplitude_1", empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue", alpha=0.5) obj.time_plot.plot(("time", "amplitude_1"), name="Time", color="red", alpha=0.5) obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = "Time (seconds)" obj.time_plot.value_axis.title = "Amplitude" time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -1 time_range.high = 1 # Spectrogram plot spectrogram_data = zeros((MAX_FREQN, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data("imagedata", spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE # max_freq = float(SAMPLING_RATE / 2) max_freq = float(MAX_FREQ) spectrogram_plot.img_plot( "imagedata", name="Spectrogram", xbounds=(0, max_time), ybounds=(0, max_freq), colormap=jet ) range_obj = spectrogram_plot.plots["Spectrogram"][0].value_mapper.range range_obj.high = 2 # brightness of specgram range_obj.low = 0.0 range_obj.edit_traits() spectrogram_plot.title = "Spectrogram" obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
def __init__(self, signal_instance): super(TemplatePicker, self).__init__() try: import cv except: print "OpenCV unavailable. Can't do cross correlation without it. Aborting." return None self.OK_custom = OK_custom_handler() self.sig = signal_instance if not hasattr(self.sig.mapped_parameters, "original_files"): self.sig.data = np.atleast_3d(self.sig.data) self.titles = [self.sig.mapped_parameters.name] else: self.numfiles = len( self.sig.mapped_parameters.original_files.keys()) self.titles = self.sig.mapped_parameters.original_files.keys() tmp_plot_data = ArrayPlotData( imagedata=self.sig.data[self.top:self.top + self.tmp_size, self.left:self.left + self.tmp_size, self.img_idx]) tmp_plot = Plot(tmp_plot_data, default_origin="top left") tmp_plot.img_plot("imagedata", colormap=jet) tmp_plot.aspect_ratio = 1.0 self.tmp_plot = tmp_plot self.tmp_plotdata = tmp_plot_data self.img_plotdata = ArrayPlotData( imagedata=self.sig.data[:, :, self.img_idx]) self.img_container = self._image_plot_container() self.crop_sig = None
def __init__(self, signal_instance): super(TemplatePicker, self).__init__() try: import cv except: print "OpenCV unavailable. Can't do cross correlation without it. Aborting." return None self.OK_custom=OK_custom_handler() self.sig=signal_instance if not hasattr(self.sig.mapped_parameters,"original_files"): self.sig.data=np.atleast_3d(self.sig.data) self.titles=[self.sig.mapped_parameters.name] else: self.numfiles=len(self.sig.mapped_parameters.original_files.keys()) self.titles=self.sig.mapped_parameters.original_files.keys() tmp_plot_data=ArrayPlotData(imagedata=self.sig.data[self.top:self.top+self.tmp_size,self.left:self.left+self.tmp_size,self.img_idx]) tmp_plot=Plot(tmp_plot_data,default_origin="top left") tmp_plot.img_plot("imagedata", colormap=jet) tmp_plot.aspect_ratio=1.0 self.tmp_plot=tmp_plot self.tmp_plotdata=tmp_plot_data self.img_plotdata=ArrayPlotData(imagedata=self.sig.data[:,:,self.img_idx]) self.img_container=self._image_plot_container() self.crop_sig=None
def _create_plot_component(self): self.data = ArrayPlotData() self.data["frequency"] = np.linspace(0., SAMPLING_RATE/2.0, num=NUM_SAMPLES/2) for i in xrange(NUM_LINES): self.data['amplitude%d' % i] = np.zeros(NUM_SAMPLES/2) self.data["time"] = np.linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) self.data['time_amplitude'] = np.zeros(NUM_SAMPLES) self.data['imagedata'] = np.zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) spectrum_plot = Plot(self.data) for i in xrange(NUM_LINES): if i==NUM_LINES-1: linewidth = 2 color = (1,0,0) else: linewidth = 1 c = (NUM_LINES-i-1)/float(NUM_LINES) color = (1, 0.5+c/2, c) spectrum_plot.plot(("frequency", "amplitude%d" % i), name="Spectrum%d" % i, color=color, line_width=linewidth) spectrum_plot.padding_bottom = 20 spectrum_plot.padding_top = 20 spec_range = spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = -90 spec_range.high = 0.0 spectrum_plot.index_axis.title = 'Frequency(Hz)' spectrum_plot.value_axis.title = 'Amplitude(dB)' time_plot = Plot(self.data) time_plot.plot(("time", "time_amplitude"), name="Time", color="blue") time_plot.padding_top = 20 time_plot.padding_bottom = 20 time_plot.index_axis.title = 'Time (seconds)' time_plot.value_axis.title = 'Amplitude' time_range = time_plot.plots.values()[0][0].value_mapper.range time_range.low = -1.5 time_range.high = 1.5 spectrogram_plot = Plot(self.data) spectrogram_time = (0.0, SPECTROGRAM_LENGTH*NUM_SAMPLES/float(SAMPLING_RATE)) spectrogram_freq = (0.0, SAMPLING_RATE/2.0) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=cm.reverse(cm.Blues), ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = -20 range_obj.low = -60 spectrogram_plot.padding_bottom = 20 spectrogram_plot.padding_top = 20 container = VPlotContainer() container.add(time_plot) container.add(spectrum_plot) container.add(spectrogram_plot) return container
def _create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE)/2, num=NUM_SAMPLES/2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES/2) obj.spectrum_data.set_data('amplitude', empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = 'Frequency (hz)' obj.spectrum_plot.value_axis.title = 'Amplitude' # Time Series plot times = linspace(0.0, float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data('amplitude', empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = 'Time (seconds)' obj.time_plot.value_axis.title = 'Amplitude' time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data('imagedata', spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) max_time = float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / SAMPLING_RATE max_freq = float(SAMPLING_RATE / 2) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=(0, max_time), ybounds=(0, max_freq), colormap=jet, ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = 'Spectrogram' obj.spectrogram_plot = spectrogram_plot container = HPlotContainer() container.add(obj.spectrum_plot) container.add(obj.time_plot) container.add(spectrogram_plot) return container
def _create_plot_component(self): self.data = ArrayPlotData() self.data["frequency"] = np.linspace(0., SAMPLING_RATE/2.0, num=NUM_SAMPLES/2) for i in range(NUM_LINES): self.data['amplitude%d' % i] = np.zeros(NUM_SAMPLES/2) self.data["time"] = np.linspace(0., float(NUM_SAMPLES)/SAMPLING_RATE, num=NUM_SAMPLES) self.data['time_amplitude'] = np.zeros(NUM_SAMPLES) self.data['imagedata'] = np.zeros(( NUM_SAMPLES/2, SPECTROGRAM_LENGTH)) spectrum_plot = Plot(self.data) for i in range(NUM_LINES): if i==NUM_LINES-1: linewidth = 2 color = (1,0,0) else: linewidth = 1 c = (NUM_LINES-i-1)/float(NUM_LINES) color = (1, 0.5+c/2, c) spectrum_plot.plot(("frequency", "amplitude%d" % i), name="Spectrum%d" % i, color=color, line_width=linewidth) spectrum_plot.padding_bottom = 20 spectrum_plot.padding_top = 20 spec_range = list(spectrum_plot.plots.values())[0][0].value_mapper.range spec_range.low = -90 spec_range.high = 0.0 spectrum_plot.index_axis.title = 'Frequency(Hz)' spectrum_plot.value_axis.title = 'Amplitude(dB)' time_plot = Plot(self.data) time_plot.plot(("time", "time_amplitude"), name="Time", color="blue") time_plot.padding_top = 20 time_plot.padding_bottom = 20 time_plot.index_axis.title = 'Time (seconds)' time_plot.value_axis.title = 'Amplitude' time_range = list(time_plot.plots.values())[0][0].value_mapper.range time_range.low = -1.5 time_range.high = 1.5 spectrogram_plot = Plot(self.data) spectrogram_time = (0.0, SPECTROGRAM_LENGTH*NUM_SAMPLES/float(SAMPLING_RATE)) spectrogram_freq = (0.0, SAMPLING_RATE/2.0) spectrogram_plot.img_plot('imagedata', name='Spectrogram', xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=cm.reverse(cm.Blues), ) range_obj = spectrogram_plot.plots['Spectrogram'][0].value_mapper.range range_obj.high = -20 range_obj.low = -60 spectrogram_plot.padding_bottom = 20 spectrogram_plot.padding_top = 20 container = VPlotContainer() container.add(time_plot) container.add(spectrum_plot) container.add(spectrogram_plot) return container
def get_plot(self): pixel_sizes = self.data_source.voxel_sizes shape = self.data.shape m = min(pixel_sizes) s = [int(d*sz/m) for d, sz in zip(shape, pixel_sizes)] if 1: # else physical aspect ratio is enabled ss = max(s)/4 s = [max(s,ss) for s in s] plot_sizes = dict (xy = (s[2], s[1]), xz = (s[2], s[0]), zy = (s[0],s[1]), zz=(s[0],s[0])) plots = GridContainer(shape=(2,2), spacing=(3, 3), padding = 50, aspect_ratio=1) pxy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xy'], x_axis=PlotAxis (orientation='top'), ) pxz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['xz'], ) pzy = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zy'], #orientation = 'v', # cannot use 'v' because of img_plot assumes row-major ordering x_axis=PlotAxis(orientation='top'), y_axis=PlotAxis(orientation='right'), ) pzz = Plot(self.plotdata, padding=1, fixed_preferred_size = plot_sizes['zz']) plots.add(pxy, pzy, pxz, pzz) self.plots = dict(xy = pxy.img_plot('xy', colormap=bone)[0], xz = pxz.img_plot('xz', colormap=bone)[0], zy = pzy.img_plot('zy', colormap=bone)[0], zz = pzz.img_plot('zz')[0], xyp = pxy.plot(('z_x', 'z_y'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size = 3, selection_marker='circle')[0], xzp = pxz.plot(('y_x', 'y_z'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size = 3, selection_marker='circle')[0], zyp = pzy.plot(('x_z', 'x_y'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size = 3, selection_marker='circle')[0], ) for p in ['xy', 'xz', 'zy']: self.plots[p].overlays.append(ZoomTool(self.plots[p])) self.plots[p].tools.append(PanTool(self.plots[p], drag_button='right')) imgtool = ImageInspectorTool(self.plots[p]) self.plots[p].tools.append(imgtool) overlay = ImageInspectorOverlay(component=self.plots[p], bgcolor = 'white', image_inspector=imgtool) self.plots['zz'].overlays.append(overlay) self.plots[p+'p'].tools.append (ScatterInspector(self.plots[p+'p'], selection_mode = 'toggle')) self.plots['xyp'].index.on_trait_change (self._xyp_metadata_handler, 'metadata_changed') self.plots['xzp'].index.on_trait_change (self._xzp_metadata_handler, 'metadata_changed') self.plots['zyp'].index.on_trait_change (self._zyp_metadata_handler, 'metadata_changed') plot = HPlotContainer() # todo: add colormaps plot.add(plots) return plot
def _create_window(self): # Create the model #try: # self.model = model = BrainModel() # cmap = bone #except SystemExit: # sys.exit() #except: # print "Unable to load BrainModel, using generated data cube." self.model = model = Model() cmap = jet self._update_model(cmap) datacube = self.colorcube # Create the plot self.plotdata = ArrayPlotData() self._update_images() # Center Plot centerplot = Plot(self.plotdata, padding=0) imgplot = centerplot.img_plot("xy", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0] self._add_plot_tools(imgplot, "xy") self.center = imgplot # Right Plot rightplot = Plot(self.plotdata, width=150, resizable="v", padding=0) rightplot.value_range = centerplot.value_range imgplot = rightplot.img_plot("yz", xbounds=(model.zs[0], model.zs[-1]), ybounds=(model.ys[0], model.ys[-1]), colormap=cmap)[0] self._add_plot_tools(imgplot, "yz") self.right = imgplot # Bottom Plot bottomplot = Plot(self.plotdata, height=150, resizable="h", padding=0) bottomplot.index_range = centerplot.index_range imgplot = bottomplot.img_plot("xz", xbounds=(model.xs[0], model.xs[-1]), ybounds=(model.zs[0], model.zs[-1]), colormap=cmap)[0] self._add_plot_tools(imgplot, "xz") self.bottom = imgplot # Create Container and add all Plots container = GridPlotContainer(padding=20, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(2,2), spacing=(12,12)) container.add(centerplot) container.add(rightplot) container.add(bottomplot) self.container = container return Window(self, -1, component=container)
def __init__(self): super(ImagePlot, self).__init__() x = np.linspace(0, 10, 50) y = np.linspace(0, 5, 50) xgrid, ygrid = np.meshgrid(x, y) z = np.exp(-(xgrid * xgrid + ygrid * ygrid) / 100) plotdata = ArrayPlotData(imagedata=z) plot = Plot(plotdata) plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=jet) self.plot = plot
def __init__(self): super(ImagePlot, self).__init__() x = linspace(0, 10, 50) y = linspace(0, 5, 50) xgrid, ygrid = meshgrid(x, y) z = exp(-(xgrid*xgrid+ygrid*ygrid)/100) plotdata = ArrayPlotData(imagedata = z) plot = Plot(plotdata) plot.img_plot("imagedata", colormap=jet) self.plot = plot
def __init__(self, dims=(128, 10)): super(ImagePlot, self).__init__() z = numpy.zeros(dims) self.plotdata = ArrayPlotData(imagedata=z) plot = Plot(self.plotdata) plot.img_plot("imagedata", xbounds=(0, dims[1]), ybounds=(0, dims[0]), colormap=self._cmap) self.plot = plot self.flag = True
def __init__(self, dims=(128, 10)): super(ImagePlot, self).__init__() z = numpy.zeros(dims) self.plotdata = ArrayPlotData(imagedata=z) plot = Plot(self.plotdata) plot.img_plot("imagedata", xbounds=(0, dims[1]), ybounds=(0, dims[0]), colormap=self._cmap ) self.plot = plot self.flag = True
def _result_changed(self, res): if self.plot is None: plotdata = ArrayPlotData(img = res) self.plotdata = plotdata # Create a Plot and associate it with the PlotData plot = Plot(plotdata) # Create a line plot in the Plot plot.img_plot("img", colormap=jet) #plot.tools.append(BetterSelectingZoom(plot)) self.plot = plot else: self.plotdata.set_data('img', res)
def create_plot_component(obj): # Setup the spectrum plot frequencies = linspace(0.0, float(SAMPLING_RATE) / 2, num=NUM_SAMPLES / 2) obj.spectrum_data = ArrayPlotData(frequency=frequencies) empty_amplitude = zeros(NUM_SAMPLES / 2) obj.spectrum_data.set_data("amplitude", empty_amplitude) obj.spectrum_plot = Plot(obj.spectrum_data) obj.spectrum_plot.plot(("frequency", "amplitude"), name="Spectrum", color="red") obj.spectrum_plot.padding = 50 obj.spectrum_plot.title = "Spectrum" spec_range = obj.spectrum_plot.plots.values()[0][0].value_mapper.range spec_range.low = 0.0 spec_range.high = 5.0 obj.spectrum_plot.index_axis.title = "Frequency (hz)" obj.spectrum_plot.value_axis.title = "Amplitude" # Time Series plot times = linspace(0.0, float(NUM_SAMPLES) / SAMPLING_RATE, num=NUM_SAMPLES) obj.time_data = ArrayPlotData(time=times) empty_amplitude = zeros(NUM_SAMPLES) obj.time_data.set_data("amplitude", empty_amplitude) obj.time_plot = Plot(obj.time_data) obj.time_plot.plot(("time", "amplitude"), name="Time", color="blue") obj.time_plot.padding = 50 obj.time_plot.title = "Time" obj.time_plot.index_axis.title = "Time (seconds)" obj.time_plot.value_axis.title = "Amplitude" time_range = obj.time_plot.plots.values()[0][0].value_mapper.range time_range.low = -0.2 time_range.high = 0.2 # Spectrogram plot spectrogram_data = zeros((NUM_SAMPLES / 2, SPECTROGRAM_LENGTH)) obj.spectrogram_plotdata = ArrayPlotData() obj.spectrogram_plotdata.set_data("imagedata", spectrogram_data) spectrogram_plot = Plot(obj.spectrogram_plotdata) spectrogram_time = linspace( 0.0, float(SPECTROGRAM_LENGTH * NUM_SAMPLES) / float(SAMPLING_RATE), num=SPECTROGRAM_LENGTH ) spectrogram_freq = linspace(0.0, float(SAMPLING_RATE / 2), num=NUM_SAMPLES / 2) spectrogram_plot.img_plot( "imagedata", name="Spectrogram", xbounds=spectrogram_time, ybounds=spectrogram_freq, colormap=jet ) range_obj = spectrogram_plot.plots["Spectrogram"][0].value_mapper.range range_obj.high = 5 range_obj.low = 0.0 spectrogram_plot.title = "Spectrogram" obj.spectrogram_plot = spectrogram_plot return obj.spectrum_plot, obj.time_plot, obj.spectrogram_plot
def _update_img_plot(self, plot_name, image, title): """Update an image plot.""" plotdata = ArrayPlotData(imagedata=image) xbounds = (0, image.shape[1] - 1) ybounds = (0, image.shape[0] - 1) plot = Plot(plotdata) plot.aspect_ratio = float(xbounds[1]) / float(ybounds[1]) plot.img_plot("imagedata", colormap=bone, xbounds=xbounds, ybounds=ybounds) plot.title = title setattr(self, plot_name, plot) getattr(self, plot_name).request_redraw()
def __init__(self): # Create the data and the PlotData object. For a 2D plot, we need to # take the row of X points and Y points and create a grid from them # using meshgrid(). x = linspace(0, 10, 50) y = linspace(0, 5, 50) xgrid, ygrid = meshgrid(x, y) z = exp(-(xgrid*xgrid + ygrid*ygrid) / 100) plotdata = ArrayPlotData(imagedata = z) # Create a Plot and associate it with the PlotData plot = Plot(plotdata) # Create a line plot in the Plot plot.img_plot("imagedata", colormap=jet) self.plot = plot
def __init__(self): # Create plot data. row = linspace(0, 1, 100) self.data = ones([10, 100]) * row plotdata = ArrayPlotData(imagedata=self.data) # Create a Plot and associate it with the PlotData plot = Plot(plotdata) # Create a line plot in the Plot plot.img_plot("imagedata", xbounds=(0, 1), colormap=color_map_name_dict[self.colormap])[0] plot.y_axis.visible = False self.plot = plot self.plot.aspect_ratio = 5
def _image_plot_default(self): plot = Plot(self.image_data, default_origin="top left") #plot.x_axis.orientation = "top" img_plot = plot.img_plot("image_data")[0] plot.bgcolor = "black" return plot
def render_image(self): plot = Plot(self.img_plotdata, default_origin="top left") img = plot.img_plot("imagedata", colormap=gray)[0] plot.title = "%s of %s: " % (self.img_idx + 1, self.numfiles) + self.titles[self.img_idx] plot.aspect_ratio = float(self.sig.data.shape[1]) / float( self.sig.data.shape[0]) #if not self.ShowCC: csr = CursorTool(img, drag_button='left', color='white', line_width=2.0) self.csr = csr csr.current_position = self.left, self.top img.overlays.append(csr) # attach the rectangle tool plot.tools.append(PanTool(plot, drag_button="right")) zoom = ZoomTool(plot, tool_mode="box", always_on=False, aspect_ratio=plot.aspect_ratio) plot.overlays.append(zoom) self.img_plot = plot return plot
def _create_plot_component():# Create a scalar field to colormap xbounds = (-2*pi, 2*pi, 600) ybounds = (-1.5*pi, 1.5*pi, 300) xs = linspace(*xbounds) ys = linspace(*ybounds) x, y = meshgrid(xs,ys) z = sin(x)*y # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create the plot plot = Plot(pd) img_plot = plot.img_plot("imagedata", xbounds = xbounds[:2], ybounds = ybounds[:2], colormap=jet)[0] # Tweak some of the plot properties plot.title = "My First Image Plot" plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) overlay = ImageInspectorOverlay(component=img_plot, image_inspector=imgtool, bgcolor="white", border_visible=True) img_plot.overlays.append(overlay) return plot
def _create_plot_component(): # Create some RGBA image data image = zeros((200,400,4), dtype=uint8) image[:,0:40,0] += 255 # Vertical red stripe image[0:25,:,1] += 255 # Horizontal green stripe; also yellow square image[-80:,-160:,2] += 255 # Blue square image[:,:,3] = 255 # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", image) # Create the plot plot = Plot(pd, default_origin="top left") plot.x_axis.orientation = "top" img_plot = plot.img_plot("imagedata")[0] # Tweak some of the plot properties plot.bgcolor = "white" # Attach some tools to the plot plot.tools.append(PanTool(plot, constrain_key="shift")) plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False)) imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) plot.overlays.append(ImageInspectorOverlay(component=img_plot, image_inspector=imgtool)) return plot
def _create_plot_component(self): pd = self.pd # Create the plot plot = Plot(pd, default_origin="top left",orientation="h") shape = pd.get_data('imagedata').shape plot.aspect_ratio = float(shape[1]) / shape[0] plot.x_axis.orientation = "top" #plot.y_axis.orientation = "top" #img_plot = plot.img_plot("imagedata",colormap = jet)[0] img_plot = plot.img_plot("imagedata",name = 'image', colormap = jet)[0] # Tweak some of the plot properties #plot.bgcolor = "white" plot.bgcolor = bg_color # Attach some tools to the plot plot.tools.append(PanTool(plot,constrain_key="shift", drag_button = 'right')) printer = DataPrinter(component=plot, process = self.process_selection) plot.tools.append(printer) plot.overlays.append(ZoomTool(component=plot, tool_mode="box", always_on=False)) #plot.title = 'Default image' imgtool = ImageInspectorTool(img_plot) img_plot.tools.append(imgtool) plot.overlays.append(ImageInspectorOverlay(component=img_plot, image_inspector=imgtool)) return plot
def _create_plot_component():# Create a scalar field to colormap xbounds = (-2*pi, 2*pi, 600) ybounds = (-1.5*pi, 1.5*pi, 300) xs = linspace(*xbounds) ys = linspace(*ybounds) x, y = meshgrid(xs,ys) z = sin(x)*y # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create the plot plot = Plot(pd) img_plot = plot.img_plot("imagedata", xbounds=xbounds[:2], ybounds=ybounds[:2], colormap=jet)[0] # Tweak some of the plot properties plot.title = "Image Plot with Lasso" plot.padding = 50 lasso_selection = LassoSelection(component=img_plot) lasso_selection.on_trait_change(lasso_updated, "disjoint_selections") lasso_overlay = LassoOverlay(lasso_selection = lasso_selection, component=img_plot) img_plot.tools.append(lasso_selection) img_plot.overlays.append(lasso_overlay) return plot
def _create_plot_component(): # Create a scalar field to colormap xs = linspace(0, 10, 600) ys = linspace(0, 5, 600) x, y = meshgrid(xs, ys) z = exp(-(x**2 + y**2) / 100) # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create the plot plot = Plot(pd) img_plot = plot.img_plot("imagedata", xbounds=(0, 10), ybounds=(0, 5), colormap=jet)[0] # Tweak some of the plot properties plot.title = "My First Image Plot" plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False) img_plot.overlays.append(zoom) return plot
def create_plots(self): """Create a simple 2D image plot of the parameter sweep """ # Figure is horizontal container for main plot + colorbar self.figure = \ container = HPlotContainer(fill_padding=True, padding=25, bgcolor='linen') # Convert old data sets to the new generalized style if 'J0_bounds' in self.results: self.results['x_bounds'] = self.results['J0_bounds'] self.results['x_param'] = 'J0' if 'lambda_bounds' in self.results: self.results['y_bounds'] = self.results['lambda_bounds'] self.results['y_param'] = 'phi_lambda' # Data and bounds for main plot raw_data = self.results[self.display_data] data = ArrayPlotData(image=self.get_rgba_data(raw_data), raw=raw_data, x=self.results['samples'][:,0], y=self.results['samples'][:,1]) x_range = tuple(self.results['x_bounds']) y_range = tuple(self.results['y_bounds']) bounds = dict(xbounds=x_range, ybounds=y_range) # Create main plot p = Plot(data) p.img_plot('image', name='sweep', origin='top left', **bounds) p.contour_plot('raw', name='contour', type='line', origin='top left', **bounds) p.plot(('x', 'y'), name='samples', type='scatter', marker='circle', color=(0.5, 0.6, 0.7, 0.4), marker_size=2) # Tweak main plot p.title = snake2title(self.display_data) p.x_axis.orientation = 'bottom' p.x_axis.title = snake2title(self.results['x_param']) p.y_axis.title = snake2title(self.results['y_param']) p.plots['samples'][0].visible = self.show_sample_points # Add main plot and colorbar to figure container.add(p) container.add( self.get_colorbar_plot(bounds=(raw_data.min(), raw_data.max()))) # Set radio buttons self.unit_data = self.field_data = 'none'
def _unit_map_default(self): # Set the initial unit map data = ArrayPlotData(unit_map=self._get_unit_map_data()) p = Plot(data) # Plot the map p.img_plot('unit_map', name='unit', xbounds=(0, self.PMap.W), ybounds=(0, self.PMap.H), origin='top left') # Plot tweaks p.aspect_ratio = 1.0 p.y_axis.title = 'Y (cm)' p.x_axis.title = 'X (cm)' p.x_axis.orientation = 'bottom' p.title = 'Single Unit Maps' return p
def _vr_image_plot_default(self): plot = Plot(self.vr_image_data, default_origin="top left", size=(512,512)) plot.aspect_ratio = 1.0 #plot.x_axis.orientation = "top" img_plot = plot.img_plot("vr_image_data")[0] plot.bgcolor = "black" return plot
def __init__(self): super(Probe, self).__init__() x = linspace(0, self.N, self.N/self.d) y = linspace(0, self.N, self.N/self.d) xgrid, ygrid = meshgrid(x[1:], y[1:]) z = exp(-(xgrid*xgrid+ygrid*ygrid)/10000) plotdata = ArrayPlotData(imagedata = z) plot = Plot(plotdata) self.renderer=plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=bone) #self.renderer = plot.plot(("x", "y"), type="scatter", color="blue")[0] self.plot = plot
def __init__(self): super(LinePlot, self).__init__() self.size_x = 800 self.size_y = 600 arr = numpy.zeros(dtype=numpy.uint32, shape=(self.size_x, self.size_y)) rslt = mandelbrot( arr, self.x_lbound, self.x_ubound, self.y_lbound, self.y_ubound, 1000) self.plotdata = ArrayPlotData(imagedata=self._get_image()) plot = Plot(self.plotdata) plot.img_plot("imagedata", colormap=jet) self.plot = plot
def __init__(self): super(Probe, self).__init__() x = linspace(0, self.N, self.N / self.d) y = linspace(0, self.N, self.N / self.d) xgrid, ygrid = meshgrid(x[1:], y[1:]) z = exp(-(xgrid * xgrid + ygrid * ygrid) / 10000) plotdata = ArrayPlotData(imagedata=z) plot = Plot(plotdata) self.renderer = plot.img_plot("imagedata", xbounds=x, ybounds=y, colormap=bone) #self.renderer = plot.plot(("x", "y"), type="scatter", color="blue")[0] self.plot = plot
def _plot_default(self): pd = ArrayPlotData() plot = Plot(pd, padding = 0) self.fid._data = self.panner.buffer pd.set_data("imagedata", self.fid) img_plot = plot.img_plot("imagedata", colormap=algae, interpolation='nearest', xbounds=(0.0, 1.0), ybounds=(0.0, 1.0))[0] self.fid.data_range = plot.range2d self.helper.index = img_plot.index self.img_plot = img_plot return plot
def rate_plot( self, rates, **traits ): rp = Plot( self.rate_data, default_origin = 'bottom left' ) rp.x_axis.visible = False rp.y_axis.visible = False # bounds = self.rate_data.get_data( rates ).shape rp.img_plot( rates, # xbounds = np.linspace( 0, 1, bounds[1] + 1 ), # ybounds = np.linspace( 0, 1, bounds[0] + 1 ), colormap = chaco_colormaps.jet, interpolation = 'nearest') rp.contour_plot( rates, type = 'line', # xbounds = np.linspace( 0, 1, bounds[1] + 1 ), # ybounds = np.linspace( 0, 1, bounds[0] + 1 ), bgcolor = 'black', levels = 15, styles = 'solid', widths = list( np.linspace( 4.0, 0.1, 15 )), colors = gmt_drywet ) rp.aspect_ratio = 1 # zoom = ZoomTool( rp, tool_mode = 'box', always_on = False ) # rp.overlays.append(zoom) # rp.tools.append( PanTool( rp, constrain_key = 'shift' ) ) subplot = OverlayPlotContainer( ) subplot.add( rp ) return subplot
def _plot_default(self): pd = ArrayPlotData() plot = Plot(pd, padding=0) self.fid._data = self.panner.buffer pd.set_data("imagedata", self.fid) img_plot = plot.img_plot("imagedata", colormap=algae, interpolation='nearest', xbounds=(0.0, 1.0), ybounds=(0.0, 1.0))[0] self.fid.data_range = plot.range2d self.helper.index = img_plot.index self.img_plot = img_plot return plot
class FloodFillDemo(HasTraits): lo_diff = Array(np.float, (1,4)) hi_diff = Array(np.float, (1,4)) plot = Instance(Plot) point = Tuple((0,0)) option = Trait(u"以邻点为标准-4联通", Options) view = View( VGroup( VGroup( Item("lo_diff", label=u"负方向范围"), Item("hi_diff", label=u"正方向范围"), Item("option", label=u"算法标志") ), Item("plot", editor=ComponentEditor(), show_label=False), ), title = u"FloodFill Demo控制面板", width = 500, height = 450, resizable = True ) def __init__(self, *args, **kwargs): self.lo_diff.fill(5) self.hi_diff.fill(5) self.img = cv.imread("lena.jpg") self.data = ArrayPlotData(img = self.img[:,:,::-1]) w = self.img.size().width h = self.img.size().height self.plot = Plot(self.data, padding=10, aspect_ratio=float(w)/h) self.plot.x_axis.visible = False self.plot.y_axis.visible = False self.imgplot = self.plot.img_plot("img", origin="top left")[0] self.imgplot.interpolation = "nearest" self.imgplot.overlays.append(PointPicker(application=self, component=self.imgplot)) self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option") def redraw(self): img=self.img.clone() cv.floodFill(img, cv.Point(*self.point), cv.Scalar(255, 0, 0, 255), loDiff=cv.asScalar(self.lo_diff[0]), upDiff=cv.asScalar(self.hi_diff[0]), flags = self.option_) self.data["img"] = img[:,:,::-1]
class FloodFillDemo(HasTraits): lo_diff = Array(np.float, (1, 4)) hi_diff = Array(np.float, (1, 4)) plot = Instance(Plot) point = Tuple((0, 0)) option = Trait(u"以邻点为标准-4联通", Options) view = View(VGroup( VGroup(Item("lo_diff", label=u"负方向范围"), Item("hi_diff", label=u"正方向范围"), Item("option", label=u"算法标志")), Item("plot", editor=ComponentEditor(), show_label=False), ), title=u"FloodFill Demo控制面板", width=500, height=450, resizable=True) def __init__(self, *args, **kwargs): self.lo_diff.fill(5) self.hi_diff.fill(5) self.img = cv.imread("lena.jpg") self.data = ArrayPlotData(img=self.img[:, :, ::-1]) w = self.img.size().width h = self.img.size().height self.plot = Plot(self.data, padding=10, aspect_ratio=float(w) / h) self.plot.x_axis.visible = False self.plot.y_axis.visible = False self.imgplot = self.plot.img_plot("img", origin="top left")[0] self.imgplot.interpolation = "nearest" self.imgplot.overlays.append( PointPicker(application=self, component=self.imgplot)) self.on_trait_change(self.redraw, "point,lo_diff,hi_diff,option") def redraw(self): img = self.img.clone() cv.floodFill(img, cv.Point(*self.point), cv.Scalar(255, 0, 0, 255), loDiff=cv.asScalar(self.lo_diff[0]), upDiff=cv.asScalar(self.hi_diff[0]), flags=self.option_) self.data["img"] = img[:, :, ::-1]
def render_image(self): plot = Plot(self.img_plotdata,default_origin="top left") img=plot.img_plot("imagedata", colormap=gray)[0] plot.title="%s of %s: "%(self.img_idx+1,self.numfiles)+self.titles[self.img_idx] plot.aspect_ratio=float(self.sig.data.shape[1])/float(self.sig.data.shape[0]) #if not self.ShowCC: csr = CursorTool(img, drag_button='left', color='white', line_width=2.0) self.csr=csr csr.current_position=self.left, self.top img.overlays.append(csr) # attach the rectangle tool plot.tools.append(PanTool(plot,drag_button="right")) zoom = ZoomTool(plot, tool_mode="box", always_on=False, aspect_ratio=plot.aspect_ratio) plot.overlays.append(zoom) self.img_plot=plot return plot
def get_plot(self): pixel_sizes = self.data_source.pixel_sizes shape = self.data.shape[1:] m = min(pixel_sizes) s = [int(d*sz/m) for d, sz in zip(shape, pixel_sizes)] plot_sizes = dict (xy = (s[1], s[0])) plot = Plot(self.plotdata, padding=30, fixed_preferred_size = plot_sizes['xy'], ) image = plot.img_plot('xy', colormap=bone)[0] image.overlays.append(ZoomTool(image)) image.tools.append(PanTool(image, drag_button='right')) imgtool = ImageInspectorTool(image) image.tools.append(imgtool) overlay = ImageInspectorOverlay(component=image, bgcolor = 'white', image_inspector=imgtool) image.overlays.append(overlay) self.image = image self.plots = dict(xy = image) return plot
def _plot_default(self): self._pd = ArrayPlotData() self._pd.set_data("imagedata", self._image) plot = Plot(self._pd, default_origin="top left") plot.x_axis.orientation = "top" img_plot = plot.img_plot("imagedata")[0] plot.bgcolor = "white" # Tweak some of the plot properties plot.title = "Click to add points, press Enter to clear selection" plot.padding = 50 plot.line_width = 1 # Attach some tools to the plot pan = PanTool(plot, drag_button="right", constrain_key="shift") plot.tools.append(pan) zoom = ZoomTool(component=plot, tool_mode="box", always_on=False) plot.overlays.append(zoom) return plot
def get_plot(self): pixel_sizes = self.data_source.pixel_sizes shape = self.data.shape[1:] m = min(pixel_sizes) s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)] plot_sizes = dict(xy=(s[1], s[0])) plot = Plot( self.plotdata, padding=30, fixed_preferred_size=plot_sizes['xy'], ) image = plot.img_plot('xy', colormap=bone)[0] image.overlays.append(ZoomTool(image)) image.tools.append(PanTool(image, drag_button='right')) imgtool = ImageInspectorTool(image) image.tools.append(imgtool) overlay = ImageInspectorOverlay(component=image, bgcolor='white', image_inspector=imgtool) image.overlays.append(overlay) self.image = image self.plots = dict(xy=image) return plot
def _create_plot_component(): # Create a scalar field to colormap xs = linspace(0, 10, 600) ys = linspace(0, 5, 600) x, y = meshgrid(xs, ys) z = exp(-(x ** 2 + y ** 2) / 100) # Create a plot data obect and give it this data pd = ArrayPlotData() pd.set_data("imagedata", z) # Create the plot plot = Plot(pd) img_plot = plot.img_plot("imagedata", xbounds=(0, 10), ybounds=(0, 5), colormap=jet)[0] # Tweak some of the plot properties plot.title = "My First Image Plot" plot.padding = 50 # Attach some tools to the plot plot.tools.append(PanTool(plot)) zoom = ZoomTool(component=img_plot, tool_mode="box", always_on=False) img_plot.overlays.append(zoom) return plot
def get_plot(self): pixel_sizes = self.data_source.voxel_sizes shape = self.data.shape m = min(pixel_sizes) s = [int(d * sz / m) for d, sz in zip(shape, pixel_sizes)] if 1: # else physical aspect ratio is enabled ss = max(s) / 4 s = [max(s, ss) for s in s] plot_sizes = dict(xy=(s[2], s[1]), xz=(s[2], s[0]), zy=(s[0], s[1]), zz=(s[0], s[0])) plots = GridContainer(shape=(2, 2), spacing=(3, 3), padding=50, aspect_ratio=1) pxy = Plot( self.plotdata, padding=1, fixed_preferred_size=plot_sizes['xy'], x_axis=PlotAxis(orientation='top'), ) pxz = Plot( self.plotdata, padding=1, fixed_preferred_size=plot_sizes['xz'], ) pzy = Plot( self.plotdata, padding=1, fixed_preferred_size=plot_sizes['zy'], #orientation = 'v', # cannot use 'v' because of img_plot assumes row-major ordering x_axis=PlotAxis(orientation='top'), y_axis=PlotAxis(orientation='right'), ) pzz = Plot(self.plotdata, padding=1, fixed_preferred_size=plot_sizes['zz']) plots.add(pxy, pzy, pxz, pzz) self.plots = dict( xy=pxy.img_plot('xy', colormap=bone)[0], xz=pxz.img_plot('xz', colormap=bone)[0], zy=pzy.img_plot('zy', colormap=bone)[0], zz=pzz.img_plot('zz')[0], xyp=pxy.plot(('z_x', 'z_y'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size=3, selection_marker='circle')[0], xzp=pxz.plot(('y_x', 'y_z'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size=3, selection_marker='circle')[0], zyp=pzy.plot(('x_z', 'x_y'), type='scatter', color='orange', marker='circle', marker_size=3, selection_marker_size=3, selection_marker='circle')[0], ) for p in ['xy', 'xz', 'zy']: self.plots[p].overlays.append(ZoomTool(self.plots[p])) self.plots[p].tools.append( PanTool(self.plots[p], drag_button='right')) imgtool = ImageInspectorTool(self.plots[p]) self.plots[p].tools.append(imgtool) overlay = ImageInspectorOverlay(component=self.plots[p], bgcolor='white', image_inspector=imgtool) self.plots['zz'].overlays.append(overlay) self.plots[p + 'p'].tools.append( ScatterInspector(self.plots[p + 'p'], selection_mode='toggle')) self.plots['xyp'].index.on_trait_change(self._xyp_metadata_handler, 'metadata_changed') self.plots['xzp'].index.on_trait_change(self._xzp_metadata_handler, 'metadata_changed') self.plots['zyp'].index.on_trait_change(self._zyp_metadata_handler, 'metadata_changed') plot = HPlotContainer() # todo: add colormaps plot.add(plots) return plot
class MandelbrotDemo(HasTraits): plot = Instance(Plot) imgplot = Any data = Instance(ArrayPlotData) cx = Float(0) cy = Float(0) d = Float(1.5) width = Property(depends_on="imgplot.x2") height = Property(depends_on="imgplot.y2") color_maps = List current_map = Str("Blues") reverse_map = Bool(True) position = Property(depends_on="cx,cy,d") def _get_width(self): return self.imgplot.x2 def _get_height(self): return self.imgplot.y2 def _color_maps_default(self): return [x.__name__ for x in cmaps.color_map_functions] def default_traits_view(self): view = View( VGroup( HGroup( Item("current_map", label=u"颜色映射", editor=EnumEditor(name="object.color_maps")), Item("reverse_map", label=u"反转颜色"), Item("position", label=u"位置", style="readonly"), ), Item("plot", show_label=False, editor=ComponentEditor()), ), resizable = True, width = 550, height = 300, title = u"Mandelbrot观察器" ) return view def _get_position(self): return "X:%f Y:%f d:%f" % (self.cx, self.cy, self.d) @on_trait_change("reverse_map,current_map") def change_color_map(self): try: cmap_func = getattr(cmaps, self.current_map) if self.reverse_map: cmap_func = reverse(cmap_func) self.imgplot.color_mapper = cmap_func(DataRange1D(self.imgplot.value)) self.plot.request_redraw() except: print "Cannot set color map:%s" % self.current_map def __init__(self, **traits): super(MandelbrotDemo, self).__init__(**traits) self.data = ArrayPlotData(image=np.zeros((1, 1))) self.plot = Plot(self.data, padding=0) imgplot = self.plot.img_plot("image", colormap=reverse(Blues), interpolation="bilinear")[0] imgplot.tools.append( MandelbrotController(imgplot, application=self) ) self.imgplot = imgplot self.plot.x_axis.visible = False self.plot.y_axis.visible = False @on_trait_change("imgplot.bounds") def update_plot(self): arr = self.data["image"] if arr.shape[0] != self.height or arr.shape[1] != self.width: arr = np.empty((self.height, self.width)) weave_mandelbrot(self.cx, self.cy, self.d, arr) self.data["image"] = arr
class MatrixViewer(HasTraits): tplot = Instance(Plot) plot = Instance(Component) custtool = Instance(CustomTool) colorbar = Instance(ColorBar) edge_para = Any data_name = Enum("a", "b") fro = Int to = Int data = None val = Float traits_view = View(Group(Item('plot', editor=ComponentEditor(size=(800, 600)), show_label=False), HGroup( Item('fro', label="From", style='readonly', springy=True), Item('to', label="To", style='readonly', springy=True), Item('val', label="Value", style='readonly', springy=True), ), orientation="vertical"), Item('data_name', label="Image data"), handler=CustomHandler(), resizable=True, title="Matrix Viewer") def __init__(self, data, **traits): """ Data is a nxn numpy array """ super(HasTraits, self).__init__(**traits) self.data_name = data.keys()[0] self.data = data self.plot = self._create_plot_component() # set trait notification on customtool self.custtool.on_trait_change(self._update_fields, "xval") self.custtool.on_trait_change(self._update_fields, "yval") def _data_name_changed(self, old, new): self.pd.set_data("imagedata", self.data[self.data_name]) self.my_plot.set_value_selection((0, 2)) def _update_fields(self): from numpy import trunc # map mouse location to array index frotmp = int(trunc(self.custtool.yval)) totmp = int(trunc(self.custtool.xval)) # check if within range sh = self.data[self.data_name].shape # assume matrix whose shape is (# of rows, # of columns) if frotmp >= 0 and frotmp < sh[0] and totmp >= 0 and totmp < sh[1]: self.fro = frotmp self.to = totmp self.val = self.data[self.data_name][self.fro, self.to] def _create_plot_component(self): # Create a plot data object and give it this data self.pd = ArrayPlotData() self.pd.set_data("imagedata", self.data[self.data_name]) # Create the plot self.tplot = Plot(self.pd, default_origin="top left") self.tplot.x_axis.orientation = "top" self.tplot.img_plot( "imagedata", name="my_plot", #xbounds=(0,10), #ybounds=(0,10), colormap=jet) # Tweak some of the plot properties self.tplot.title = "Matrix" self.tplot.padding = 50 # Right now, some of the tools are a little invasive, and we need the # actual CMapImage object to give to them self.my_plot = self.tplot.plots["my_plot"][0] # Attach some tools to the plot self.tplot.tools.append(PanTool(self.tplot)) zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False) self.tplot.overlays.append(zoom) # my custom tool to get the connection information self.custtool = CustomTool(self.tplot) self.tplot.tools.append(self.custtool) # Create the colorbar, handing in the appropriate range and colormap colormap = self.my_plot.color_mapper self.colorbar = ColorBar( index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=self.my_plot, orientation='v', resizable='v', width=30, padding=20) self.colorbar.padding_top = self.tplot.padding_top self.colorbar.padding_bottom = self.tplot.padding_bottom # create a range selection for the colorbar self.range_selection = RangeSelection(component=self.colorbar) self.colorbar.tools.append(self.range_selection) self.colorbar.overlays.append( RangeSelectionOverlay(component=self.colorbar, border_color="white", alpha=0.8, fill_color="lightgray")) # we also want to the range selection to inform the cmap plot of # the selection, so set that up as well self.range_selection.listeners.append(self.my_plot) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.tplot) container.add(self.colorbar) container.bgcolor = "white" return container
def make_image_plot(self, img_data): p = Plot(self.data, aspect_ratio=1) p.x_axis.visible = False p.y_axis.visible = False p.padding = [1, 1, 1, 1] return p, p.img_plot(img_data, colormap=gray, origin="top left")[0]
class ConnectionMatrixViewer(HasTraits): tplot = Instance(Plot) plot = Instance(Component) custtool = Instance(CustomTool) colorbar = Instance(ColorBar) fro = Any to = Any data = None val = Float nodelabels = Any traits_view = View( Group(Item('plot', editor=ComponentEditor(size=(800, 600)), show_label=False), HGroup( Item('fro', label="From", style='readonly', springy=True), Item('to', label="To", style='readonly', springy=True), Item('val', label="Value", style='readonly', springy=True), ), orientation="vertical"), Item('data_name', label="Edge key"), # handler=CustomHandler(), resizable=True, title="Connection Matrix Viewer") def __init__(self, nodelabels, matdict, **traits): """ Starts a matrix inspector Parameters ---------- nodelables : list List of strings of labels for the rows of the matrix matdict : dictionary Keys are the edge type and values are NxN Numpy arrays """ super(HasTraits, self).__init__(**traits) self.add_trait('data_name', Enum(matdict.keys())) self.data_name = matdict.keys()[0] self.data = matdict self.nodelables = nodelabels self.plot = self._create_plot_component() # set trait notification on customtool self.custtool.on_trait_change(self._update_fields, "xval") self.custtool.on_trait_change(self._update_fields, "yval") def _data_name_changed(self, old, new): self.pd.set_data("imagedata", self.data[self.data_name]) #self.my_plot.set_value_selection((0, 2)) self.tplot.title = "Connection Matrix for %s" % self.data_name def _update_fields(self): # map mouse location to array index frotmp = int(round(self.custtool.yval) - 1) totmp = int(round(self.custtool.xval) - 1) # check if within range sh = self.data[self.data_name].shape # assume matrix whose shape is (# of rows, # of columns) if frotmp >= 0 and frotmp < sh[0] and totmp >= 0 and totmp < sh[1]: row = " (index: %i" % (frotmp + 1) + ")" col = " (index: %i" % (totmp + 1) + ")" self.fro = " " + str(self.nodelables[frotmp]) + row self.to = " " + str(self.nodelables[totmp]) + col self.val = self.data[self.data_name][frotmp, totmp] def _create_plot_component(self): # Create a plot data object and give it this data self.pd = ArrayPlotData() self.pd.set_data("imagedata", self.data[self.data_name]) # find dimensions xdim = self.data[self.data_name].shape[1] ydim = self.data[self.data_name].shape[0] # Create the plot self.tplot = Plot(self.pd, default_origin="top left") self.tplot.x_axis.orientation = "top" self.tplot.img_plot("imagedata", name="my_plot", xbounds=(0.5, xdim + 0.5), ybounds=(0.5, ydim + 0.5), colormap=jet) # Tweak some of the plot properties self.tplot.title = "Connection Matrix for %s" % self.data_name self.tplot.padding = 80 # Right now, some of the tools are a little invasive, and we need the # actual CMapImage object to give to them self.my_plot = self.tplot.plots["my_plot"][0] # Attach some tools to the plot self.tplot.tools.append(PanTool(self.tplot)) zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False) self.tplot.overlays.append(zoom) # my custom tool to get the connection information self.custtool = CustomTool(self.tplot) self.tplot.tools.append(self.custtool) # Create the colorbar, handing in the appropriate range and colormap colormap = self.my_plot.color_mapper self.colorbar = ColorBar( index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=self.my_plot, orientation='v', resizable='v', width=30, padding=20) self.colorbar.padding_top = self.tplot.padding_top self.colorbar.padding_bottom = self.tplot.padding_bottom # create a range selection for the colorbar self.range_selection = RangeSelection(component=self.colorbar) self.colorbar.tools.append(self.range_selection) self.colorbar.overlays.append( RangeSelectionOverlay(component=self.colorbar, border_color="white", alpha=0.8, fill_color="lightgray")) # we also want to the range selection to inform the cmap plot of # the selection, so set that up as well self.range_selection.listeners.append(self.my_plot) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.tplot) container.add(self.colorbar) container.bgcolor = "white" return container
class ImagePlot(HasTraits): #plot = Instance(Plot) # traits_view = View( # Group(Item('container', # editor=ComponentEditor(), # show_label=False)), # width=500, height=500, # buttons=NoButtons, # resizable=True, title="QTLab Analysis Plot") # Item('plot', editor=ComponentEditor(), show_label=False), # width=500, height=500, resizable=True, title="QTLab Analysis Plot") # def __init__(self, title, xtitle, x, ytitle, y, z): # super(ImagePlot, self).__init__() # self.create_plot(title, xtitle, x, ytitle, y, z) def _create_window(self, title, xtitle, x, ytitle, y, z): ''' - Left-drag pans the plot. - Mousewheel up and down zooms the plot in and out. - Pressing "z" brings up the Zoom Box, and you can click-drag a rectangular region to zoom. If you use a sequence of zoom boxes, pressing alt-left-arrow and alt-right-arrow moves you forwards and backwards through the "zoom history". ''' self._plotname = title # Create window self.data = ArrayPlotData() self.plot = Plot(self.data) self.update_plot(x, y, z) self.plot.title = title self.plot.x_axis.title = xtitle self.plot.y_axis.title = ytitle cmap_renderer = self.plot.plots[self._plotname][0] # Create colorbar self._create_colorbar() self._colorbar.plot = cmap_renderer self._colorbar.padding_top = self.plot.padding_top self._colorbar.padding_bottom = self.plot.padding_bottom # Add some tools self.plot.tools.append(PanTool(self.plot, constrain_key="shift")) self.plot.overlays.append( ZoomTool(component=self.plot, tool_mode="box", always_on=False)) # selection = ColormappedSelectionOverlay(cmap_renderer, fade_alpha=0.35, selection_type="mask") # cmap_renderer.overlays.append(selection) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.plot) container.add(self._colorbar) self.container = container # Return a window containing our plot container return Window(self, -1, component=container) def update_plot(self, x, y, z): self.data.set_data('x', x) self.data.set_data('y', y) self.data.set_data('z', z) if self.plot.plots.has_key(self._plotname): self.plot.delplot(self._plotname) # determine correct bounds xstep = (x.max() - x.min()) / (len(x) - 1) ystep = (y.max() - y.min()) / (len(y) - 1) x0, x1 = x.min() - xstep / 2, x.max() + xstep / 2 y0, y1 = y.min() - ystep / 2, y.max() + ystep / 2 self.plot.img_plot('z', name=self._plotname, xbounds=(x0, x1), ybounds=(y0, y1), colormap=jet) # self.plot.plot(("x", "y", "z"), # type = "img_plot", # name = self._plotname, # color_mapper = jet, # marker = "square", # fill_alpha = 0.5, # marker_size = 6, # outline_color = "black", # border_visible = True, # bgcolor = "white") def _create_colorbar(self): cmap = self.plot.color_mapper self._colorbar = ColorBar(index_mapper=LinearMapper(range=cmap.range), color_mapper=cmap, orientation='v', resizable='v', width=30, padding=30)
class InPaintDemo(HasTraits): plot = Instance(Plot) painter = Instance(CirclePainter) r = Range(2.0, 20.0, 10.0) # inpaint的半径参数 method = Enum("INPAINT_NS", "INPAINT_TELEA") # inpaint的算法 show_mask = Bool(False) # 是否显示选区 clear_mask = Button("清除选区") apply = Button("保存结果") view = View(VGroup( VGroup( Item("object.painter.r", label="画笔半径"), Item("r", label="inpaint半径"), HGroup( Item("method", label="inpaint算法"), Item("show_mask", label="显示选区"), Item("clear_mask", show_label=False), Item("apply", show_label=False), )), Item("plot", editor=ComponentEditor(), show_label=False), ), title="inpaint Demo控制面板", width=500, height=450, resizable=True) def __init__(self, *args, **kwargs): super(InPaintDemo, self).__init__(*args, **kwargs) self.img = cv.imread("stuff.jpg") # 原始图像 self.img2 = self.img.clone() # inpaint效果预览图像 self.mask = cv.Mat(self.img.size(), cv.CV_8UC1) # 储存选区的图像 self.mask[:] = 0 self.data = ArrayPlotData(img=self.img[:, :, ::-1]) self.plot = Plot(self.data, padding=10, aspect_ratio=float(self.img.size().width) / self.img.size().height) self.plot.x_axis.visible = False self.plot.y_axis.visible = False imgplot = self.plot.img_plot("img", origin="top left")[0] self.painter = CirclePainter(component=imgplot) imgplot.overlays.append(self.painter) @on_trait_change("r,method") def inpaint(self): cv.inpaint(self.img, self.mask, self.img2, self.r, getattr(cv, self.method)) self.draw() @on_trait_change("painter:updated") def painter_updated(self): for _, _, x, y in self.painter.track: # 在储存选区的mask上绘制圆形 cv.circle(self.mask, cv.Point(int(x), int(y)), int(self.painter.r), cv.Scalar(255, 255, 255, 255), thickness=-1) # 宽度为负表示填充圆形 self.inpaint() self.painter.track = [] self.painter.request_redraw() def _clear_mask_fired(self): self.mask[:] = 0 self.inpaint() def _apply_fired(self): """保存inpaint的处理结果,并清除选区""" self.img[:] = self.img2[:] self._clear_mask_fired() @on_trait_change("show_mask") def draw(self): if self.show_mask: data = self.img[:, :, ::-1].copy() data[self.mask[:] > 0] = 255 self.data["img"] = data else: self.data["img"] = self.img2[:, :, ::-1]
def _create_plot_window(self): # Create the model min_value = 350 max_value = self.max_data image_value_range = DataRange1D(low=min_value, high=max_value) self.cmap = jet(range=image_value_range) self._update_model() datacube = self.colorcube # Create the plot self.plotdata = ArrayPlotData() self.plotdataVoxel = ArrayPlotData() self.plotdataSlices = ArrayPlotData() self.plotdataVoxelFFT = ArrayPlotData() self.plotdataPC = ArrayPlotData() self._update_images() # Top Left plot centerplot = Plot(self.plotdata, resizable='hv', padding=20, title="Slice_X") imgplot = centerplot.img_plot("yz", xbounds=None, ybounds=None, colormap=self.cmap)[0] centerplot.x_axis.title = "Y" centerplot.y_axis.title = "Z" self._add_plot_tools(imgplot, "yz") self.cursorYZ = CursorTool(imgplot, drag_button='left', color='white') self.cursorYZ.current_position = self.slice_y, self.slice_z imgplot.overlays.append(self.cursorYZ) self.center = imgplot # Top Right Plot rightplot = Plot(self.plotdata, resizable='hv', padding=20, title="Slice_Y") rightplot.x_axis.title = "X" rightplot.y_axis.title = "Z" imgplot = rightplot.img_plot("xz", xbounds=None, ybounds=None, colormap=self.cmap)[0] self._add_plot_tools(imgplot, "xz") self.cursorXZ = CursorTool(imgplot, drag_button='left', color='white') self.cursorXZ.current_position = self.slice_x, self.slice_z imgplot.overlays.append(self.cursorXZ) self.right = imgplot # Bottom LeftPlot bottomplot = Plot(self.plotdata, resizable='hv', padding=20, title="Slice_Z") bottomplot.x_axis.title = "Y" bottomplot.y_axis.title = "X" imgplot = bottomplot.img_plot("xy", xbounds=None, ybounds=None, colormap=self.cmap)[0] """bottomplot.contour_plot("xy", type="poly", xbounds=None, ybounds=None)[0]""" self._add_plot_tools(imgplot, "xy") self.cursorXY = CursorTool(imgplot, drag_button='left', color='white') self.cursorXY.current_position = self.slice_y, self.slice_x imgplot.overlays.append(self.cursorXY) self.bottom = imgplot """ # Create a colorbar cbar_index_mapper = LinearMapper(range=image_value_range) self.colorbar = ColorBar(index_mapper=cbar_index_mapper, plot=centerplot, padding_top=centerplot.padding_top, padding_bottom=centerplot.padding_bottom, padding_right=40, resizable='v', width=30, height = 100)""" # Create data series to plot timeplot = Plot(self.plotdataVoxel, resizable='hv', padding=20) timeplot.x_axis.title = "Frames" timeplot.plot("TimeVoxel", color='lightblue', line_width=1.0, bgcolor="white", name="Time")[0] # for i in range(len(self.tasks)): # timeplot.plot(self.timingNames[i+2],color=tuple(COLOR_PALETTE[i]), # line_width=1.0, bgcolor = "white", border_visible=True, name = self.timingNames[i+2])[0] timeplot.legend.visible = True timeplot.plot("time", type="scatter", color=tuple(COLOR_PALETTE[2]), line_width=1, bgcolor="white", border_visible=True, name="time")[0] self.timePlot = timeplot # Create data series to plot timeplotBig = Plot(self.plotdataVoxel, resizable='hv', padding=20) timeplotBig.x_axis.title = "Frames" timeplotBig.plot("TimeVoxel", color='lightblue', line_width=1.5, bgcolor="white", name="Time")[0] timeplotBig.legend.visible = True timeplotBig.plot("time", type="scatter", color=tuple(COLOR_PALETTE[2]), line_width=1, bgcolor="white", border_visible=True, name="time")[0] self.timePlotBig = timeplotBig # Create data series to plot freqplotBig = Plot(self.plotdataVoxelFFT, resizable='hv', padding=20) freqplotBig.x_axis.title = "Frequency (Hz)" freqplotBig.plot("FreqVoxel", color='lightblue', line_width=1.5, bgcolor="white", name="Abs(Y)")[0] freqplotBig.legend.visible = True freqplotBig.plot("peaks", type="scatter", color=tuple(COLOR_PALETTE[2]), line_width=1, bgcolor="white", border_visible=True, name="peaks")[0] self.freqPlotBig = freqplotBig # Create data series to plot PCplotBig = Plot(self.plotdataPC, resizable='hv', padding=20) PCplotBig.x_axis.title = "Frames" PCplotBig.plot("Principal Component", color='lightblue', line_width=1.5, bgcolor="white", name="Principal Component")[0] PCplotBig.legend.visible = True PCplotBig.plot("time", type="scatter", color=tuple(COLOR_PALETTE[2]), line_width=1, bgcolor="white", border_visible=True, name="time")[0] self.PCplotBig = PCplotBig #self.time = time # Create a GridContainer to hold all of our plots container = GridContainer(padding=10, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(2, 2), spacing=(10, 10)) containerTime = GridContainer(padding=10, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(1, 1), spacing=(5, 5)) containerFreq = GridContainer(padding=10, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(1, 1), spacing=(5, 5)) containerPC = GridContainer(padding=10, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(1, 1), spacing=(5, 5)) container.add(centerplot) container.add(rightplot) container.add(bottomplot) container.add(timeplot) containerTime.add(timeplotBig) containerFreq.add(freqplotBig) containerPC.add(PCplotBig) """container = GridContainer(padding=10, fill_padding=True, bgcolor="white", use_backbuffer=True, shape=(3,3), spacing=(10,10)) for i in range(14,23): slicePlot = Plot(self.plotdataSlices, resizable= 'hv', padding=20,title = "slice " + str(i),bgcolor = "white") slicePlot.img_plot("slice " + str(i),xbounds= None, ybounds= None, colormap=self.cmap,bgcolor = "white")[0] container.add(slicePlot)""" self.container = container self.nb.DeleteAllPages() self.window = Window(self.nb, -1, component=container) self.windowTime = Window(self.nb, -1, component=containerTime) self.windowFreq = Window(self.nb, -1, component=containerFreq) self.windowPC = Window(self.nb, -1, component=containerPC) self.sizer.Detach(self.topsizer) self.sizer.Detach(self.pnl2) self.topsizer.Clear() self.topsizer.Add(self.pnl3, 0, wx.ALL, 10) self.nb.AddPage(self.window.control, "fMRI Slices") self.nb.AddPage(self.windowTime.control, "Time Voxel") self.nb.AddPage(self.windowFreq.control, "Frequency Voxel") self.nb.AddPage(self.windowPC.control, "Principal Component") self.topsizer.Add(self.nb, 1, wx.EXPAND) self.sizer.Add(self.topsizer, 1, wx.EXPAND) self.sizer.Add(self.pnl2, flag=wx.EXPAND | wx.BOTTOM | wx.TOP, border=10) self.SetSizer(self.sizer) self.Centre() self.Show(True)
class TimerController(HasTraits): def __init__(self): self.arch = BehOrg.GraspArchitecture() self._time_steps = 0 self.create_plot_component() def get_container(self): return self._container def create_plot_component(self): color_range_max_value = 10 # gripper right cos field x_axis = numpy.array( range(self.arch._gripper_right_cos_field. get_output_dimension_sizes()[0])) self._gripper_right_cos_field_plotdata = ArrayPlotData( x=x_axis, y=self.arch._gripper_right_cos_field.get_activation()) self._gripper_right_cos_field_plot = Plot( self._gripper_right_cos_field_plotdata) self._gripper_right_cos_field_plot.title = 'gripper right cos' self._gripper_right_cos_field_plot.plot(("x", "y"), name='gripper_right_cos', type="line", color="blue") range_self = self._gripper_right_cos_field_plot.plots[ 'gripper_right_cos'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # gripper left cos field x_axis = numpy.array( range( self.arch._gripper_left_cos_field.get_output_dimension_sizes() [0])) self._gripper_left_cos_field_plotdata = ArrayPlotData( x=x_axis, y=self.arch._gripper_left_cos_field.get_activation()) self._gripper_left_cos_field_plot = Plot( self._gripper_left_cos_field_plotdata) self._gripper_left_cos_field_plot.title = 'gripper left cos' self._gripper_left_cos_field_plot.plot(("x", "y"), name='gripper_left_cos', type="line", color="blue") range_self = self._gripper_left_cos_field_plot.plots[ 'gripper_left_cos'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # find red color intention field x_axis = numpy.array( range(self.arch._find_color.get_intention_field(). get_output_dimension_sizes()[0])) self._find_color_intention_field_plotdata = ArrayPlotData( x=x_axis, y=self.arch._find_color.get_intention_field().get_activation()) self._find_color_intention_field_plot = Plot( self._find_color_intention_field_plotdata) self._find_color_intention_field_plot.title = 'find color int' self._find_color_intention_field_plot.plot(("x", "y"), name='find_color_int', type="line", color="blue") range_self = self._find_color_intention_field_plot.plots[ 'find_color_int'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # find green color intention field x_axis = numpy.array( range(self.arch._find_color_ee.get_intention_field(). get_output_dimension_sizes()[0])) self._find_color_ee_intention_field_plotdata = ArrayPlotData( x=x_axis, y=self.arch._find_color_ee.get_intention_field().get_activation()) self._find_color_ee_intention_field_plot = Plot( self._find_color_ee_intention_field_plotdata) self._find_color_ee_intention_field_plot.title = 'find color ee int' self._find_color_ee_intention_field_plot.plot(("x", "y"), name='find_color_ee_int', type="line", color="blue") range_self = self._find_color_ee_intention_field_plot.plots[ 'find_color_ee_int'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # camera self._camera_field_plotdata = ArrayPlotData() self._camera_field_plotdata.set_data( 'imagedata', self.arch._camera_field.get_activation().max(2).transpose()) self._camera_field_plot = Plot(self._camera_field_plotdata) self._camera_field_plot.title = 'camera' self._camera_field_plot.img_plot( 'imagedata', name='camera_field', xbounds=(0, self.arch._camera_field_sizes[0] - 1), ybounds=(0, self.arch._camera_field_sizes[1] - 1), colormap=jet, ) range_self = self._camera_field_plot.plots['camera_field'][ 0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # color space red self._color_space_field_plotdata = ArrayPlotData() self._color_space_field_plotdata.set_data( 'imagedata', self.arch._color_space_field.get_activation().max(1).transpose()) self._color_space_field_plot = Plot(self._color_space_field_plotdata) self._color_space_field_plot.title = 'color space' self._color_space_field_plot.img_plot( 'imagedata', name='color_space_field', xbounds=(0, self.arch._color_space_field_sizes[0] - 1), ybounds=(0, self.arch._color_space_field_sizes[2] - 1), colormap=jet, ) range_self = self._color_space_field_plot.plots['color_space_field'][ 0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # color space green self._color_space_ee_field_plotdata = ArrayPlotData() self._color_space_ee_field_plotdata.set_data( 'imagedata', self.arch._color_space_ee_field.get_activation().max( 2).transpose()) self._color_space_ee_field_plot = Plot( self._color_space_ee_field_plotdata) self._color_space_ee_field_plot.title = 'color space ee' self._color_space_ee_field_plot.img_plot( 'imagedata', name='color_space_ee_field', xbounds=(0, self.arch._color_space_ee_field_sizes[0] - 1), ybounds=(0, self.arch._color_space_ee_field_sizes[1] - 1), colormap=jet, ) range_self = self._color_space_ee_field_plot.plots[ 'color_space_ee_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # spatial target self._spatial_target_field_plotdata = ArrayPlotData() self._spatial_target_field_plotdata.set_data( 'imagedata', self.arch._spatial_target_field.get_activation().transpose()) self._spatial_target_field_plot = Plot( self._spatial_target_field_plotdata) self._spatial_target_field_plot.title = 'spatial target' self._spatial_target_field_plot.img_plot( 'imagedata', name='spatial_target_field', xbounds=(0, self.arch._spatial_target_field_sizes[0] - 1), ybounds=(0, self.arch._spatial_target_field_sizes[1] - 1), colormap=jet, ) range_self = self._spatial_target_field_plot.plots[ 'spatial_target_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # move head intention self._move_head_intention_field_plotdata = ArrayPlotData() self._move_head_intention_field_plotdata.set_data( 'imagedata', self.arch._move_head.get_intention_field().get_activation(). transpose()) self._move_head_intention_field_plot = Plot( self._move_head_intention_field_plotdata) self._move_head_intention_field_plot.title = 'move head int' self._move_head_intention_field_plot.img_plot( 'imagedata', name='move_head_intention_field', xbounds=(0, self.arch._move_head_field_sizes[0] - 1), ybounds=(0, self.arch._move_head_field_sizes[1] - 1), colormap=jet, ) range_self = self._move_head_intention_field_plot.plots[ 'move_head_intention_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # move head cos self._move_head_cos_field_plotdata = ArrayPlotData() self._move_head_cos_field_plotdata.set_data( 'imagedata', self.arch._move_head.get_cos_field().get_activation().transpose()) self._move_head_cos_field_plot = Plot( self._move_head_cos_field_plotdata) self._move_head_cos_field_plot.title = 'move head cos' self._move_head_cos_field_plot.img_plot( 'imagedata', name='move_head_cos_field', xbounds=(0, self.arch._move_head_field_sizes[0] - 1), ybounds=(0, self.arch._move_head_field_sizes[1] - 1), colormap=jet, ) range_self = self._move_head_cos_field_plot.plots[ 'move_head_cos_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # move right arm intention self._move_right_arm_intention_field_plotdata = ArrayPlotData() self._move_right_arm_intention_field_plotdata.set_data( 'imagedata', self.arch._move_right_arm_intention_field.get_activation(). transpose()) self._move_right_arm_intention_field_plot = Plot( self._move_right_arm_intention_field_plotdata) self._move_right_arm_intention_field_plot.title = 'move right arm int' self._move_right_arm_intention_field_plot.img_plot( 'imagedata', name='move_right_arm_intention_field', xbounds=(0, self.arch._move_arm_field_sizes[0] - 1), ybounds=(0, self.arch._move_arm_field_sizes[1] - 1), colormap=jet, ) range_self = self._move_right_arm_intention_field_plot.plots[ 'move_right_arm_intention_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # move right arm cos self._move_right_arm_cos_field_plotdata = ArrayPlotData() self._move_right_arm_cos_field_plotdata.set_data( 'imagedata', self.arch._move_arm_cos_field.get_activation().transpose()) self._move_right_arm_cos_field_plot = Plot( self._move_right_arm_cos_field_plotdata) self._move_right_arm_cos_field_plot.title = 'move right arm cos' self._move_right_arm_cos_field_plot.img_plot( 'imagedata', name='move_right_arm_cos_field', xbounds=(0, self.arch._move_arm_field_sizes[0] - 1), ybounds=(0, self.arch._move_arm_field_sizes[1] - 1), colormap=jet, ) range_self = self._move_right_arm_cos_field_plot.plots[ 'move_right_arm_cos_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # visual servoing right intention self._visual_servoing_right_intention_field_plotdata = ArrayPlotData() self._visual_servoing_right_intention_field_plotdata.set_data( 'imagedata', self.arch._visual_servoing_right.get_intention_field(). get_activation().transpose()) self._visual_servoing_right_intention_field_plot = Plot( self._visual_servoing_right_intention_field_plotdata) self._visual_servoing_right_intention_field_plot.title = 'visual servoing right int' self._visual_servoing_right_intention_field_plot.img_plot( 'imagedata', name='visual_servoing_right_intention_field', xbounds=(0, self.arch._visual_servoing_field_sizes[0] - 1), ybounds=(0, self.arch._visual_servoing_field_sizes[1] - 1), colormap=jet, ) range_self = self._visual_servoing_right_intention_field_plot.plots[ 'visual_servoing_right_intention_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value # visual servoing right cos self._visual_servoing_right_cos_field_plotdata = ArrayPlotData() self._visual_servoing_right_cos_field_plotdata.set_data( 'imagedata', self.arch._visual_servoing_right.get_cos_field().get_activation(). transpose()) self._visual_servoing_right_cos_field_plot = Plot( self._visual_servoing_right_cos_field_plotdata) self._visual_servoing_right_cos_field_plot.title = 'visual servoing right cos' self._visual_servoing_right_cos_field_plot.img_plot( 'imagedata', name='visual_servoing_right_cos_field', xbounds=(0, self.arch._visual_servoing_field_sizes[0] - 1), ybounds=(0, self.arch._visual_servoing_field_sizes[1] - 1), colormap=jet, ) range_self = self._visual_servoing_right_cos_field_plot.plots[ 'visual_servoing_right_cos_field'][0].value_mapper.range range_self.high = color_range_max_value range_self.low = -color_range_max_value self._container = VPlotContainer() self._hcontainer_top = HPlotContainer() self._hcontainer_bottom = HPlotContainer() self._hcontainer_bottom.add(self._camera_field_plot) self._hcontainer_bottom.add(self._color_space_field_plot) self._hcontainer_bottom.add(self._spatial_target_field_plot) self._hcontainer_bottom.add(self._move_head_intention_field_plot) self._hcontainer_bottom.add(self._move_right_arm_intention_field_plot) # self._hcontainer_bottom.add(self._find_color_intention_field_plot) # self._hcontainer_bottom.add(self._gripper_right_intention_field_plot) self._hcontainer_top.add(self._color_space_ee_field_plot) self._hcontainer_top.add( self._visual_servoing_right_intention_field_plot) self._hcontainer_top.add(self._visual_servoing_right_cos_field_plot) self._hcontainer_top.add(self._move_head_cos_field_plot) self._hcontainer_top.add(self._move_right_arm_cos_field_plot) # self._hcontainer_top.add(self._gripper_right_cos_field_plot) self._container.add(self._hcontainer_bottom) self._container.add(self._hcontainer_top) def onTimer(self, *args): self.arch.step() self._camera_field_plotdata.set_data( 'imagedata', self.arch._camera_field.get_activation().max(2).transpose()) self._color_space_field_plotdata.set_data( 'imagedata', self.arch._color_space_field.get_activation().max(1).transpose()) self._color_space_ee_field_plotdata.set_data( 'imagedata', self.arch._color_space_ee_field.get_activation().max( 2).transpose()) self._spatial_target_field_plotdata.set_data( 'imagedata', self.arch._spatial_target_field.get_activation().transpose()) self._move_head_intention_field_plotdata.set_data( 'imagedata', self.arch._move_head.get_intention_field().get_activation(). transpose()) self._move_head_cos_field_plotdata.set_data( 'imagedata', self.arch._move_head.get_cos_field().get_activation().transpose()) self._visual_servoing_right_intention_field_plotdata.set_data( 'imagedata', self.arch._visual_servoing_right.get_intention_field(). get_activation().transpose()) self._visual_servoing_right_cos_field_plotdata.set_data( 'imagedata', self.arch._visual_servoing_right.get_cos_field().get_activation(). transpose()) self._move_right_arm_intention_field_plotdata.set_data( 'imagedata', self.arch._move_right_arm_intention_field.get_activation(). transpose()) self._move_right_arm_cos_field_plotdata.set_data( 'imagedata', self.arch._move_arm_cos_field.get_activation().transpose()) # self._gripper_right_intention_field_plotdata.set_data('imagedata', self.arch._gripper_right_intention_field.get_activation().transpose()) # self._gripper_right_cos_field_plotdata.set_data('imagedata', self.arch._gripper_right_cos_field.get_activation().transpose()) # self._find_color_intention_field_plotdata.set_data('y', self.arch._find_color.get_intention_field().get_activation()) # self._find_color_ee_intention_field_plotdata.set_data('y', self.arch._find_color_ee.get_intention_field().get_activation()) self._camera_field_plot.request_redraw() self._color_space_field_plot.request_redraw() self._color_space_ee_field_plot.request_redraw() self._spatial_target_field_plot.request_redraw() self._move_head_intention_field_plot.request_redraw() self._move_head_cos_field_plot.request_redraw() self._visual_servoing_right_intention_field_plot.request_redraw() self._visual_servoing_right_cos_field_plot.request_redraw() self._move_right_arm_intention_field_plot.request_redraw() self._move_right_arm_cos_field_plot.request_redraw() # self._gripper_right_cos_field_plot.request_redraw() # self._gripper_right_intention_field_plot.request_redraw() return
class CMatrixViewer(MatrixViewer): tplot = Instance(Plot) plot = Instance(Component) custtool = Instance(CustomTool) colorbar = Instance(ColorBar) edge_parameter = Instance(EdgeParameters) network_reference = Any matrix_data_ref = Any labels = Any fro = Any to = Any val = Float traits_view = View(Group(Item('plot', editor=ComponentEditor(size=(800, 600)), show_label=False), HGroup( Item('fro', label="From", style='readonly', springy=True), Item('to', label="To", style='readonly', springy=True), Item('val', label="Value", style='readonly', springy=True), ), orientation="vertical"), Item('edge_parameter_name', label="Choose edge"), handler=CustomHandler(), resizable=True, title="Matrix Viewer") def __init__(self, net_ref, **traits): """ net_ref is a reference to a cnetwork """ super(MatrixViewer, self).__init__(**traits) self.network_reference = net_ref self.edge_parameter = self.network_reference._edge_para self.matrix_data_ref = self.network_reference.datasourcemanager._srcobj.edgeattributes_matrix_dict self.labels = self.network_reference.datasourcemanager._srcobj.labels # get the currently selected edge self.curr_edge = self.edge_parameter.parameterset.name # create plot self.plot = self._create_plot_component() # set trait notification on customtool self.custtool.on_trait_change(self._update_fields, "xval") self.custtool.on_trait_change(self._update_fields, "yval") # add edge parameter enum self.add_trait('edge_parameter_name', Enum(self.matrix_data_ref.keys())) self.edge_parameter_name = self.curr_edge def _edge_parameter_name_changed(self, new): # update edge parameter dialog self.edge_parameter.set_to_edge_parameter(self.edge_parameter_name) # update the data self.pd.set_data("imagedata", self.matrix_data_ref[self.edge_parameter_name]) # set range #self.my_plot.set_value_selection((0.0, 1.0)) def _update_fields(self): from numpy import trunc # map mouse location to array index frotmp = int(trunc(self.custtool.yval)) totmp = int(trunc(self.custtool.xval)) # check if within range sh = self.matrix_data_ref[self.edge_parameter_name].shape # assume matrix whose shape is (# of rows, # of columns) if frotmp >= 0 and frotmp < sh[0] and totmp >= 0 and totmp < sh[1]: self.fro = self.labels[frotmp] self.to = self.labels[totmp] self.val = self.matrix_data_ref[self.edge_parameter_name][frotmp, totmp] def _create_plot_component(self): # we need the matrices! # start with the currently selected one #nr_nodes = self.matrix_data_ref[curr_edge].shape[0] # Create a plot data obect and give it this data self.pd = ArrayPlotData() self.pd.set_data("imagedata", self.matrix_data_ref[self.curr_edge]) # Create the plot self.tplot = Plot(self.pd, default_origin="top left") self.tplot.x_axis.orientation = "top" self.tplot.img_plot( "imagedata", name="my_plot", #xbounds=(0,nr_nodes), #ybounds=(0,nr_nodes), colormap=jet) # Tweak some of the plot properties self.tplot.title = self.curr_edge self.tplot.padding = 50 # Right now, some of the tools are a little invasive, and we need the # actual CMapImage object to give to them self.my_plot = self.tplot.plots["my_plot"][0] # Attach some tools to the plot self.tplot.tools.append(PanTool(self.tplot)) zoom = ZoomTool(component=self.tplot, tool_mode="box", always_on=False) self.tplot.overlays.append(zoom) # my custom tool to get the connection information self.custtool = CustomTool(self.tplot) self.tplot.tools.append(self.custtool) # Create the colorbar, handing in the appropriate range and colormap colormap = self.my_plot.color_mapper self.colorbar = ColorBar( index_mapper=LinearMapper(range=colormap.range), color_mapper=colormap, plot=self.my_plot, orientation='v', resizable='v', width=30, padding=20) self.colorbar.padding_top = self.tplot.padding_top self.colorbar.padding_bottom = self.tplot.padding_bottom # TODO: the range selection gives a Segmentation Fault, # but why, the matrix_viewer.py example works just fine! # create a range selection for the colorbar self.range_selection = RangeSelection(component=self.colorbar) self.colorbar.tools.append(self.range_selection) self.colorbar.overlays.append( RangeSelectionOverlay(component=self.colorbar, border_color="white", alpha=0.8, fill_color="lightgray")) # we also want to the range selection to inform the cmap plot of # the selection, so set that up as well #self.range_selection.listeners.append(self.my_plot) # Create a container to position the plot and the colorbar side-by-side container = HPlotContainer(use_backbuffer=True) container.add(self.tplot) container.add(self.colorbar) container.bgcolor = "white" # my_plot.set_value_selection((-1.3, 6.9)) return container
class LFapplication(HasTraits): traits_view = View(Item('LF_img', editor=ComponentEditor(), show_label=False), Item('X_angle', label='Angle in the X axis'), Item('Y_angle', label='Angle in the Y axis'), resizable=True, title="LF Image") def __init__(self, img_path): super(LFapplication, self).__init__() # # Load image data # base_path = os.path.splitext(img_path)[0] lenslet_path = base_path + '-lenslet.txt' optics_path = base_path + '-optics.txt' with open(lenslet_path, 'r') as f: tmp = eval(f.readline()) x_offset, y_offset, right_dx, right_dy, down_dx, down_dy = \ np.array(tmp, dtype=np.float32) with open(optics_path, 'r') as f: for line in f: name, val = line.strip().split() try: setattr(self, name, np.float32(val)) except: pass max_angle = math.atan(self.pitch / 2 / self.flen) # # Prepare image # im_pil = Image.open(img_path) if im_pil.mode == 'RGB': self.NCHANNELS = 3 w, h = im_pil.size im = np.zeros((h, w, 4), dtype=np.float32) im[:, :, :3] = np.array(im_pil).astype(np.float32) self.LF_dim = (ceil(h / down_dy), ceil(w / right_dx), 3) else: self.NCHANNELS = 1 im = np.array(im_pil.getdata()).reshape(im_pil.size[::-1]).astype( np.float32) h, w = im.shape self.LF_dim = (ceil(h / down_dy), ceil(w / right_dx)) x_start = x_offset - int(x_offset / right_dx) * right_dx y_start = y_offset - int(y_offset / down_dy) * down_dy x_ratio = self.flen * right_dx / self.pitch y_ratio = self.flen * down_dy / self.pitch # # Generate the cuda kernel # mod_LFview = pycuda.compiler.SourceModule( _kernel_tpl.render(newiw=self.LF_dim[1], newih=self.LF_dim[0], oldiw=w, oldih=h, x_start=x_start, y_start=y_start, x_ratio=x_ratio, y_ratio=y_ratio, x_step=right_dx, y_step=down_dy, NCHANNELS=self.NCHANNELS)) self.LFview_func = mod_LFview.get_function("LFview_kernel") self.texref = mod_LFview.get_texref("tex") # # Now generate the cuda texture # if self.NCHANNELS == 3: cuda.bind_array_to_texref( cuda.make_multichannel_2d_array(im, order="C"), self.texref) else: cuda.matrix_to_texref(im, self.texref, order="C") # # We could set the next if we wanted to address the image # in normalized coordinates ( 0 <= coordinate < 1.) # texref.set_flags(cuda.TRSF_NORMALIZED_COORDINATES) # self.texref.set_filter_mode(cuda.filter_mode.LINEAR) # # Prepare the traits # self.add_trait('X_angle', Range(-max_angle, max_angle, 0.0)) self.add_trait('Y_angle', Range(-max_angle, max_angle, 0.0)) self.plotdata = ArrayPlotData(LF_img=self.sampleLF()) self.LF_img = Plot(self.plotdata) if self.NCHANNELS == 3: self.LF_img.img_plot("LF_img") else: self.LF_img.img_plot("LF_img", colormap=gray) def sampleLF(self): # # Get the output image # output = np.zeros(self.LF_dim, dtype=np.uint8) # # Calculate the gridsize. This is entirely given by the size of our image. # blocks = (16, 16, 1) gridx = ceil(self.LF_dim[1] / blocks[1]) gridy = ceil(self.LF_dim[0] / blocks[0]) grid = (gridx, gridy) # # Call the kernel # self.LFview_func(np.float32(self.X_angle), np.float32(self.Y_angle), cuda.Out(output), texrefs=[self.texref], block=blocks, grid=grid) return output @on_trait_change('X_angle, Y_angle') def updateImge(self): self.plotdata.set_data('LF_img', self.sampleLF())
def add_plot(self, label, beam): # container = GridPlotContainer(padding=20, fill_padding=True, # bgcolor="white", use_backbuffer=True, # shape=(2,2), spacing=(12,12)) # self.container = container self.plotdata = ArrayPlotData() self.model = beam.Data self.model.z_axis = self.model.z_axis[::-1] cmap = jet self._update_model(cmap) self.plotdata.set_data("xy", self.model.dose) self._update_images() # Center Plot centerplot = Plot(self.plotdata, resizable='hv', height=150, width=150, padding=0) centerplot.default_origin = 'top left' imgplot = centerplot.img_plot("xy", xbounds=(self.model.x_axis[0], self.model.x_axis[-1]), ybounds=(self.model.y_axis[0], self.model.y_axis[-1]), colormap=cmap)[0] imgplot.origin = 'top left' self._add_plot_tools(imgplot, "xy") left_axis = PlotAxis(centerplot, orientation='left', title='y') bottom_axis = PlotAxis(centerplot, orientation='bottom', title='x', title_spacing=30) centerplot.underlays.append(left_axis) centerplot.underlays.append(bottom_axis) self.center = imgplot # Right Plot rightplot = Plot(self.plotdata, height=150, width=150, resizable="hv", padding=0) rightplot.default_origin = 'top left' rightplot.value_range = centerplot.value_range imgplot = rightplot.img_plot("yz", xbounds=(self.model.z_axis[0], self.model.z_axis[-1]), ybounds=(self.model.y_axis[0], self.model.y_axis[-1]), colormap=cmap)[0] imgplot.origin = 'top left' self._add_plot_tools(imgplot, "yz") left_axis = PlotAxis(rightplot, orientation='left', title='y') bottom_axis = PlotAxis(rightplot, orientation='bottom', title='z', title_spacing=30) rightplot.underlays.append(left_axis) rightplot.underlays.append(bottom_axis) self.right = imgplot # Bottom Plot bottomplot = Plot(self.plotdata, height=150, width=150, resizable="hv", padding=0) bottomplot.index_range = centerplot.index_range imgplot = bottomplot.img_plot("xz", xbounds=(self.model.x_axis[0], self.model.x_axis[-1]), ybounds=(self.model.z_axis[0], self.model.z_axis[-1]), colormap=cmap)[0] self._add_plot_tools(imgplot, "xz") left_axis = PlotAxis(bottomplot, orientation='left', title='z') bottom_axis = PlotAxis(bottomplot, orientation='bottom', title='x', title_spacing=30) bottomplot.underlays.append(left_axis) bottomplot.underlays.append(bottom_axis) self.bottom = imgplot # Create Container and add all Plots # container = GridPlotContainer(padding=20, fill_padding=True, # bgcolor="white", use_backbuffer=True, # shape=(2,2), spacing=(12,12)) self.container.add(centerplot) self.container.add(rightplot) self.container.add(bottomplot) #return Window(self, -1, component=container) # return container return label