def edit_mask(self, mask_update_cb=None): self.win = pykoala.gui.gui_helpers.MaskTool(filter_cb=self.mask_select, reset_filter_cb=self.clear_mask) self.mask_update_cb = mask_update_cb plot = self.win.get_plot() if self.current_spectrum is None: self.mask_image = make.image(data=self.mask, colormap="hot") else: self.mask_image = make.image(data=self.current_spectrum*self.mask, colormap="hot") plot.add_item(self.mask_image) self.win.show() return self.win
def __onPlotImage(self): filename = osp.join(osp.dirname(__file__), 'brain.png') image = make.image(filename=filename, colormap="bone") data2 = np.array(image.data.T[200:], copy=True) image2 = make.image(data2, title="Modified", alpha_mask=True) window = self._newPlotWindow("testImagePlot") #self.plot1 = self.p_plotWindow.addImagePlot([image, image2]) window.addImageWidget([image, image2], show_xsection=True, show_ysection=True) window.show()
def edit_mask(self, mask_update_cb=None): self.win = pykoala.gui.gui_helpers.MaskTool( filter_cb=self.mask_select, reset_filter_cb=self.clear_mask) self.mask_update_cb = mask_update_cb plot = self.win.get_plot() if self.current_spectrum is None: self.mask_image = make.image(data=self.mask, colormap="hot") else: self.mask_image = make.image(data=self.current_spectrum * self.mask, colormap="hot") plot.add_item(self.mask_image) self.win.show() return self.win
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") win = create_window() image = make.image(filename=filename, colormap="bone") data2 = np.array(image.data.T[200:], copy=True) image2 = make.image(data2, title="Modified", alpha_mask=True) plot = win.get_plot() plot.add_item(image) plot.add_item(image2, z=1) win.exec_()
def imshow(data, interpolation=None, mask=None): """ Display the image in *data* to current axes interpolation: 'nearest', 'linear' (default), 'antialiasing' Example:: import numpy as np x = np.linspace(-5, 5, 1000) img = np.fromfunction(lambda x, y: np.sin((x/200.)*(y/200.)**2), (1000, 1000)) gray() imshow(img) show() """ axe = gca() import numpy as np if isinstance(data, np.ma.MaskedArray) and mask is None: mask = data.mask data = data.data if mask is None: img = make.image(data) else: img = make.maskedimage(data, mask, show_mask=True) if interpolation is not None: interp_dict = { 'nearest': INTERP_NEAREST, 'linear': INTERP_LINEAR, 'antialiasing': INTERP_AA } assert interpolation in interp_dict, "invalid interpolation option" img.set_interpolation(interp_dict[interpolation], size=5) axe.add_image(img) axe.yreverse = True _show_if_interactive() return [img]
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") image = make.image(filename=filename, title="Original", colormap="gray") win = ImageDialog( edit=False, toolbar=True, wintitle="Contrast test", options=dict(show_contrast=True), ) plot = win.get_plot() plot.add_item(image) win.resize(600, 600) win.show() try: plot.save_widget("contrast.png") except IOError: # Skipping this part of the test # because user has no write permission on current directory pass win.exec_()
def roi_setup(self): """Show a dialog to setup the region of interest.""" dialog = ImageDialog("ROI Setup", edit=True, toolbar=False, parent=self) default = dialog.add_tool(SelectTool) dialog.set_default_tool(default) roi_tool = dialog.add_tool(RectangleTool, switch_to_default_tool=True) roi = self.cam.roi old_roi = roi roi_tool.activate() # Get image and display plot = dialog.get_plot() img = make.image(self.cam_thread.img_data) plot.add_item(img) plot.set_active_item(img) # Wait for user input dialog.show() if dialog.exec_(): try: roi = get_rect(roi_tool) self.cam.set_roi(roi) except: e = sys.exc_info() print(e) self.cam.set_roi(old_roi)
def imshow(data, interpolation=None, mask=None): """ Display the image in *data* to current axes interpolation: 'nearest', 'linear' (default), 'antialiasing' Example: import numpy as np x = np.linspace(-5, 5, 1000) img = np.fromfunction(lambda x, y: np.sin((x/200.)*(y/200.)**2), (1000, 1000)) gray() imshow(img) show() """ axe = gca() import numpy as np if isinstance(data, np.ma.MaskedArray) and mask is None: mask = data.mask data = data.data if mask is None: img = make.image(data) else: img = make.maskedimage(data, mask, show_mask=True) if interpolation is not None: interp_dict = {'nearest': INTERP_NEAREST, 'linear': INTERP_LINEAR, 'antialiasing': INTERP_AA} assert interpolation in interp_dict, "invalid interpolation option" img.set_interpolation(interp_dict[interpolation], size=5) axe.add_image(img) axe.yreverse = True _show_if_interactive() return [img]
def image_plot(self, dset): self.msg("image plot") self.gui['plots_tabWidget'].setCurrentIndex(0) image_plot = self.gui['image_plot'] try: xdata = np.array(dset.dims[0][0]) ydata = np.array(dset.dims[1][0]) except Exception as e: self.msg("Couldn't find x/y data") self.msg(e) xdata = np.arange(dset.shape[0]) ydata = np.arange(dset.shape[1]) try: xlab = dset.dims[0].label ylab = dset.dims[1].label except: self.msg("Couldn't find x/y label") xlab, ylab = "", "" zlab = dset.name image_item = make.image(data=np.array(dset), xdata=(xdata[0], xdata[-1]), ydata=(ydata[0], ydata[-1])) image_plot.add_item(image_item) image_plot.set_axis_unit(2, xlab) image_plot.set_axis_unit(0, ylab) image_plot.set_axis_unit(1, zlab) image_plot.show() image_plot.do_autoscale()
def build_items(): x = np.linspace(-10, 10, 200) y = np.sin(np.sin(np.sin(x))) filename = osp.join(osp.dirname(__file__), "brain.png") items = [ make.curve(x, y, color="b"), make.image(filename=filename), make.trimage(filename=filename), make.maskedimage(filename=filename, colormap='gray', show_mask=True, xdata=[0, 40], ydata=[0, 50]), make.label("Relative position <b>outside</b>", (x[0], y[0]), (-10, -10), "BR"), make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10), "TL"), make.label("Absolute position", "R", (0, 0), "R"), make.legend("TR"), make.rectangle(-3, -0.8, -0.5, -1., "rc1"), make.segment(-3, -0.8, -0.5, -1., "se1"), make.ellipse(-10, 0.0, 0, 0, "el1"), make.annotated_rectangle(0.5, 0.8, 3, 1., "rc1", "tutu"), make.annotated_segment(-1, -1, 1, 1., "rc1", "tutu"), Axes((0, 0), (1, 0), (0, 1)), PolygonShape( np.array([[150., 330.], [270., 520.], [470., 480.], [520., 360.], [460., 200.], [250., 240.]])), ] return items
def build_items(): x = np.linspace(-10, 10, 200) y = np.sin(np.sin(np.sin(x))) filename = osp.join(osp.dirname(__file__), "brain.png") items = [ make.curve(x, y, color="b"), make.image(filename=filename), make.trimage(filename=filename), make.maskedimage(filename=filename, colormap='gray', show_mask=True, xdata=[0, 40], ydata=[0, 50]), make.label("Relative position <b>outside</b>", (x[0], y[0]), (-10, -10), "BR"), make.label("Relative position <i>inside</i>", (x[0], y[0]), (10, 10), "TL"), make.label("Absolute position", "R", (0, 0), "R"), make.legend("TR"), make.rectangle(-3, -0.8, -0.5, -1., "rc1"), make.segment(-3, -0.8, -0.5, -1., "se1"), make.ellipse(-10, 0.0, 0, 0, "el1"), make.annotated_rectangle(0.5, 0.8, 3, 1., "rc1", "tutu"), make.annotated_segment(-1, -1, 1, 1., "rc1", "tutu"), Axes( (0, 0), (1, 0), (0, 1) ), PolygonShape(np.array([[150., 330.], [270., 520.], [470., 480.], [520., 360.], [460., 200.], [250., 240.]])), ] return items
def image_plot(self, dset): self.msg("image plot") self.gui['plots_tabWidget'].setCurrentIndex(0) image_plot = self.gui['image_plot'] try: xdata = np.array(dset.dims[0][0]) ydata = np.array(dset.dims[1][0]) except Exception as e: self.msg("Couldn't find x/y data") self.msg(e) xdata = np.arange(dset.shape[0]) ydata = np.arange(dset.shape[1]) try: xlab = dset.dims[0].label ylab = dset.dims[1].label except: self.msg("Couldn't find x/y label") xlab, ylab = "", "" zlab = dset.name image_item = make.image(data=np.array(dset), xdata=(xdata[0],xdata[-1]), ydata=(ydata[0],ydata[-1])) image_plot.add_item(image_item) image_plot.set_axis_unit(2, xlab) image_plot.set_axis_unit(0, ylab) image_plot.set_axis_unit(1, zlab) image_plot.show() image_plot.do_autoscale()
def imshow(data, title=None, hold=False): dlg = ImageDialog(wintitle=title) dlg.get_plot().add_item(make.image(data)) if hold: dlg.show() else: dlg.exec_()
def display_data(self): kwds = OrderedDict() for name, combo in self.combos.iteritems(): try: kwds[name] = float(combo.currentText()) except ValueError: kwds[name] = str(combo.currentText()) key = self._str_data(kwds) dat, kwds = self.data[key] dat = 1.0-dat if not self.image: self.image = make.image(dat, title="Modified") self.get_plot().add_item(self.image) self.get_plot().set_axis_title(0, kwds['yname']) self.get_plot().set_axis_title(1, '1-R') self.get_plot().set_axis_title(2, kwds['xname']) # self.plot_thicknesses() self.get_plot().legend() else: self.image.set_data(dat) self.image.set_xdata(kwds['xmin'], kwds['xmax']) self.image.set_ydata(kwds['ymin'], kwds['ymax']) self.get_plot().replot() self.get_plot().do_autoscale()
def imshow( data ): win = ImageDialog(edit=False, toolbar=True, wintitle="ImageDialog test", options=dict(xlabel='Concentration', xunit='ppm')) item = make.image(data) plot = win.get_plot() plot.add_item(item) win.show() win.exec_()
def show_data(self, data): plot = self.get_plot() if self.item is not None: self.item.set_data(data) else: self.item = make.image(data, colormap="gray") plot.add_item(self.item, z=0) plot.set_active_item(self.item) plot.replot()
def __init__(self): QMainWindow.__init__(self) filename = osp.join(osp.dirname(__file__), "brain.png") image1 = make.image(filename=filename, title="Original", colormap='gray') from guiqwt.tests.image import compute_image image2 = make.image(compute_image()) widget = CentralWidget(self) self.setCentralWidget(widget) widget.plot1.add_item(image1) widget.plot2.add_item(image2) toolbar = self.addToolBar("tools") widget.manager.add_toolbar(toolbar, id(toolbar)) # widget.manager.set_default_toolbar(toolbar) widget.register_tools()
def data_view(data, ofa, data_title): win = ImageDialog(edit=True, toolbar=True, wintitle="DW viewer", options=dict(show_contrast=False, xlabel='Channel', xunit='#', ylabel='time', show_xsection=True, show_ysection=True)) # win.add_tool(AnnotatedRectangleTool) # win.add_tool(ReverseYAxisTool) # win.add_tool(AnnotatedRectangleTool, title="Flag", # switch_to_default_tool=False, # handle_final_shape_cb=customize_shape) # win.add_tool(VCursorTool) # sst=win.add_tool(SignalStatsTool) # SignalStatsTool.activate(sst) xcs = win.panels['x_cross_section'] xcs.cs_plot.curveparam.curvestyle = 'Steps' xcs.cs_plot.perimage_mode = False ycs = win.panels['y_cross_section'] ycs.cs_plot.curveparam.curvestyle = 'Steps' ycs.cs_plot.perimage_mode = False item_data = make.image(data, title=data_title) item_data.interpolate = (0, ) item_ofa = make.image(ofa, title='Overflow') item_ofa.interpolate = (0, ) item_ofa.imageparam.alpha_mask = True plot = win.get_plot() plot.add_item(item_data) plot.add_item(item_ofa) # plot.add_item(itemFlag) win.show() if win.exec_(): # return plot.items return win
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") image = make.image(filename=filename, colormap="bone") rect = get_segment(image) print("Coordinates:", rect) print("Distance:", np.sqrt((rect[2]-rect[0])**2 + (rect[3]-rect[1])**2))
def __init__(self, parent, plot): super(ImageFT, self).__init__(Qt.Vertical, parent) self.plot = plot self.image = make.image(np.zeros((512, 2048))) self.plot.add_item(self.image) self.hCursor = None self.roi = None self.scaleFun = lambda x: x self.scaleFunInv = lambda x: x
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") win = create_window() image1 = make.image(filename=filename, title="Original", alpha_mask=False, colormap='gray') data2 = np.array(image1.data.T[200:], copy=True) image2 = make.image(data2, title="Modified")#, alpha_mask=True) plot = win.get_plot() plot.add_item(image1, z=0) plot.add_item(image2, z=1) plot.set_items_readonly(False) image2.set_readonly(True) win.get_itemlist_panel().show() win.show() win.exec_()
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") win = create_window() image = make.image(filename=filename, colormap="bone", alpha_mask=True) plot = win.get_plot() plot.add_item(image) win.exec_()
def spike_amplitude_histogram(trains, num_bins, uniform_y_scale=True, x_unit=pq.uV, progress=None): """ Create a spike amplitude histogram. This plot is useful to assess the drift in spike amplitude over a longer recording. It shows histograms (one for each `trains` entry, e.g. segment) of maximum and minimum spike amplitudes. :param list trains: A list of lists of :class:`neo.core.SpikeTrain` objects. Each entry of the outer list will be one point on the x-axis (they could correspond to segments), all amplitude occurences of spikes contained in the inner list will be added up. :param int num_bins: Number of bins for the histograms. :param bool uniform_y_scale: If True, the histogram for each channel will use the same bins. Otherwise, the minimum bin range is computed separately for each channel. :param Quantity x_unit: Unit of Y-Axis. :param progress: Set this parameter to report progress. :type progress: :class:`spykeutils.progress_indicator.ProgressIndicator` :return: """ if not trains: raise SpykeException('No spikes trains for Spike Amplitude Histogram!') if not progress: progress = ProgressIndicator() hist, down, up = sah(trains, num_bins, uniform_y_scale, x_unit, progress) num_channels = len(down) columns = int(round(sp.sqrt(num_channels))) win = PlotDialog(toolbar=True, wintitle="Spike Amplitude Histogram") for c in xrange(num_channels): pW = BaseImageWidget(win, yreverse=False, lock_aspect_ratio=False) plot = pW.plot img = make.image(sp.log(hist[:, :, c] + 1), ydata=[down[c], up[c]], interpolation='nearest') plot.add_item(img) plot.set_axis_title(plot.Y_LEFT, 'Amplitude') plot.set_axis_unit(plot.Y_LEFT, x_unit.dimensionality.string) win.add_plot_widget(pW, c, column=c % columns) progress.done() win.add_custom_image_tools() win.add_x_synchronization_option(True, range(num_channels)) win.add_y_synchronization_option(uniform_y_scale, range(num_channels)) win.show() return win
def show_data(self, data, lut_range=None): plot = self.imagewidget.plot if self.item is not None: self.item.set_data(data) if lut_range is None: lut_range = self.item.get_lut_range() self.imagewidget.set_contrast_range(*lut_range) self.imagewidget.update_cross_sections() else: self.item = make.image(data) plot.add_item(self.item, z=0) plot.replot()
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") image = make.image(filename=filename, colormap="bone") rect = get_segment(image) print("Coordinates:", rect) print("Distance:", np.sqrt((rect[2] - rect[0])**2 + (rect[3] - rect[1])**2))
def test(): filename = osp.join(osp.dirname(__file__), "mr-brain.dcm") image = make.image(filename=filename, title="DICOM img", colormap='gray') win = ImageDialog(edit=False, toolbar=True, wintitle="DICOM I/O test", options=dict(show_contrast=True)) plot = win.get_plot() plot.add_item(image) plot.select_item(image) contrast = win.get_contrast_panel() contrast.histogram.eliminate_outliers(54.) win.resize(600, 700) return win
def spike_amplitude_histogram(trains, num_bins, uniform_y_scale=True, x_unit=pq.uV, progress=None): """ Create a spike amplitude histogram. This plot is useful to assess the drift in spike amplitude over a longer recording. It shows histograms (one for each `trains` entry, e.g. segment) of maximum and minimum spike amplitudes. :param list trains: A list of lists of :class:`neo.core.SpikeTrain` objects. Each entry of the outer list will be one point on the x-axis (they could correspond to segments), all amplitude occurences of spikes contained in the inner list will be added up. :param int num_bins: Number of bins for the histograms. :param bool uniform_y_scale: If True, the histogram for each channel will use the same bins. Otherwise, the minimum bin range is computed separately for each channel. :param Quantity x_unit: Unit of Y-Axis. :param progress: Set this parameter to report progress. :type progress: :class:`spykeutils.progress_indicator.ProgressIndicator` :return: """ if not trains: raise SpykeException('No spikes trains for Spike Amplitude Histogram!') if not progress: progress = ProgressIndicator() hist, down, up = sah(trains, num_bins, uniform_y_scale, x_unit, progress) num_channels = len(down) columns = int(round(sp.sqrt(num_channels))) win = PlotDialog(toolbar=True, wintitle="Spike Amplitude Histogram") for c in xrange(num_channels): pW = BaseImageWidget( win, yreverse=False, lock_aspect_ratio=False) plot = pW.plot img = make.image(sp.log(hist[:, :, c] + 1), ydata=[down[c], up[c]], interpolation='nearest') plot.add_item(img) plot.set_axis_title(plot.Y_LEFT, 'Amplitude') plot.set_axis_unit(plot.Y_LEFT, x_unit.dimensionality.string) win.add_plot_widget(pW, c, column=c % columns) progress.done() win.add_custom_image_tools() win.add_x_synchronization_option(True, range(num_channels)) win.add_y_synchronization_option(uniform_y_scale, range(num_channels)) win.show() return win
def initializeTimeFreq(self): self.plot.del_all_items() self.len_wavelet = int(self.xsize/self.threadacquisition.samplingInterval) self.wf = generate_wavelet_fourier(len_wavelet= self.len_wavelet, ** self.paramsTimeFreq).transpose() self.win = hamming(self.len_wavelet) self.map = zeros(self.wf.shape) self.image = make.image(self.map, title='TimeFreq',interpolation ='nearest') self.plot.add_item(self.image) p = self.paramsTimeFreq self.freqs = arange(p['f_start'],p['f_stop'],p['deltafreq'])
def add_item(self, trace, plotkwargs={}): if trace in self.items: self.plot_widget.plot.del_item(self.items[trace]) if self.rank == 1: try: self.items[trace] = make.curve([], [], **plotkwargs) except: raise elif self.rank == 2: if 'interpolation' not in plotkwargs: plotkwargs['interpolation'] = 'nearest' self.items[trace] = make.image(np.array([[0]]), **plotkwargs) else: raise ValueError self.plot_widget.plot.add_item(self.items[trace])
def update(self, img_data): """Update the image plot and other information.""" # Apply image transformations if necessary. img_data = np.rot90(img_data, -self.rotation) if self.mirror[0]: img_data = np.flipud(img_data) if self.mirror[1]: img_data = np.fliplr(img_data) # Configure plot plot = self.imageWidget.get_plot() img = get_image_item(self.imageWidget) roi_rect = get_rect_item(self.imageWidget) if img is None: img = make.image(img_data, colormap=str(self.colormapBox.currentText())) plot.add_item(img) else: img.set_data(img_data) #img.select() #plot.replot() # Display ROI if requested. # TODO: make mirroring work roi = np.array(self.cam.roi) center = np.array(img_data.shape)/2 roi = rotate_rect_cw(roi, center, self.rotation) if self.showROIBox.isChecked(): if roi_rect is None: roi_rect = make.rectangle(roi[0], roi[1], roi[2], roi[3]) roi_rect.set_resizable(False) roi_rect.set_selectable(False) plot.add_item(roi_rect) else: roi_rect.set_rect(roi[0], roi[1], roi[2], roi[3]) else: if roi_rect is not None: plot.del_item(roi_rect) # Update plot if self.autoscaleButton.isChecked(): self.rescale() self.set_lut_range() plot.set_plot_limits(0, img_data.shape[1], 0, img_data.shape[0]) plot.set_aspect_ratio(img_data.shape[0]/img_data.shape[1], lock=True) plot.replot()
def __init__(self, parent): super(QWidget, self).__init__(parent) self.parent = parent self.base_path = os.path.realpath(os.path.curdir) self.threadAcq = ThreadAcq(self) self.configMTE = QSettings('configMTE.ini', QSettings.IniFormat) self.setup() self.win = ImageDialog(edit=False, toolbar=True, wintitle="Visu Data", options=dict(show_xsection=True, show_ysection=True, show_contrast=True, show_itemlist=False)) self.win.resize(800, 1000) data = np.ones((1300, 1340)) self.item_data = make.image(data, colormap='hot') self.plot = self.win.get_plot() self.plot.add_item(self.item_data)
def display_data(self): n = float(self.combo_n.currentText()) eta = float(self.combo_eta.currentText()) pol = self.combo_pol.currentText() dat, kwds = self.data[self._str_data(n, eta, pol)] dat = 1.0 - dat if not self.image: self.image = make.image(dat, title="Modified") self.get_plot().add_item(self.image) self.get_plot().set_axis_title(0, 'thickness') self.get_plot().set_axis_title(1, '1-R') self.get_plot().set_axis_title(2, 'llambda') self.plot_thicknesses() self.get_plot().legend() else: self.image.set_data(dat) self.image.set_xdata(kwds['llambda_min'], kwds['llambda_max']) self.image.set_ydata(kwds['t_min'], kwds['t_max']) self.get_plot().replot() self.get_plot().do_autoscale()
def display_data(self): n = float(self.combo_n.currentText()) eta = float(self.combo_eta.currentText()) pol = self.combo_pol.currentText() dat, kwds = self.data[self._str_data(n, eta, pol)] dat = 1.0-dat if not self.image: self.image = make.image(dat, title="Modified") self.get_plot().add_item(self.image) self.get_plot().set_axis_title(0, 'thickness') self.get_plot().set_axis_title(1, '1-R') self.get_plot().set_axis_title(2, 'llambda') self.plot_thicknesses() self.get_plot().legend() else: self.image.set_data(dat) self.image.set_xdata(kwds['llambda_min'], kwds['llambda_max']) self.image.set_ydata(kwds['t_min'], kwds['t_max']) self.get_plot().replot() self.get_plot().do_autoscale()
def test(): """Test""" # -- Create QApplication import guidata _app = guidata.qapplication() # -- filename = osp.join(osp.dirname(__file__), "brain.png") image = make.image(filename=filename, title="Original", colormap='gray') win = ImageDialog(edit=False, toolbar=True, wintitle="Contrast test", options=dict(show_contrast=True)) plot = win.get_plot() plot.add_item(image) win.resize(600, 600) win.show() try: plot.save_widget('contrast.png') except IOError: # Skipping this part of the test # because user has no write permission on current directory pass win.exec_()
def update(self): """Show the currently selected image from the ring buffer.""" # Get the specified image data and ROI img_data = self.rbuffer.read(self.indexBox.value()) roi = self.rbuffer.get_roi(self.indexBox.value()) # Update the viewer plot = self.imageWidget.get_plot() img = get_image_item(self.imageWidget) rect = get_rect_item(self.imageWidget) if img is None: img = make.image(img_data, colormap=str( self.parent().colormapBox.currentText())) plot.add_item(img) else: img.set_data(img_data) if rect is None: rect = make.rectangle(roi[0], roi[1], roi[2], roi[3]) plot.add_item(rect) else: rect.set_rect(roi[0], roi[1], roi[2], roi[3]) plot.replot()
def start(self, current, selections): current.progress.begin('Creating Spectogram') signals = current.analog_signals(self.which_signals + 1) if not signals: current.progress.done() raise SpykeException('No signals selected!') num_signals = len(signals) columns = int(round(sp.sqrt(num_signals))) current.progress.set_ticks(num_signals) samples = self.nfft_index[self.fft_samples] win = PlotDialog(toolbar=True, wintitle="Signal Spectogram (FFT window size %d)" % samples) for c in xrange(num_signals): pW = BaseImageWidget(win, yreverse=False, lock_aspect_ratio=False) plot = pW.plot s = signals[c] # Calculate spectrogram and create plot v = mlab.specgram(s, NFFT=samples, noverlap=samples/2, Fs=s.sampling_rate) interpolation = 'nearest' if self.interpolate: interpolation = 'linear' img = make.image(sp.log(v[0]), ydata=[v[1][0],v[1][-1]], xdata=[v[2][0],v[2][-1]], interpolation=interpolation) plot.add_item(img) # Labels etc. if not self.show_color_bar: plot.disable_unused_axes() title = '' if s.recordingchannel and s.recordingchannel.name: title = s.recordingchannel.name if s.segment and s.segment.name: if title: title += ' , ' title += s.segment.name plot.set_title(title) plot.set_axis_title(plot.Y_LEFT, 'Frequency') plot.set_axis_unit(plot.Y_LEFT, s.sampling_rate.dimensionality.string) plot.set_axis_title(plot.X_BOTTOM, 'Time') time_unit = (1 / s.sampling_rate).simplified plot.set_axis_unit(plot.X_BOTTOM, time_unit.dimensionality.string) win.add_plot_widget(pW, c, column=c%columns) current.progress.step() current.progress.done() win.add_custom_image_tools() win.add_x_synchronization_option(True, range(num_signals)) win.add_y_synchronization_option(True, range(num_signals)) win.show()
def compute_oblique_section(item, obj): """Return oblique averaged cross section""" global TEMP_ITEM xa, ya, xb, yb = obj.get_bounding_rect_coords() x0, y0, x1, y1, x2, y2, x3, y3 = obj.get_rect() getcpi = item.get_closest_pixel_indexes ixa, iya = getcpi(xa, ya) ixb, iyb = getcpi(xb, yb) ix0, iy0 = getcpi(x0, y0) ix1, iy1 = getcpi(x1, y1) ix3, iy3 = getcpi(x3, y3) destw = vector_norm(ix0, iy0, ix1, iy1) desth = vector_norm(ix0, iy0, ix3, iy3) ysign = -1 if obj.plot().get_axis_direction('left') else 1 angle = vector_angle(ix1-ix0, (iy1-iy0)*ysign) dst_rect = (0, 0, int(destw), int(desth)) dst_image = np.empty((desth, destw), dtype=np.float64) if isinstance(item.data, np.ma.MaskedArray): if item.data.dtype in (np.float32, np.float64): item_data = item.data else: item_data = np.ma.array(item.data, dtype=np.float32, copy=True) data = np.ma.filled(item_data, np.nan) else: data = item.data ixr = .5*(ixb+ixa) iyr = .5*(iyb+iya) mat = translate(ixr, iyr)*rotate(-angle)*translate(-.5*destw, -.5*desth) _scale_tr(data, mat, dst_image, dst_rect, (1., 0., np.nan), (INTERP_LINEAR,)) if DEBUG: plot = obj.plot() if TEMP_ITEM is None: from guiqwt.builder import make TEMP_ITEM = make.image(dst_image) plot.add_item(TEMP_ITEM) else: TEMP_ITEM.set_data(dst_image) if False: TEMP_ITEM.imageparam.alpha_mask = True xmin, ymin = ixa, iya xmax, ymax = xmin+destw, ymin+desth TEMP_ITEM.imageparam.xmin = xmin TEMP_ITEM.imageparam.xmax = xmax TEMP_ITEM.imageparam.ymin = ymin TEMP_ITEM.imageparam.ymax = ymax TEMP_ITEM.imageparam.update_image(TEMP_ITEM) plot.replot() ydata = np.ma.fix_invalid(dst_image, copy=DEBUG).mean(axis=1) xdata = item.get_x_values(0, ydata.size)[:ydata.size] try: xdata -= xdata[0] except IndexError: print(xdata, ydata) return xdata, ydata
def compute_oblique_section(item, obj): """Return oblique averaged cross section""" global TEMP_ITEM xa, ya, xb, yb = obj.get_bounding_rect_coords() x0, y0, x1, y1, x2, y2, x3, y3 = obj.get_rect() getcpi = item.get_closest_pixel_indexes ixa, iya = getcpi(xa, ya) ixb, iyb = getcpi(xb, yb) ix0, iy0 = getcpi(x0, y0) ix1, iy1 = getcpi(x1, y1) ix3, iy3 = getcpi(x3, y3) destw = vector_norm(ix0, iy0, ix1, iy1) desth = vector_norm(ix0, iy0, ix3, iy3) ysign = -1 if obj.plot().get_axis_direction('left') else 1 angle = vector_angle(ix1 - ix0, (iy1 - iy0) * ysign) dst_rect = (0, 0, int(destw), int(desth)) dst_image = np.empty((desth, destw), dtype=np.float64) if isinstance(item.data, np.ma.MaskedArray): if item.data.dtype in (np.float32, np.float64): item_data = item.data else: item_data = np.ma.array(item.data, dtype=np.float32, copy=True) data = np.ma.filled(item_data, np.nan) else: data = item.data ixr = .5 * (ixb + ixa) iyr = .5 * (iyb + iya) mat = translate(ixr, iyr) * rotate(-angle) * translate( -.5 * destw, -.5 * desth) _scale_tr(data, mat, dst_image, dst_rect, (1., 0., np.nan), (INTERP_LINEAR, )) if DEBUG: plot = obj.plot() if TEMP_ITEM is None: from guiqwt.builder import make TEMP_ITEM = make.image(dst_image) plot.add_item(TEMP_ITEM) else: TEMP_ITEM.set_data(dst_image) if False: TEMP_ITEM.imageparam.alpha_mask = True xmin, ymin = ixa, iya xmax, ymax = xmin + destw, ymin + desth TEMP_ITEM.imageparam.xmin = xmin TEMP_ITEM.imageparam.xmax = xmax TEMP_ITEM.imageparam.ymin = ymin TEMP_ITEM.imageparam.ymax = ymax TEMP_ITEM.imageparam.update_image(TEMP_ITEM) plot.replot() ydata = np.ma.fix_invalid(dst_image, copy=DEBUG).mean(axis=1) xdata = item.get_x_values(0, ydata.size)[:ydata.size] try: xdata -= xdata[0] except IndexError: print(xdata, ydata) return xdata, ydata
def __init__(self, image_data): super(TestWindow, self).__init__() plot = self.imagewidget.plot plot.add_item(make.image(image_data)) self.setWindowTitle("QtDesigner plugins example")
def start(self, current, selections): current.progress.begin('Creating Spectogram') signals = current.analog_signals(self.which_signals + 1) if not signals: current.progress.done() raise SpykeException('No signals selected!') num_signals = len(signals) columns = int(round(sp.sqrt(num_signals))) current.progress.set_ticks(num_signals) samples = self.nfft_index[self.fft_samples] win = PlotDialog(toolbar=True, wintitle="Signal Spectogram (FFT window size %d)" % samples) for c in xrange(num_signals): pW = BaseImageWidget(win, yreverse=False, lock_aspect_ratio=False) plot = pW.plot s = signals[c] # Calculate spectrogram and create plot v = mlab.specgram(s, NFFT=samples, noverlap=samples / 2, Fs=s.sampling_rate.rescale(pq.Hz)) interpolation = 'nearest' if self.interpolate: interpolation = 'linear' img = make.image(sp.log(v[0]), ydata=[v[1][0], v[1][-1]], xdata=[ v[2][0] + s.t_start.rescale(pq.s), v[2][-1] + s.t_start.rescale(pq.s) ], interpolation=interpolation) plot.add_item(img) # Labels etc. if not self.show_color_bar: plot.disable_unused_axes() title = '' if s.recordingchannel and s.recordingchannel.name: title = s.recordingchannel.name if s.segment and s.segment.name: if title: title += ' , ' title += s.segment.name plot.set_title(title) plot.set_axis_title(plot.Y_LEFT, 'Frequency') plot.set_axis_unit(plot.Y_LEFT, s.sampling_rate.dimensionality.string) plot.set_axis_title(plot.X_BOTTOM, 'Time') time_unit = (1 / s.sampling_rate).simplified plot.set_axis_unit(plot.X_BOTTOM, time_unit.dimensionality.string) win.add_plot_widget(pW, c, column=c % columns) current.progress.step() current.progress.done() win.add_custom_image_tools() win.add_x_synchronization_option(True, range(num_signals)) win.add_y_synchronization_option(True, range(num_signals)) win.show()
def setup_plot(self): self.imagewidget = ImageWidget() self.plot = self.imagewidget.plot self.image = make.image(np.random.rand(100,100)) self.plot.add_item(self.image)
def setup_plot(self): self.imagewidget = ImageWidget() self.plot = self.imagewidget.plot self.image = make.image(np.random.rand(100, 100)) self.plot.add_item(self.image)
def load_dset_deprecated(self, item, column): # Message attribute values _type = item.text(1) if _type == "attr": self.msg("Attribute", item.name, ":", item.val) return self.msg("Load Dataset") h5file = self.open_file for name in item.path: h5file = h5file[name] # TODO 1D, Axis Selection, etc original_h5file = h5file if isinstance(h5file, h5py.Dataset): # 2D dataset handling if len(h5file.shape) == 2: if h5file.shape[0] == 1: h5file = h5file[0,:] else: try: xdata, ydata = h5file.attrs["_axes"] pi = make.image(data=np.array(h5file), xdata=tuple(xdata), ydata=tuple(ydata)) except KeyError: self.msg("no _axes attribute") self.msg("Axes scaling could not be set up.") pi = make.image(data=np.array(h5file)) try: xlab, ylab, zlab = h5file.attrs["_axes_labels"] except Exception as e: xlab, ylab, zlab = "", "", "" self.msg(e) self.gui["image_plot"].set_axis_unit(2, xlab) self.gui["image_plot"].set_axis_unit(0, ylab) self.gui["image_plot"].set_axis_unit(1, zlab) self.gui["plots_tabWidget"].setCurrentIndex(0) self.gui["image_plot"].del_all_items() self.gui["image_plot"].add_item(pi) self.gui["image_plot"].show() self.gui["image_plot"].do_autoscale() # 1D dataset handling if len(h5file.shape) == 1: if hasattr(self, "x_data"): x_data = self.x_data else: try: x0, x1 = original_h5file.attrs['_axes'][0] x_data = np.linspace(x0, x1, h5file.shape[0]) self.msg('set up axes') except: x_data = list(range(h5file.shape[0])) try: xlab, ylab = original_h5file.attrs["_axes_labels"] except Exception as e: xlab, ylab = "", "" self.msg("Labels could not be set up", e) self.gui["line_plot"].set_axis_unit(2, xlab) self.gui["line_plot"].set_axis_unit(0, ylab) if len(x_data) != h5file.shape[0]: self.msg("Cannot broadcast shapes: x data has length", len(x_data)) return ci = make.curve(x=x_data, y=np.array(h5file)) self.gui["plots_tabWidget"].setCurrentIndex(1) self.gui["line_plot"].del_all_items() self.gui["line_plot"].add_item(ci) self.gui["line_plot"].show() self.gui["line_plot"].do_autoscale()
def load_dset_deprecated(self, item, column): # Message attribute values _type = item.text(1) if _type == "attr": self.msg("Attribute", item.name, ":", item.val) return self.msg("Load Dataset") h5file = self.open_file for name in item.path: h5file = h5file[name] # TODO 1D, Axis Selection, etc original_h5file = h5file if isinstance(h5file, h5py.Dataset): # 2D dataset handling if len(h5file.shape) == 2: if h5file.shape[0] == 1: h5file = h5file[0, :] else: try: xdata, ydata = h5file.attrs["_axes"] pi = make.image(data=np.array(h5file), xdata=tuple(xdata), ydata=tuple(ydata)) except KeyError: self.msg("no _axes attribute") self.msg("Axes scaling could not be set up.") pi = make.image(data=np.array(h5file)) try: xlab, ylab, zlab = h5file.attrs["_axes_labels"] except Exception as e: xlab, ylab, zlab = "", "", "" self.msg(e) self.gui["image_plot"].set_axis_unit(2, xlab) self.gui["image_plot"].set_axis_unit(0, ylab) self.gui["image_plot"].set_axis_unit(1, zlab) self.gui["plots_tabWidget"].setCurrentIndex(0) self.gui["image_plot"].del_all_items() self.gui["image_plot"].add_item(pi) self.gui["image_plot"].show() self.gui["image_plot"].do_autoscale() # 1D dataset handling if len(h5file.shape) == 1: if hasattr(self, "x_data"): x_data = self.x_data else: try: x0, x1 = original_h5file.attrs['_axes'][0] x_data = np.linspace(x0, x1, h5file.shape[0]) self.msg('set up axes') except: x_data = list(range(h5file.shape[0])) try: xlab, ylab = original_h5file.attrs["_axes_labels"] except Exception as e: xlab, ylab = "", "" self.msg("Labels could not be set up", e) self.gui["line_plot"].set_axis_unit(2, xlab) self.gui["line_plot"].set_axis_unit(0, ylab) if len(x_data) != h5file.shape[0]: self.msg("Cannot broadcast shapes: x data has length", len(x_data)) return ci = make.curve(x=x_data, y=np.array(h5file)) self.gui["plots_tabWidget"].setCurrentIndex(1) self.gui["line_plot"].del_all_items() self.gui["line_plot"].add_item(ci) self.gui["line_plot"].show() self.gui["line_plot"].do_autoscale()