def show_confidence_region(results, test_params, img=None): """Show contour lines for 5% (red), 50% (green), and 95% (blue) percentile levels from the output of test_model_grid(). This yields a kind of confidence region showing where 95% of simulated fit experiments yield parameters greater (blue) or less than (red) the threshold *test_params*. """ amp_min = scipy.stats.scoreatpercentile(results['fit_amp'], 5, axis=2) amp_mid = scipy.stats.scoreatpercentile(results['fit_amp'], 50, axis=2) amp_max = scipy.stats.scoreatpercentile(results['fit_amp'], 95, axis=2) tau_min = scipy.stats.scoreatpercentile(results['fit_tau'], 5, axis=2) tau_mid = scipy.stats.scoreatpercentile(results['fit_tau'], 50, axis=2) tau_max = scipy.stats.scoreatpercentile(results['fit_tau'], 95, axis=2) def filter(img): return scipy.ndimage.gaussian_filter(img, (1, 1)) curves = [] for (name, i, p_min, p_mid, p_max) in [('amp', 0, amp_min, amp_mid, amp_max), ('tau', 1, tau_min, tau_mid, tau_max)]: c1 = pg.IsocurveItem(data=filter(p_min), level=test_params[i], pen={ 'color': 'r', 'width': i + 1 }) c1.setZValue(10) c2 = pg.IsocurveItem(data=filter(p_mid), level=test_params[i], pen={ 'color': 'g', 'width': i + 1 }) c2.setZValue(10) c3 = pg.IsocurveItem(data=filter(p_max), level=test_params[i], pen={ 'color': 'b', 'width': i + 1 }) c3.setZValue(10) if img is not None: c1.setParentItem(img) c2.setParentItem(img) c3.setParentItem(img) curves.append((c1, c2, c3)) return curves
def __init__(self, *args, **kwargs): super(Base2DGraph, self).__init__(*args, **kwargs) self._plot = self.addPlot() self._plot.showGrid(True, True, 0.5) self.vb = self.plot.getViewBox() self.vb.setAspectLocked() self.image_item = pg.ImageItem() self._plot.addItem(self.image_item) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.image_item) self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso_line = pg.InfiniteLine(angle=0, movable=True, pen='g') self.iso.setParentItem(self.image_item) self.iso.setZValue(5) # Draggable line for settings isocurve level self.hist.vb.addItem(self.iso_line) self.hist.vb.setMouseEnabled(y=False) self.iso_line.setValue(0.8) self.iso_line.setZValue(1000) def update_isocurve(): self.iso.setLevel(self.iso_line.value()) self.iso_line.sigDragged.connect(update_isocurve)
def redraw(self, interp_order=0): """ Update the image when the slice data may have changed and therefore may need re-extracting. This is more expensive than just changing image parameters so it is only triggered when required """ self.debug("slicedataview: redrawing image") self.debug(self._vol) self.debug("%s, %s", self._plane.basis, self._plane.normal) self._z_order = self._view.z_order if self._qpdata.roi: # FIXME ROIs always on top - should be option self._z_order += MAX_NUM_DATA_SETS if self._img.isVisible() or self._view.contour: slicedata, slicemask, scale, offset = self._qpdata.slice_data( self._plane, vol=self._vol, interp_order=interp_order) self.debug("Image data range: %f, %f", np.min(slicedata), np.max(slicedata)) qtransform = QtGui.QTransform(scale[0, 0], scale[0, 1], scale[1, 0], scale[1, 1], offset[0], offset[1]) if self._img.isVisible(): self._img.setTransform(qtransform) self._img.setImage(slicedata, autoLevels=False) self._img.setZValue(self._z_order) if self._view.roi: roi = self._ivm.data[self._view.roi] resampled_roi = roi.resample(self._qpdata.grid) maskdata, _, _, _ = resampled_roi.slice_data(self._plane) self._img.mask = np.logical_and(maskdata, slicemask) else: self._img.mask = slicemask n_contours = 0 if self._qpdata.roi and self._view.contour and self._view.visible == Visibility.SHOW: # Update data and level for existing contour items, and create new ones if needed max_region = max(self._qpdata.regions.keys()) for val in self._qpdata.regions: pencol = get_col(self._lut, val, max_region) if val != 0: if n_contours == len(self._contours): self._contours.append(pg.IsocurveItem()) self._viewbox.addItem(self._contours[n_contours]) contour = self._contours[n_contours] contour.setTransform(qtransform) contour.setData((slicedata == val).astype(np.int)) contour.setLevel(1) contour.setPen(pg.mkPen(pencol, width=3)) contour.setZValue(self._z_order) n_contours += 1 # Clear data from contours not required - FIXME delete them? for idx in range(n_contours, len(self._contours)): self._contours[idx].setData(None)
def addIsocurve(self, level=0.): iso = pg.IsocurveItem(level=level, pen='g') iso.setZValue(1000) iso.setData(pg.gaussianFilter(self.data, (5, 5))) iso.setParentItem(self.image) self.iso = iso
def redraw(self, viewbox, slice_plane, slice_vol): img = self._get_img(viewbox) contours = self._get_contours(viewbox) self.update() n_contours = 0 if self.data is not None: slicedata, _, scale, offset = self.data.slice_data(slice_plane) transform = QtGui.QTransform(scale[0, 0], scale[0, 1], scale[1, 0], scale[1, 1], offset[0], offset[1]) if img.isVisible(): img.setImage(slicedata, autoLevels=False) img.setTransform(transform) if self.get("contour"): # Update data and level for existing contour items, and create new ones if needed for val in self.data.regions: pencol = get_pencol(self.data, val) if val != 0: if n_contours == len(contours): contours.append(pg.IsocurveItem()) viewbox.addItem(contours[n_contours]) contour = contours[n_contours] contour.setTransform(transform) contour.setData((slicedata == val).astype(np.int)) contour.setLevel(1) contour.setPen( pg.mkPen(pencol, width=self.get("outline_width"))) n_contours += 1 # Clear data from contours not required - FIXME delete them? for idx in range(n_contours, len(contours)): contours[idx].setData(None)
def __init__(self, name, **kwargs): terminals = {'view': {'io': 'in'}, 'level': {'io': 'out'}} super().__init__(name, terminals=terminals, **kwargs) self.view = None self.iso = pg.IsocurveItem(level=0.5, pen='g') self.iso.setZValue(5) self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.isoLine.setValue(0.5) self.isoLine.setZValue(1000) self.isoLine.sigDragged.connect(self.updateIsocurve) self.panel = QWidget() self.panelLayout = QGridLayout(self.panel) self.colorButton = pg.ColorButton(self.panel) self.panelLayout.addWidget(self.colorButton, 1, 1) self.visibleCheckBox = QCheckBox('Visible', self.panel) self.visibleCheckBox.setChecked(True) self.panelLayout.addWidget(self.visibleCheckBox, 1, 2) self.panel.setLayout(self.panelLayout) self.visibleCheckBox.toggled.connect(self.setVisible) self.colorButton.sigColorChanged.connect(self.setIsoColor)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.img = pg.ImageItem() self.plot.addItem(self.img) # Isocurve draplotsg self.iso = pg.IsocurveItem(level=1000, pen=color_palette[2]) self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.plots.addItem(self.hist) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen=color_palette[2]) self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.isoLine.setValue(1000) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Monkey-patch the image to use our custom hover function. # This is generally discouraged (you should subclass ImageItem instead), # but it works for a very simple use like this. self.img.hoverEvent = self.imageHoverEvent self.img.translate(-0.5, -0.5) self.scalex = 1 self.scaley = 1 self.cx = 0 self.cy = 0 self.nplots = 0 self.table.setColumnCount(3) self.table.setRowCount(2) self.table.setColumnWidth(0, 200) self.table.setColumnWidth(1, 150) self.table.setColumnWidth(2, 150) self.table.setHorizontalHeaderLabels(['xvalue', 'yarray', 'zarray']) self.combox = NumericDataCombo(self.ap.df) self.comboy = NumericDataCombo(self.ap.df) self.comboz = NumericDataCombo(self.ap.df) self.table.setCellWidget(0, 0, self.combox) self.table.setCellWidget(0, 1, self.comboy) self.table.setCellWidget(0, 2, self.comboz) self.mk_buttons()
def addIsocurveROI(self, l): logger.debug(' ImageDisplay::addIsocurveROI(%s)' % l) self.isocurve = l if self.itemList['ISOCURVE'][0] is not None: self.removeIsocurveROI() roi = pg.IsocurveItem(data=self.imgData, level=l, pen=(3, 9)) roi.setZValue(10) self.addDisplayItem('ISOCURVE', roi)
def __init__(self, parent=None): # initialization of the superclass super(VideoMainWindow, self).__init__(parent) # setup the GUI self.setupUi(self) pg.setConfigOptions(background=pg.mkColor(0.5)) pg.setConfigOptions(foreground=pg.mkColor(0.3)) self.setWindowTitle('pyqtgraph example: Image Analysis') # Preserve plot area's aspect ration so image always scales correctly self.graphicsView.p1.setAspectLocked(True) # Use a file dialog to choose tiff stack file, mask = QFileDialog.getOpenFileName(self, 'Open a .tif/.tiff stack') # Read image data self.img_data_raw = volread(file) frames = self.img_data_raw.shape[0] # Transpose second and third axes (y, x) to correct orientation (x, y) self.img_data = np.transpose(self.img_data_raw, (0, 2, 1)) # Flip each frame in the left/right direction, expected to be up/down for i in range(frames): self.img_data[i] = np.fliplr(self.img_data[i]) self.ptr = 0 self.lastTime = ptime.time() self.fps = None self.timer = QtCore.QTimer() self.timer.timeout.connect(self.update) self.timer.start(50) # 50 ms =~ 20 fps # Levels/color control with a histogram # TODO try with a HistogramLUTWidget self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.graphicsView.img) self.graphicsView.widget.addItem(self.hist) # Isocurve drawing self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso.setParentItem(self.graphicsView.img) self.iso.setZValue(5) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Generate image data self.graphicsView.img.setImage(self.img_data[0]) # self.graphicsView.img.scale(self.img_data.shape[1], self.img_data.shape[2]) self.hist.setLevels(self.img_data.min(), self.img_data.max()) # build isocurves from smoothed data self.isoLine.setValue(self.img_data.max() / 2) self.iso.setData(pg.gaussianFilter(self.img_data[0], (2, 2)))
def setup_iso_curve(self, parent_image_item='red'): # # Isocurve drawing self._isocurve_item = pg.IsocurveItem(level=0.8, pen='g', axisOrder='row-major') self._isocurve_item.setZValue(5) # # Draggable line for setting isocurve level self._isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self._isoLine.setValue(0.8) self._isoLine.setZValue(1000) # bring iso line above contrast controls self._isoLine.sigDragged.connect(self.update_isocurve)
def plotIsoCurves(self, data, color=(255, 255, 255), rescale=True, levels=[0.5, 0.1, 0.01]): print(self.name) if data is not None: item = [] xmin, xmax, ymin, ymax = np.min(data[0]), np.max(data[0]), np.min( data[1]), np.max(data[1]) print(xmin, xmax, ymin, ymax) pen = pg.mkPen(*color, 255) num = 100.0 if 0: kde = gaussian_kde(data) X, Y = np.mgrid[xmin:xmax:complex(0, num), ymin:ymax:complex(0, num)] positions = np.vstack([X.ravel(), Y.ravel()]) Z = np.log10(np.reshape(kde(positions).T, X.shape)) print(Z) item = pg.ImageItem() item.setImage(Z, levels=(-10, 0)) item.translate(-num / 2 + (xmax + xmin) / 2, -num / 2 + (ymax + ymin) / 2) item.scale((xmax - xmin) / num, (ymax - ymin) / num) self.addItem(item) else: H, X, Y = np.histogram2d(data[0], data[1], bins=num, normed=True, range=[[xmin, xmax], [ymin, ymax]]) for l in levels: i = pg.IsocurveItem(H, level=l, pen=pen) i.scale((xmax - xmin) / num, (ymax - ymin) / num) i.translate( -num / 2 + (xmax + xmin) / 2 * num / (xmax - xmin), -num / 2 + (ymax + ymin) / 2 * num / (ymax - ymin)) item.append(i) self.addItem(i) if rescale: self.enableAutoRange() else: self.disableAutoRange() return item
def on_change_rect_roi(self, roi=None): # pyqtgraph axes are x,y, but data is stored in (frame, y,x, time) #roi_slice, roi_tr = self.rect_roi.getArraySlice(self.data, self.imview.getImageItem(), axes=(1,0)) #self.rect_plotdata.setData(self.spec_x_array, self.hyperspec_data[roi_slice].mean(axis=(0,1))+1) self.roi_img = self.rect_roi.getArrayRegion( data=self.data, img=self.imview.getImageItem(), axes=(1, 0)) #print(self.roi_img.shape) self.imview_roi.setImage(self.roi_img, axes=dict(x=1, y=0)) #, axes=dict(x=1,y=0)) #print("roi_slice", roi_slice) p, success = fitgaussian(self.roi_img) height, x, y, width_x, width_y, angle = p print(p) if success: fwhm_x = 2 * np.sqrt(2 * np.log(2)) * width_x fwhm_y = 2 * np.sqrt(2 * np.log(2)) * width_y self.info_label.setText( "height:{}, x: {}, y: {}, width_x: {}, width_y: {}, angle: {}". format(*p) + "\nfwhm {} {}".format(fwhm_x, fwhm_y)) ny, nx = self.roi_img.shape X, Y = np.mgrid[:ny, :nx] self.gaus_img = gaussian(*p)(X, Y) self.imview_gauss.setImage(self.gaus_img, axes=dict(x=1, y=0)) #, axes=dict(x=1,y=0)) if not hasattr(self, 'iso_curve'): self.iso_curve = pg.IsocurveItem(data=self.gaus_img, level=0.5) #, pen, axisOrder) self.imview_roi.getView().addItem(self.iso_curve) else: print(height * 0.5) self.iso_curve.setData(data=self.gaus_img.T, level=height * 0.5) self.iso_curve.setParentItem(self.imview_roi.getImageItem())
def draw_unfilled(self): lws, lss = self.extl(self.linewidths), self.extl(self.linestyles) pens = [ setup_pen_kw(penkw=dict(color=self.colors[i]), linestyle=lss[i], linewidth=lws[i]) for i in range(len(self.levels)) ] contours = [ pg.IsocurveItem(data=self.z, level=lvl, pen=pens[i]) for i, lvl in enumerate(self.levels) ] x0, y0, x1, y1 = self.x.min(), self.y.min(), self.x.max(), self.y.max() for contour in contours: contour.translate( x0, y0) # https://stackoverflow.com/a/51109935/6605826 contour.scale(int(round((x1 - x0) / np.shape(self.z)[0])), int(round((y1 - y0) / np.shape(self.z)[1]))) self.ax.addItem(contour)
def SetIsocurve(IM): global img, levels, curves, c, init_flag #img = pg.ImageItem(IM) ## generate empty curves curves = [] levels = np.linspace(IM.min(), IM.max(), nlevels) for i in range(len(levels)): v = levels[i] ## generate isocurve with cmap color selection pg_cmap = tuple(int(255 * x) for x in cmap(i)) pg_pen = pg.mkPen(pg_cmap) c = pg.IsocurveItem(level=v, pen=pg_pen) #c = pg.IsocurveItem(level=v, pen=(i, len(levels)*1.5)) c.setParentItem( imv3 ) ## make sure isocurve is always correctly displayed over image curves.append(c) init_flag = 0
def __init__(self, parent=None, globals=None, signals=None, **kwargs): self.config = {} self.globals = globals self.signals = signals self.parent = parent self.config_file = os.path.join('DigitalPulses\digital_schemes', 'display_widget_config.json') self.screen_size = QDesktopWidget().screenGeometry() self.roi_center = [200, 200] self.roi_size = [100, 100] self.all_plot_data = {'N': [], 'width': []} self.N_point_to_plot = 40 self.do_fit1D_x = True self.do_fit1D_y = True self.do_fit2D = False self.subs_bgnd = True self.n_sigmas = 3 self.image_data_to_display = np.array([('N', 0, 0, 0), ('Center', 0, 0, 0), ("Width", 0, 0, 0), ("N_small", 0, 0, 0), ('Center_full', 0, 0, 0)], dtype=[('Parameter', object), ('x', object), ('y', object), ('2D', object)]) self.load() self.globals['image_lower_left_corner'] = self.roi_center super(DisplayWidget, self).__init__(parent) self.initUI() self.iso = pg.IsocurveItem(pen='g') self.iso.setZValue(1000) self.iso.setParentItem(self.img) self.show() self.timer = QTimer(self) self.timer.setInterval(1000) self.timer.timeout.connect(self.routine)
def recToggled(self, b): """ Set the rec mode and update image """ self.recMode = b if b: # Enable the dthresh bar self.parent.slRec.setEnabled(True) # Make the isocurve plot item self.iso = pg.IsocurveItem(level=0.8, pen='w') self.vb = self.imageItem.getViewBox() self.vb.addItem(self.iso) self.iso.setZValue(1.) # Initialize the rec region pdensrFull = self.parent.loadDataFld('pdens', self.parent.strn1z) pdensr = self.parent.subsetData(pdensrFull) densFull = self.parent.loadDataFld('dens', self.parent.strn1z) dens = self.parent.subsetData(densFull) bdensFull = self.parent.loadDataFld('bdens', self.parent.strn1z) bdens = self.parent.subsetData(bdensFull) pdenstot = dens - bdens rat = self.parent.nandiv(pdensr, pdenstot) whrec = np.where((rat > self.parent.dthresh) & (rat < (1 - self.parent.dthresh)) & (bdens == 0)) my, mx = np.shape(bdens) self.parent.recReg = np.zeros((my, mx)) self.parent.recReg[whrec] = 1. if not b: self.parent.slRec.setEnabled(False) self.vb.removeItem(self.iso) self.updateImage()
def initUI(self): # A plot area (ViewBox + axes) for displaying the image plot_area = self.addPlot(lockAspect=True) # Item for displaying image data self.image_view = pg.ImageItem() plot_area.addItem(self.image_view) # Isocurve drawing self.iso_curve = pg.IsocurveItem(level=0.8, pen='g') self.iso_curve.setParentItem(self.image_view) self.iso_curve.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.image_view) self.addItem(self.hist) # Draggable line for setting isocurve level self.iso_line = pg.InfiniteLine(angle=0, movable=True, pen='g') self.iso_line.setValue(0.8) self.iso_line.setZValue(1000) # bring iso line above contrast controls self.iso_line.sigDragged.connect(self.updateIsoCurve) self.hist.vb.addItem(self.iso_line) self.hist.vb.setMouseEnabled(y=False) self.nextRow() self.line_plot = self.addPlot(colspan=2) self.line_plot.plot((0, 100), (0, 150)) self.roi = pg.LineSegmentROI([[0, 0], [100, 150]], pen=(5, 9)) self.roi.setZValue(10) plot_area.addItem(self.roi) self.roi.sigRegionChanged.connect(self.update_roi)
# A plot area (ViewBox + axes) for displaying the image p1 = win.addPlot(title="") # Item for displaying image data img = pg.ImageItem() p1.addItem(img) # Custom ROI for selecting an image region roi = pg.ROI([-8, 14], [6, 5]) roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) p1.addItem(roi) roi.setZValue(10) # make sure ROI is drawn above image # Isocurve drawing iso = pg.IsocurveItem(level=0.8, pen='g') iso.setParentItem(img) iso.setZValue(5) # Contrast/color control hist = pg.HistogramLUTItem() hist.setImageItem(img) win.addItem(hist) # Draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') hist.vb.addItem(isoLine) hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier isoLine.setValue(0.8) isoLine.setZValue(1000) # bring iso line above contrast controls
def __init__(self,parent=None,scaling_options=dict(scaled_xaxis=dict(label="",units=None,offset=0,scaling=1),scaled_yaxis=dict(label="",units=None,offset=0,scaling=1))): super(Viewer2D,self).__init__() #setting the gui self.ui=Ui_Form() self.ui.ROIs_widget=self.setup_Roi_widget() if parent is None: parent=QtWidgets.QWidget() self.ui.setupUi(parent)#it's a widget here self.ui.horizontalLayout.addWidget(self.ui.ROIs_widget) self.ui.ROIs_widget.setVisible(False) self.max_size_integrated = 200 self.scaling_options = copy.deepcopy(scaling_options) self.viewer_type='Data2D' #☺by default self.title="" self.parent=parent self.image = None self.isdata=edict(blue=False,green=False,red=False) self.color_list=[(255,0,0),(0,255,0),(0,0,255),(14,207,189),(207,14,166),(207,204,14)] self.image_widget = ImageWidget() self.ui.plotitem = self.image_widget.plotitem # for backward compatibility self.ui.splitter_VLeft.replaceWidget(0, self.ui.graphicsView) self.autolevels=False self.ui.auto_levels_pb.clicked.connect(self.set_autolevels) self.scaled_yaxis=AxisItem_Scaled('right') self.scaled_xaxis=AxisItem_Scaled('top') self.image_widget.view.sig_double_clicked.connect(self.double_clicked) self.image_widget.plotitem.layout.addItem(self.scaled_xaxis, *(1,1)) self.image_widget.plotitem.layout.addItem(self.scaled_yaxis, *(2,2)) self.scaled_xaxis.linkToView(self.image_widget.view) self.scaled_yaxis.linkToView(self.image_widget.view) self.set_scaling_axes(self.scaling_options) self.image_widget.plotitem.vb.setAspectLocked(lock=True, ratio=1) self.ui.img_red = ImageItem() self.ui.img_green = ImageItem() self.ui.img_blue = ImageItem() #self.ui.img_red.sig_double_clicked.connect(self.double_clicked) self.ui.img_red.setCompositionMode( QtGui.QPainter.CompositionMode_Plus ) self.ui.img_green.setCompositionMode( QtGui.QPainter.CompositionMode_Plus ) self.ui.img_blue.setCompositionMode( QtGui.QPainter.CompositionMode_Plus ) self.ui.img_red.setOpts(axisOrder='row-major') self.ui.img_green.setOpts(axisOrder='row-major') self.ui.img_blue.setOpts(axisOrder='row-major') #selection area checkbox self.ui.blue_cb.setVisible(True) self.ui.blue_cb.setChecked(True) self.ui.blue_cb.clicked.connect(self.update_selection_area_visibility) self.ui.green_cb.setVisible(True) self.ui.green_cb.setChecked(True) self.ui.green_cb.clicked.connect(self.update_selection_area_visibility) self.ui.red_cb.setVisible(True) self.ui.red_cb.clicked.connect(self.update_selection_area_visibility) self.ui.red_cb.setChecked(True) self.image_widget.plotitem.addItem(self.ui.img_red) self.image_widget.plotitem.addItem(self.ui.img_green) self.image_widget.plotitem.addItem(self.ui.img_blue) self.ui.graphicsView.setCentralItem(self.image_widget.plotitem) ##self.ui.graphicsView.setCentralItem(self.image_widget.plotitem) #axis=pg.AxisItem('right',linkView=self.image_widget.view) #self.ui.graphicsView.addItem(axis) self.ui.aspect_ratio_pb.clicked.connect(self.lock_aspect_ratio) self.ui.aspect_ratio_pb.setChecked(True) #histograms histo_layout = QtWidgets.QHBoxLayout() self.ui.widget_histo.setLayout(histo_layout) self.ui.histogram_red=pg.HistogramLUTWidget() self.ui.histogram_red.setImageItem(self.ui.img_red) self.ui.histogram_green=pg.HistogramLUTWidget() self.ui.histogram_green.setImageItem(self.ui.img_green) self.ui.histogram_blue=pg.HistogramLUTWidget() self.ui.histogram_blue.setImageItem(self.ui.img_blue) histo_layout.addWidget(self.ui.histogram_red) histo_layout.addWidget(self.ui.histogram_green) histo_layout.addWidget(self.ui.histogram_blue) Ntick=3 colors_red =[(int(r),0,0) for r in pg.np.linspace(0,255,Ntick)] colors_green=[(0,int(g),0) for g in pg.np.linspace(0,255,Ntick)] colors_blue=[(0,0,int(b)) for b in pg.np.linspace(0,255,Ntick)] cmap_red = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_red) cmap_green = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_green) cmap_blue = pg.ColorMap(pos=pg.np.linspace(0.0, 1.0, Ntick), color=colors_blue) self.ui.histogram_red.gradient.setColorMap(cmap_red) self.ui.histogram_green.gradient.setColorMap(cmap_green) self.ui.histogram_blue.gradient.setColorMap(cmap_blue) self.ui.histogram_red.setVisible(False) self.ui.histogram_green.setVisible(False) self.ui.histogram_blue.setVisible(False) self.ui.Show_histogram.clicked.connect(self.show_hide_histogram) #ROI selects an area and export its bounds as a signal self.ui.ROIselect=pg.RectROI([0,0],[10,10],centered=True,sideScalers=True) self.image_widget.plotitem.addItem(self.ui.ROIselect) self.ui.ROIselect.setVisible(False) self.ui.ROIselect.sigRegionChangeFinished.connect(self.selected_region_changed) self.ui.ROIselect_pb.clicked.connect(self.show_ROI_select) ## Isocurve drawing self.ui.iso = pg.IsocurveItem(level=0.8, pen='g',axisOrder='row-major') self.ui.iso.setParentItem(self.ui.img_red) self.ui.iso.setZValue(5) ## Draggable line for setting isocurve level self.ui.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.ui.histogram_red.vb.addItem(self.ui.isoLine) self.ui.histogram_red.vb.setMouseEnabled(y=False) # makes user interaction a little easier self.ui.isoLine.setValue(0.8) self.ui.isoLine.setZValue(1000) # bring iso line above contrast controls self.ui.isocurve_pb.clicked.connect(self.show_hide_iso) self.ui.isocurve_pb.setChecked(False) self.show_hide_iso() # build isocurves from smoothed data self.ui.isoLine.sigDragged.connect(self.updateIsocurve) ##crosshair self.ui.crosshair=Crosshair(self.image_widget.plotitem) self.ui.crosshair_H_blue = self.ui.Lineout_H.plot(pen="b") self.ui.crosshair_H_green = self.ui.Lineout_H.plot(pen="g") self.ui.crosshair_H_red = self.ui.Lineout_H.plot(pen="r") self.ui.crosshair_V_blue = self.ui.Lineout_V.plot(pen="b") self.ui.crosshair_V_green = self.ui.Lineout_V.plot(pen="g") self.ui.crosshair_V_red = self.ui.Lineout_V.plot(pen="r") self.ui.crosshair.crosshair_dragged.connect(self.update_crosshair_data) self.ui.crosshair_pb.clicked.connect(self.crosshairClicked) self.crosshairClicked() #flipping self.ui.FlipUD_pb.clicked.connect(self.update_image_flip) self.ui.FlipLR_pb.clicked.connect(self.update_image_flip) self.ui.rotate_pb.clicked.connect(self.update_image_flip) ## ROI stuff self.ui.RoiCurve_H=edict() self.ui.RoiCurve_V=edict() self.ui.RoiCurve_integrated=edict() self.data_integrated_plot= edict() self.ui.ROIs=OrderedDict([]) self.ui.roiBtn.clicked.connect(self.roiClicked) self.data_to_export=OrderedDict(data0D=OrderedDict(),data1D=OrderedDict(),data2D=OrderedDict()) self._x_axis=None self._y_axis=None self.x_axis_scaled=None self.y_axis_scaled=None self.ui.Ini_plot_pb.clicked.connect(self.ini_plot) params = [ROIScalableGroup(name="ROIs")] self.roi_settings=Parameter.create(title='ROIs Settings', name='roissettings', type='group', children=params) self.ui.ROI_Tree.setParameters(self.roi_settings, showTop=False) self.roi_settings.sigTreeStateChanged.connect(self.roi_tree_changed) self.ui.save_ROI_pb.clicked.connect(self.save_ROI) self.ui.load_ROI_pb.clicked.connect(self.load_ROI) #self.roiClicked() ## initialize roi plot to correct shape / visibility ##splitter try: self.ui.splitter_VLeft.splitterMoved[int,int].connect(self.move_right_splitter) self.ui.splitter_VRight.splitterMoved[int,int].connect(self.move_left_splitter) except: pass
def __init__(self, data, parent=None): super().__init__(parent) self.lut = np.empty((256, 3), dtype=np.uint8) self.ct = CMap().load_ct('blue_orange') self.ct_name = 'blue_orange' self.gamma = 1 self.cmap_piecewise = False # make image view self.view = ImageBase(data) self.imageItem = self.view.img # preprocess image image = data.values self.img_min = image.min() self.img_max = image.max() image = (image - self.img_min) / (self.img_max - self.img_min) # make isocurve self.iso = pg.IsocurveItem(pen=pg.mkPen(color='g')) self.iso.setTransform(self.imageItem.transform()) self.iso_enabled = True # calculate histogram self.hist, self.bin_edges = np.histogram(image, 256) self.hist = self.hist / self.hist.sum() self.bin_midpoints = self.bin_edges[:-1] + np.diff(self.bin_edges) / 2 # color bar self.color_bar_coords = pg.PlotItem() self.color_bar_coords.hideAxis('left') height = 0.2 * (self.bin_midpoints.max() - self.bin_midpoints.min()) width = self.bin_midpoints.max() - self.bin_midpoints.min() x = self.bin_midpoints.min() y = 0 self.color_bar = QtGui.QGraphicsRectItem( QtCore.QRectF(x - 0.5, y - 0.5, width + 1, height + 1)) self.gradient = QtGui.QLinearGradient(QtCore.QPointF(x, 0), QtCore.QPointF(width, 0)) self.gradient.setFinalStop(width, 0) self.gradient.setStops([(i / 255, QtGui.QColor(*tuple(self.ct[i]))) for i in range(256)]) self.color_bar.setBrush(QtGui.QBrush(self.gradient)) self.color_bar_line = pg.InfiniteLine(bounds=(self.bin_edges[0], self.bin_edges[-1]), movable=True) # histogram self.histogram = pg.PlotItem() self.hist_data = self.histogram.plot(self.bin_midpoints, self.hist) # histogram line and position label self.hist_line = pg.InfiniteLine(bounds=(self.bin_edges[0], self.bin_edges[-1]), movable=True) self.hist_line.setZValue(0) self.hist_line_label = pg.TextItem(anchor=(0.5, 0.5)) self.hist_line_label.setPos(self.bin_midpoints[128], self.hist.max()) # connect the colorbar line and histogram line def hist_callback(dragged_line, other_line, iso, _=None): other_line.setValue(dragged_line.value()) iso.setLevel(dragged_line.value()) self.hist_line.sigDragged.connect( partial(hist_callback, self.hist_line, self.color_bar_line, self.iso)) self.color_bar_line.sigDragged.connect( partial(hist_callback, self.color_bar_line, self.hist_line, self.iso)) # add menus to the histogram line self.histogram.vb.menu.addSeparator() self.add_point_action: QtWidgets.QAction = self.histogram.vb.menu.addAction( 'Add point') self.rm_point_action: QtWidgets.QAction = self.histogram.vb.menu.addAction( 'Remove point') self.rm_point_action.setEnabled(False) self.add_point_action.triggered.connect(self.add_piecewise_point) # histogram piecewise line self.hist_graph = Graph(pos=np.array( [[self.bin_midpoints[0], self.hist.min()], [self.bin_midpoints[-1], self.hist.max()]]), adj=np.array([[0, 1]])) self.hist_graph.setVisible(False) # histogram power law line self.hist_cnorm = (np.arange(len(self.hist)) / (len(self.hist) - 1))**self.gamma self.hist_cnorm_data = self.histogram.plot( self.bin_midpoints, self.hist_cnorm * self.hist.max()) # set data self.imageItem.setImage(image, lut=self.lut) self.iso.setData(image) # add items self.ci.addItem(self.view, row=0, col=0, rowspan=2) self.ci.addItem(self.color_bar_coords, row=0, col=1) self.ci.addItem(self.histogram, row=1, col=1) self.view.addItem(self.iso) # self.color_bar_coords.addItem(self.color_bar_element) self.color_bar_coords.addItem(self.color_bar) self.color_bar_coords.addItem(self.color_bar_line) self.histogram.addItem(self.hist_line) self.histogram.addItem(self.hist_graph) self.histogram.addItem(self.hist_line_label) # Mouse interaction self.mousepnt: Union[None, QtCore.QPointF] = QtCore.QPointF(0, 0) # Set events self.hist_hover_proxy = pg.SignalProxy( self.histogram.scene().sigMouseMoved, rateLimit=20, slot=self.hist_hover_handler) self.histogram.setXLink(self.color_bar_coords) self.hist_graph.color_map_changed.connect(self.update) self.sceneObj.sigMouseClicked.connect(self.mouseClickEvent) self.resize(800, 400) self.color_bar_coords.autoRange() self.update()
def __init__(self): # Load an instance of the Digitizer control object ## Load the ui file for GUI QtGui.QMainWindow.__init__(self) Ui_MainWindow.__init__(self) self.setupUi(self) ## Link the buttons self.RecMode_button.clicked.connect(self.setAcquisitionParameters) self.RecSS_button.clicked.connect(self.setAcquisitionParameters) self.RecAvg_button.clicked.connect(self.setAcquisitionParameters) # Digitizer record parameters #self.Nsamples_button.valueChanged.connect(self.setAcquisitionParameters) self.Nrecords_button.valueChanged.connect(self.setAcquisitionParameters) #self.ChA_button.clicked.connect(self.setAcquisitionParameters) #self.ChB_button.clicked.connect(self.setAcquisitionParameters) self.TrigExt_button.clicked.connect(self.setAcquisitionParameters) #self.TrigA_button.clicked.connect(self.setAcquisitionParameters) #self.TrigB_button.clicked.connect(self.setAcquisitionParameters) # Metadata record parameters # Voltages self.Vtofmcpf_button.valueChanged.connect(self.setMetadata) self.Vgrid_button.valueChanged.connect(self.setMetadata) self.Vtofdtube_button.valueChanged.connect(self.setMetadata) self.Vrep_button.valueChanged.connect(self.setMetadata) self.Vext_button.valueChanged.connect(self.setMetadata) self.Vcorr_button.valueChanged.connect(self.setMetadata) self.Vvmimcpf_button.valueChanged.connect(self.setMetadata) self.Vvmimcpb_button.valueChanged.connect(self.setMetadata) self.Vph_button.valueChanged.connect(self.setMetadata) #delay value for single tof (no dscan) self.Singledelay_button.valueChanged.connect(self.setMetadata) # Comments on the scan self.Comments_button.textChanged.connect(self.setMetadata) # Path for file saving self.FilePath_button.textChanged.connect(self.setAcquisitionParameters) self.FilePath='L:/atto/labdata/2016/20160411_Isopropanol' self.FilePathBrowser_button.clicked.connect(self.setDir) # # #self.DscanMode_button.stateChanged.connect(self.setAcquisitionParameters) self.DscanStart_button.valueChanged.connect(self.setAcquisitionParameters) self.DscanStop_button.valueChanged.connect(self.setAcquisitionParameters) self.DscanStep_button.valueChanged.connect(self.setAcquisitionParameters) #self.FilePath_button.textChanged.connect(self.setAcquisitionParameters) self.Delayfile=[] self.DelayfilePath='' self.DelayfileBrowser_button.clicked.connect(self.setDelayfile) ## Start/Stop self.StartAcq_button.clicked.connect(self.StartAcquisition) self.StopAcq_button.clicked.connect(self.StopAcquisition) print 'GUI loaded' f.write('GUI loaded') self.MetadataDict=[] ##Display graphs self.ViewWin =pg.LayoutWidget() # Main layout self.ViewWin.setWindowTitle('VMI Viewer') self.graph = pg.GraphicsLayoutWidget() self.ViewWin.addWidget(self.graph,row=0,col=2,rowspan=17,colspan=5) self.ViewWin.resize(1250, 500) print 'GUI loaded' f.write('GUI loaded') self.Cartplot=self.graph.addPlot(row=0,col=0,rowspan=2) self.Cartplot.setLabel(axis='left',text='Py (pixel)') self.Cartplot.setLabel(axis='bottom',text='Py (pixel)') ## Item for displaying image data self.img = pg.ImageItem() self.Cartplot.addItem(self.img) self.Cartplot.setAspectLocked(True,ratio=1) ## Custom ROI for selecting an image region self.roi = pg.CircleROI([100, 100], [50, 50]) # first vector =[x0,y0], second vector =[lx,ly] # self.roi.addScaleHandle([0.5, 1], [0.5, 0.5]) # self.roi.addScaleHandle([0, 0.5], [0.5, 0.5]) self.Cartplot.addItem(self.roi) self.roi.setZValue(10) # make sure ROI is drawn above image self.roi.sigRegionChanged.connect(self.updatePlot) print 'GUI loaded3' f.write('GUI loaded') ## Isocurve drawing self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso.setParentItem(self.img) self.iso.setZValue(5) ## Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.graph.addItem(self.hist,row=0,col=1,rowspan=2) ## Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Another plot area for displaying ROI data self.graph.nextRow() self.Polplot = self.graph.addPlot(row=0,col=3,colspan=2) self.Polplot.setLabel(axis='left',text='Radius (px)') self.Polplot.setLabel(axis='bottom',text='Angle ()') self.imgpol = pg.ImageItem() self.Polplot.addItem(self.imgpol) self.histpol = pg.HistogramLUTItem() self.histpol.setImageItem(self.imgpol) self.graph.addItem(self.histpol,row=0,col=5) self.histpol.setMaximumWidth(100) self.roipol = pg.ROI([10, 10], [5, 5]) # first vector =[x0,y0], second vector =[lx,ly] self.roipol.addScaleHandle([0.5, 1], [0.5, 0.5]) self.roipol.addScaleHandle([0, 0.5], [0.5, 0.5]) self.Polplot.addItem(self.roipol) self.roipol.setZValue(10) # make sure ROI is drawn above image self.roipol.sigRegionChanged.connect(self.updatePlot) self.graph.nextCol() self.RadialDistplot = self.graph.addPlot(row=1,col=3,colspan=3) self.RadialDistplot.setLabel(axis='left',text='Signal (arb. u)') self.RadialDistplot.setLabel(axis='bottom',text='Momentum (pixel)') #self.p2.setMaximumHeight(250) #Initialize the image self.initimg = np.random.normal(size=(400, 400)) self.initimg[380:420, 380:420] += 2. self.initimg = pg.gaussianFilter(self.initimg, (3, 3)) self.initimg += np.random.normal(size=(400, 400)) * 0.1 self.scan=VMITraceProcessing(self.initimg) self.activeimg=self.scan.imgcart_raw self.img.setImage(self.activeimg) self.img.scale(1,1) self.img.translate(0, 0) self.hist.setLevels(self.activeimg.min(), self.activeimg.max()) self.Cartplot.autoRange() print 'GUI loaded4' f.write('GUI loaded') #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0],self.roi.size()) #self.imgpol.setImage(self.scan.imgpol).setLabel(axis='left',text='Py (pixel)') self.Cartplot.setLabel(axis='bottom',text='Py (pixel)') self.img.setImage(self.activeimg) self.img.scale(1,1) self.img.translate(0, 0) self.hist.setLevels(self.activeimg.min(), self.activeimg.max()) self.Polplot.autoRange() self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0],self.roi.size()) self.imgpol.setImage(self.scan.imgpol) self.ViewWin.show() ## Init the frame grabber #self.myVAQD=VMIcrtl_ext.VMIcrtl() f.write('init framegrabber done') print 'init framegrabber done'
data[:, 15:16, 15:17] += 1 win = pg.GraphicsLayoutWidget(show=True) win.setWindowTitle('pyqtgraph example: Isocurve') vb = win.addViewBox() img = pg.ImageItem(data[0]) vb.addItem(img) vb.setAspectLocked() ## generate empty curves curves = [] levels = np.linspace(data.min(), data.max(), 10) for i in range(len(levels)): v = levels[i] ## generate isocurve with automatic color selection c = pg.IsocurveItem(level=v, pen=(i, len(levels) * 1.5)) c.setParentItem( img) ## make sure isocurve is always correctly displayed over image c.setZValue(10) curves.append(c) ## animate! ptr = 0 imgLevels = (data.min(), data.max() * 2) def update(): global data, curves, img, ptr, imgLevels ptr = (ptr + 1) % data.shape[0] data[ptr] img.setImage(data[ptr], levels=imgLevels)
def __init__(self, title, **kwargs): super().__init__(title, **kwargs) self.setMinimumHeight(550) self.setMinimumWidth(550) self.axsumy = self.plots.addPlot(title="") self.axsumy.setFixedWidth(100) self.sumy = self.axsumy.plot() self.sumy_fit = self.axsumy.plot( pen=pg.mkPen(style=QtCore.Qt.DashLine, color=color_palette[1])) self.img = pg.ImageItem() self.aximg = self.plots.addPlot(title="") self.aximg.addItem(self.img) self.axsumy.setYLink(self.aximg) # Isocurve draplotsg self.iso = pg.IsocurveItem(level=1000, pen=color_palette[2]) self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.plots.addItem(self.hist) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen=color_palette[2]) self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.isoLine.setValue(1000) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Monkey-patch the image to use our custom hover function. # This is generally discouraged (you should subclass ImageItem instead), # but it works for a very simple use like this. self.img.hoverEvent = self.imageHoverEvent self.plots.nextRow() self.plots.nextColumn() self.axsumx = self.plots.addPlot() self.axsumx.setFixedHeight(100) self.axsumx.setXLink(self.aximg) self.sumx = self.axsumx.plot() self.sumx_fit = self.axsumx.plot( pen=pg.mkPen(style=QtCore.Qt.DashLine, color=color_palette[1])) self.table.setMinimumHeight(85) self.img.translate(-0.5, -0.5) self.scalex = 1 self.scaley = 1 self.cx = 0 self.cy = 0
def __init__(self): #TemplateBaseClass.__init__(self) # Initialize Camera tlFactory = pylon.TlFactory.GetInstance() devices=tlFactory.EnumerateDevices print devices()[1].GetModelName() self.VMIcrtl = pylon.InstantCamera(tlFactory.CreateDevice(devices()[1])) #self.VMIcrtl.open() ## initialize camera acquisition settings self.NbAcq=10 self.NbAcquired=0 self.Threshold=0 #self.VMIcrtl=VMIcrtl_ext.VMIcrtl(); #Init semaphore self.mutex = QtCore.QMutex() #Initialize window self.win =pg.LayoutWidget() # Main layout self.win.setWindowTitle('VMI GUI') #Loadfile button self.loadbutton=QtGui.QPushButton('Load Data') self.loadbutton.clicked.connect(self.OpenFile) #Take reference button self.refbutton=QtGui.QPushButton('Save Reference') self.refbutton.clicked.connect(self.SaveReference) self.Prevbutton=QtGui.QPushButton('Preview') self.Prevbutton.clicked.connect(self.PrevAcq) self.FlatBGbutton=QtGui.QPushButton('Flat Corr') self.FlatBGbutton.clicked.connect(self.LoadFlatCorrection) self.Startbutton=QtGui.QPushButton('Start') self.Startbutton.clicked.connect(self.StartAcq) self.Stopbutton=QtGui.QPushButton('Stop') self.Stopbutton.clicked.connect(self.StopAcq) #Checkboxes self.checkbox0=QtGui.QCheckBox('Reference') #View the data feeded by the digitizer self.checkbox0.clicked.connect(self.updatePlot) self.checkbox1=QtGui.QCheckBox('Refresh Viewer') #View the data feeded by the digitizer self.checkbox1.clicked.connect(self.StreamOnOff) self.checkbox1.setEnabled(False) self.checkbox2=QtGui.QCheckBox('Norm Radial Distribution') self.checkbox2.clicked.connect(self.NormalizeDscan) self.checkbox3=QtGui.QCheckBox('Norm TOF') self.checkbox3.clicked.connect(self.NormalizeTOF) # Center control buttons self.cxlabel=QtGui.QLabel('Center X pos') self.spinbox1=QtGui.QDoubleSpinBox() self.spinbox1.valueChanged.connect(self.updateROI) self.spinbox1.setMaximum(1000.0) self.spinbox1.setMinimum(0.0) self.spinbox1.setValue(204.0) self.cylabel=QtGui.QLabel('Center Y pos') self.spinbox2=QtGui.QDoubleSpinBox() self.spinbox2.valueChanged.connect(self.updateROI) self.spinbox2.setMaximum(1000.0) self.spinbox2.setMinimum(0.0) self.spinbox2.setValue(197.0) #background removal buttons self.BGbutton=QtGui.QPushButton('Load XUV BG') self.BGbutton.clicked.connect(self.LoadBG) self.bglabel=QtGui.QLabel('BG removal amount') self.spinbox3=QtGui.QDoubleSpinBox() self.spinbox3.valueChanged.connect(self.updateBG) self.spinbox3.setMaximum(10.0) self.spinbox3.setMinimum(0.0) self.spinbox3.setValue(1.0) self.checkbox4=QtGui.QCheckBox('BG removed ON/OFF') self.checkbox4.clicked.connect(self.updateBG) self.checkbox5=QtGui.QCheckBox('pixels to energy') self.checkbox5.clicked.connect(self.updatePlot) self.EnCaliblabel=QtGui.QLabel('Energy Calibration coeff (x1e-6)') self.spinbox4=QtGui.QDoubleSpinBox() self.spinbox4.valueChanged.connect(self.updatePlot) self.spinbox4.setMaximum(10000.0) self.spinbox4.setMinimum(0.0) self.spinbox4.setValue(894.30) self.NAcqLabel=QtGui.QLabel('Number of acquisitions') self.spinbox5=QtGui.QSpinBox() self.spinbox5.valueChanged.connect(self.UpdateParameters) self.spinbox5.setMaximum(100000) self.spinbox5.setMinimum(0) self.spinbox5.setValue(50) self.checkbox6=QtGui.QCheckBox('Dscan') self.Dstart=QtGui.QLabel('Dstart') self.spinbox6=QtGui.QDoubleSpinBox() #self.spinbox6.valueChanged.connect(self.updatePlot) self.spinbox6.setMaximum(80.0) self.spinbox6.setMinimum(0.0) self.spinbox6.setValue(0.0) self.Dstop=QtGui.QLabel('Dstop') self.spinbox7=QtGui.QDoubleSpinBox() self.spinbox7.setMaximum(80.0) self.spinbox7.setMinimum(0.0) self.spinbox7.setValue(80.0) self.Dstep=QtGui.QLabel('Dstep') self.spinbox8=QtGui.QDoubleSpinBox() self.spinbox8.setMaximum(80.0) self.spinbox8.setMinimum(0.0) self.spinbox8.setValue(1.0) self.ThLabel=QtGui.QLabel('Threshold') self.spinbox9=QtGui.QSpinBox() self.spinbox9.valueChanged.connect(self.UpdateParameters) self.spinbox9.setMaximum(5000) self.spinbox9.setMinimum(1) self.spinbox9.setValue(1) self.checkbox7=QtGui.QCheckBox('Median Filter') self.checkbox7.clicked.connect(self.UpdateParameters) self.checkbox8=QtGui.QCheckBox('Single Shot rec') self.checkbox8.clicked.connect(self.UpdateParameters) ## Trigger mode self.checkbox10=QtGui.QCheckBox('Trigger ON/OFF') self.checkbox10.clicked.connect(self.setTriggerMode) self.ExpoLabel=QtGui.QLabel(' Exposure (us)') self.spinbox10=QtGui.QSpinBox() self.spinbox10.valueChanged.connect(self.UpdateParameters) self.spinbox10.setMaximum(990) self.spinbox10.setMinimum(100) self.spinbox10.setValue(500.0) ## save path self.Savepath='20161130_0000.dat' self.SaveLabel=QtGui.QLabel('Save path:') self.Savepathbutton=QtGui.QPushButton('...') self.Savepathedit=QtGui.QLineEdit(self.Savepath) self.Savepathedit.textChanged.connect(self.UpdateParameters) self.Savepathbutton.clicked.connect(self.setDir) ## Progress bars self.DprogressLabel=QtGui.QLabel('Dscan progress') self.Dprogressbar=QtGui.QProgressBar() self.Dprogressbar.setRange(0,100) self.progressLabel=QtGui.QLabel('Acq progress') self.progressbar=QtGui.QProgressBar() self.progressbar.setRange(0,100) self.infos=QtGui.QLabel('Center Position : X0= 0.0 / Y0= 0.0 ; ROI radius = 100.0 px') self.graph = pg.GraphicsLayoutWidget() # GUI layout self.win.addWidget(self.loadbutton,row=0,col=0,colspan=1) self.win.addWidget(self.refbutton,row=1,col=0,colspan=1) self.win.addWidget(self.checkbox0,row=2,col=0,colspan=1) self.win.addWidget(self.checkbox1,row=3,col=0,colspan=1) self.win.addWidget(self.checkbox2,row=4,col=0,colspan=1) self.win.addWidget(self.checkbox3,row=5,col=0,colspan=1) self.win.addWidget(self.BGbutton,row=6,col=0) self.win.addWidget(self.checkbox4,row=7,col=0) self.win.addWidget(self.bglabel,row=8,col=0) self.win.addWidget(self.spinbox3,row=9,col=0) #self.win.addWidget(self.triggerlabel,row=11,col=2,colspan=1) self.win.addWidget(self.checkbox10,row=11,col=2,colspan=1) self.win.addWidget(self.ExpoLabel,row=12,col=2,colspan=1) self.win.addWidget(self.spinbox10,row=13,col=2,colspan=1) self.win.addWidget(self.cxlabel,row=10,col=0) self.win.addWidget(self.spinbox1,row=11,col=0) self.win.addWidget(self.cylabel,row=12,col=0) self.win.addWidget(self.spinbox2,row=13,col=0) self.win.addWidget(self.checkbox5,row=14,col=0) self.win.addWidget(self.EnCaliblabel,row=15,col=0) self.win.addWidget(self.spinbox4,row=16,col=0) self.win.addWidget(self.Prevbutton,row=0,col=1,colspan=1) self.win.addWidget(self.FlatBGbutton,row=0,col=2,colspan=1) self.win.addWidget(self.Startbutton,row=1,col=1,colspan=1) self.win.addWidget(self.Stopbutton,row=1,col=2,colspan=1) self.win.addWidget(self.NAcqLabel,row=2,col=1) self.win.addWidget(self.spinbox5,row=3,col=1,colspan=1) self.win.addWidget(self.checkbox7,row=4,col=1,colspan=1) self.win.addWidget(self.checkbox8,row=5,col=1,colspan=1) self.win.addWidget(self.ThLabel,row=2,col=2) self.win.addWidget(self.spinbox9,row=3,col=2,colspan=1) self.win.addWidget(self.checkbox6,row=4,col=2,colspan=1) self.win.addWidget(self.Dstart,row=5,col=2,colspan=1) self.win.addWidget(self.spinbox6,row=6,col=2,colspan=1) self.win.addWidget(self.Dstop,row=7,col=2,colspan=1) self.win.addWidget(self.spinbox7,row=8,col=2,colspan=1) self.win.addWidget(self.Dstep,row=9,col=2,colspan=1) self.win.addWidget(self.spinbox8,row=10,col=2,colspan=1) self.win.addWidget(self.SaveLabel,row=14,col=1,colspan=1) self.win.addWidget(self.Savepathbutton,row=14,col=2,colspan=1) self.win.addWidget(self.Savepathedit,row=15,col=1,colspan=2) self.win.addWidget(self.progressLabel,row=17,col=0,colspan=1) self.win.addWidget(self.progressbar,row=17,col=1,colspan=2) self.win.addWidget(self.DprogressLabel,row=18,col=0,colspan=1) self.win.addWidget(self.Dprogressbar,row=18,col=1,colspan=2) self.win.addWidget(self.infos,row=18,col=3) self.win.addWidget(self.graph,row=0,col=3,rowspan=18,colspan=6) self.win.resize(1500, 1000) #self.win.show() # Graph layout for cartesian image self.p1 =self.graph.addPlot(row=0,col=0,rowspan=2) self.p1.setLabel(axis='left',text='Py (pixel)') self.p1.setLabel(axis='bottom',text='Py (pixel)') # Item for displaying image data self.img = pg.ImageItem() self.p1.addItem(self.img) self.p1.setAspectLocked(True,ratio=1) # Custom ROI for selecting an image region self.roi = pg.CircleROI([100, 100], [50, 50]) # first vector =[x0,y0], second vector =[lx,ly] # self.roi.addScaleHandle([0.5, 1], [0.5, 0.5]) # self.roi.addScaleHandle([0, 0.5], [0.5, 0.5]) self.p1.addItem(self.roi) self.roi.setZValue(10) # make sure ROI is drawn above image self.roi.sigRegionChanged.connect(self.updatePlot) # Isocurve drawing self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.graph.addItem(self.hist,row=0,col=1,rowspan=2) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled(y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Another plot area for displaying ROI data self.graph.nextRow() self.p0 = self.graph.addPlot(row=0,col=3,colspan=2) self.p0.setLabel(axis='left',text='Radius (px)') self.p0.setLabel(axis='bottom',text='Angle (°)') self.imgpol = pg.ImageItem() self.p0.addItem(self.imgpol) self.histpol = pg.HistogramLUTItem() self.histpol.setImageItem(self.imgpol) self.graph.addItem(self.histpol,row=0,col=5) self.histpol.setMaximumWidth(100) self.graph.nextCol() self.p2 = self.graph.addPlot(row=1,col=3,colspan=2) self.p2.setLabel(axis='left',text='Signal (arb. u)') self.p2.setLabel(axis='bottom',text='Momentum (pixel)') self.graph.nextRow() self.p3 = self.graph.addPlot(row=3,col=0,colspan=5) self.p3.setLabel(axis='bottom',text='Delay (fs)') self.p3.setLabel(axis='left',text='Momentum (px)') self.Dscan = pg.ImageItem() self.p3.addItem(self.Dscan) self.histpol2 = pg.HistogramLUTItem() self.histpol2.setImageItem(self.Dscan) self.graph.addItem(self.histpol2,row=3,col=5) self.histpol2.setMaximumWidth(100) self.roipol = pg.ROI([50, 1], [30, 150]) # first vector =[x0,y0], second vector =[lx,ly] self.roipol.addScaleHandle([0.5, 1], [0.5, 0.5]) self.roipol.addScaleHandle([0, 0.5], [0.5, 0.5]) self.p0.addItem(self.roipol) self.roipol.setZValue(10) # make sure ROI is drawn above image self.roipol.sigRegionChanged.connect(self.updatePlot) #Initialize the image self.initimg = np.random.normal(size=(1000, 1000)) self.initimg[380:420, 380:420] += 2. self.initimg = pg.gaussianFilter(self.initimg, (3, 3)) self.initimg += np.random.normal(size=(1000, 1000)) * 0.1 self.scan=VMITraceProcessing(self.initimg) self.activeimg=self.scan.imgcart_raw self.img.setImage(self.activeimg) self.img.scale(1,1) self.img.translate(0, 0) self.hist.setLevels(self.activeimg.min(), self.activeimg.max()) self.p1.autoRange() #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0],self.roi.size()) #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0]) self.scan.DefineCenter([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0]) self.scan.ImgCart2Pol(self.roi.size()) print self.roi.size()[0], 'test' #self.scan.ImgCart2Pol([self.roi.size()[0]]) self.imgpol.setImage(self.scan.imgpol) #self.imgDscan=np.zeros((1000,80)) # Infos from filedata self.pname='' self.pnameBG='' self.fname='' # Initialise useful variables self.FlatCorrimg=np.zeros((1000,1000)) self.BGimg=np.zeros((1000,1000)) self.normDscan=[] self.normTOF=[] self.refRadialDist=[] self.refx0=[] self.refy0=[] self.cx=[] self.cy=[] #Load previous config if available: isconfig=glob.glob('config.npz') # if isconfig!=[]: # # conf=np.load('config.npz') # self.Threshold=conf['Threshold'] # self.NbAcq=conf['NbAcq'] # self.FlatCorrimg=conf['Flatcorr'] # self.SavePath=conf['Savepath'] #Instanciate acquisition Thread self.thread=[] #Timer object for realtime data self.timer=QtCore.QTimer() self.timer.timeout.connect(self.updatePlot) #Update the gui self.win.show()
def __init__(self): #TemplateBaseClass.__init__(self) self.win = pg.LayoutWidget() # Main layout self.win.setWindowTitle('VMI Viewer') #Loadfile button self.loadbutton = QtGui.QPushButton('Load Data') self.loadbutton.clicked.connect(self.OpenFile) #Take reference button self.refbutton = QtGui.QPushButton('Save Reference') self.refbutton.clicked.connect(self.SaveReference) #Checkboxes self.checkbox0 = QtGui.QCheckBox( 'Reference') #View the data feeded by the digitizer self.checkbox0.clicked.connect(self.updatePlot) self.checkbox1 = QtGui.QCheckBox( 'Stream mode') #View the data feeded by the digitizer self.checkbox1.clicked.connect(self.StreamOnOff) self.checkbox2 = QtGui.QCheckBox('Norm Radial Distribution') self.checkbox2.clicked.connect(self.NormalizeDscan) self.checkbox3 = QtGui.QCheckBox('Norm TOF') self.checkbox3.clicked.connect(self.NormalizeTOF) # Center control buttons self.cxlabel = QtGui.QLabel('Center X pos') self.spinbox1 = QtGui.QDoubleSpinBox() self.spinbox1.valueChanged.connect(self.updateROI) self.spinbox1.setMaximum(1000.0) self.spinbox1.setMinimum(0.0) self.spinbox1.setValue(204.0) self.cylabel = QtGui.QLabel('Center Y pos') self.spinbox2 = QtGui.QDoubleSpinBox() self.spinbox2.valueChanged.connect(self.updateROI) self.spinbox2.setMaximum(1000.0) self.spinbox2.setMinimum(0.0) self.spinbox2.setValue(197.0) #background removal buttons self.BGbutton = QtGui.QPushButton('Load BG') self.BGbutton.clicked.connect(self.LoadBG) self.bglabel = QtGui.QLabel('BG removal amount') self.spinbox3 = QtGui.QDoubleSpinBox() self.spinbox3.valueChanged.connect(self.updateBG) self.spinbox3.setMaximum(10.0) self.spinbox3.setMinimum(0.0) self.spinbox3.setValue(1.0) self.checkbox4 = QtGui.QCheckBox('BG removed ON/OFF') self.checkbox4.clicked.connect(self.updateBG) self.checkbox5 = QtGui.QCheckBox('pixels to energy') self.checkbox5.clicked.connect(self.updatePlot) self.EnCaliblabel = QtGui.QLabel('Energy Calibration coeff (x1e-6)') self.spinbox4 = QtGui.QDoubleSpinBox() self.spinbox4.valueChanged.connect(self.updatePlot) self.spinbox4.setMaximum(10000.0) self.spinbox4.setMinimum(0.0) self.spinbox4.setValue(894.30) self.spinbox5 = QtGui.QDoubleSpinBox() self.spinbox5.valueChanged.connect(self.updateROI) self.spinbox5.setMaximum(1000.0) self.spinbox5.setMinimum(1.0) self.spinbox4.setMaximum(10000.0) self.spinbox4.setMinimum(0.0) self.infos = QtGui.QLabel( 'Center Position : X0= 0.0 / Y0= 0.0 ; ROI radius = 100.0 px') self.graph = pg.GraphicsLayoutWidget() # GUI layout self.win.addWidget(self.loadbutton, row=0, col=0, colspan=2) self.win.addWidget(self.refbutton, row=1, col=0, colspan=2) self.win.addWidget(self.checkbox0, row=2, col=0, colspan=2) self.win.addWidget(self.checkbox1, row=3, col=0, colspan=2) self.win.addWidget(self.checkbox2, row=4, col=0, colspan=2) self.win.addWidget(self.checkbox3, row=5, col=0, colspan=2) self.win.addWidget(self.BGbutton, row=6, col=0) self.win.addWidget(self.checkbox4, row=7, col=0) self.win.addWidget(self.bglabel, row=8, col=0) self.win.addWidget(self.spinbox3, row=9, col=0) self.win.addWidget(self.cxlabel, row=10, col=0) self.win.addWidget(self.spinbox1, row=11, col=0) self.win.addWidget(self.cylabel, row=12, col=0) self.win.addWidget(self.spinbox2, row=13, col=0) self.win.addWidget(self.checkbox5, row=14, col=0) self.win.addWidget(self.EnCaliblabel, row=15, col=0) self.win.addWidget(self.spinbox4, row=16, col=0) self.win.addWidget(self.spinbox5, row=19, col=0) self.win.addWidget(self.infos, row=18, col=2) self.win.addWidget(self.graph, row=0, col=2, rowspan=17, colspan=5) self.win.resize(1250, 500) #self.win.show() # Graph layout for cartesian image self.p1 = self.graph.addPlot(row=0, col=0, rowspan=2) self.p1.setLabel(axis='left', text='Py (pixel)') self.p1.setLabel(axis='bottom', text='Py (pixel)') # Item for displaying image data self.img = pg.ImageItem() self.p1.addItem(self.img) self.p1.setAspectLocked(True, ratio=1) # Custom ROI for selecting an image region self.roi = pg.CircleROI( [100, 100], [50, 50]) # first vector =[x0,y0], second vector =[lx,ly] # self.roi.addScaleHandle([0.5, 1], [0.5, 0.5]) # self.roi.addScaleHandle([0, 0.5], [0.5, 0.5]) self.p1.addItem(self.roi) self.roi.setZValue(10) # make sure ROI is drawn above image self.roi.sigRegionChanged.connect(self.updatePlot) # Isocurve drawing self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.graph.addItem(self.hist, row=0, col=1, rowspan=2) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Another plot area for displaying ROI data self.graph.nextRow() self.p0 = self.graph.addPlot(row=0, col=3, colspan=2) self.p0.setLabel(axis='left', text='Radius (px)') self.p0.setLabel(axis='bottom', text='Angle (°)') self.imgpol = pg.ImageItem() self.p0.addItem(self.imgpol) self.histpol = pg.HistogramLUTItem() self.histpol.setImageItem(self.imgpol) self.graph.addItem(self.histpol, row=0, col=5) self.histpol.setMaximumWidth(100) self.graph.nextCol() self.p2 = self.graph.addPlot(row=1, col=3, colspan=3) self.p2.setLabel(axis='left', text='Signal (arb. u)') self.p2.setLabel(axis='bottom', text='Momentum (pixel)') #self.p2.setMaximumHeight(250) self.roipol = pg.ROI( [10, 10], [5, 5]) # first vector =[x0,y0], second vector =[lx,ly] self.roipol.addScaleHandle([0.5, 1], [0.5, 0.5]) self.roipol.addScaleHandle([0, 0.5], [0.5, 0.5]) self.p0.addItem(self.roipol) self.roipol.setZValue(10) # make sure ROI is drawn above image self.roipol.sigRegionChanged.connect(self.updatePlot) #Initialize the image self.initimg = np.random.normal(size=(1000, 1000)) self.initimg[380:420, 380:420] += 2. self.initimg = pg.gaussianFilter(self.initimg, (3, 3)) self.initimg += np.random.normal(size=(1000, 1000)) * 0.1 self.scan = VMITraceProcessing(self.initimg) self.activeimg = self.scan.imgcart_raw self.img.setImage(self.activeimg) self.img.scale(1, 1) self.img.translate(0, 0) self.hist.setLevels(self.activeimg.min(), self.activeimg.max()) self.p1.autoRange() #self.scan.ImgCart2Pol([self.roi.pos()[1]+self.roi.size()[0]/2.0,self.roi.pos()[0]+self.roi.size()[0]/2.0],self.roi.size()) self.scan.DefineCenter([ self.roi.pos()[1] + self.roi.size()[0] / 2.0, self.roi.pos()[0] + self.roi.size()[0] / 2.0 ]) self.scan.ImgCart2Pol(self.roi.size()) self.imgpol.setImage(self.scan.imgpol) # Infos from filedata self.pname = '' self.pnameBG = '' self.fname = '' # Initialise useful variables self.BGimg = [] self.normDscan = [] self.normTOF = [] self.refRadialDist = [] self.refx0 = [] self.refy0 = [] self.cx = [] self.cy = [] #Timer object for realtime data self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updatePlot) #Update the gui self.win.show()
def setup_image(self): # Interpret image data as row-major instead of col-major global img, roi, data, isoLine, iso, region win = self.widget_image #win.setWindowTitle('pyqtgraph example: Image Analysis') #iso.setZValue(5) img = pg.ImageItem() # Contrast/color control hist = pg.HistogramLUTItem() self.hist = hist hist.setImageItem(img) win.addItem(hist) # A plot area (ViewBox + axes) for displaying the image if self.app_ctr.time_scan: p1 = win.addPlot(row=1, col=0, rowspan=4, colspan=1) else: p1 = win.addPlot(row=1, col=0, rowspan=3, colspan=1) p1.setMaximumWidth(300) # Item for displaying image data self.img_pyqtgraph = img p1.addItem(img) # Custom ROI for selecting an image region #roi = pg.ROI([0, 0], [self.app_ctr.dim_detector[1]-2*self.app_ctr.hor_offset, self.app_ctr.dim_detector[0]-2*self.app_ctr.ver_offset]) roi = pg.ROI( [0, 0], [self.app_ctr.dim_detector[1] - 2 * self.app_ctr.hor_offset, 50]) self.roi = roi roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) p1.addItem(roi) #roi.setZValue(10) # make sure ROI is drawn above image # Isocurve drawing iso = pg.IsocurveItem(level=0.8, pen='g') iso.setParentItem(img) self.iso = iso # Draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.isoLine = isoLine hist.vb.addItem(isoLine) hist.vb.setMouseEnabled( y=True) # makes user interaction a little easier isoLine.setValue(0.) isoLine.setZValue(100000) # bring iso line above contrast controls # Another plot area for displaying ROI data #win.nextColumn() p2 = win.addPlot(0, 1, rowspan=1, colspan=1, title='image profile (vertical direction)') region = pg.LinearRegionItem() region.setZValue(10) region.setRegion([10, 15]) # Add the LinearRegionItem to the ViewBox, but tell the ViewBox to exclude this # item when doing auto-range calculations. region_mon = pg.LinearRegionItem() region_mon.setZValue(10) region_mon.setRegion([10, 15]) #monitor window p2_mon = win.addPlot(0, 2, rowspan=1, colspan=2, title='Monitor window') def update(): region.setZValue(10) region.show() minX, maxX = region.getRegion() region_mon.show() region_mon.setRegion([(minX + maxX) / 2 - 0.05, (minX + maxX) / 2 + 0.05]) #save the bounds of shape area for plotting in monitor window self.region_bounds = [minX, maxX] x, y = p2_mon.listDataItems()[0].xData, p2_mon.listDataItems( )[0].yData data_range = [np.argmin(abs(x - minX)), np.argmin(abs(x - maxX))] if data_range[1] > len(y): data_range[1] = len(y) minY = min(y[data_range[0]:data_range[1]]) maxY = max(y[data_range[0]:data_range[1]]) * 1.1 p2_mon.setYRange(minY, maxY, padding=0) p2_mon.setXRange(minX, maxX, padding=0) region.sigRegionChanged.connect(update) # plot to show intensity over time p3 = win.addPlot(1, 1, rowspan=1, colspan=3) if self.app_ctr.time_scan: p2.addItem(region, ignoreBounds=True) p2_mon.addItem(region_mon, ignoreBounds=True) else: p3.addItem(region, ignoreBounds=True) p2_mon.addItem(region_mon, ignoreBounds=True) # plot to show intensity over time p4 = win.addPlot(2, 1, rowspan=1, colspan=3) #if self.app_ctr.time_scan: p5 = win.addPlot(3, 1, rowspan=1, colspan=3) p5.setMaximumHeight(200) # zoom to fit imageo self.p1 = p1 self.p2 = p2 self.p3 = p3 self.p4 = p4 self.p5 = p5 self.p2_mon = p2_mon self.region_mon = region_mon p1.autoRange() self.legend_p2 = self.p2.addLegend() self.legend_p3 = self.p3.addLegend() self.legend_p4 = self.p4.addLegend() self.legend_p5 = self.p5.addLegend() #set axis labels self.p2.setLabel('left', 'Normalized intensity', units='c/s') self.p2.setLabel('bottom', '2theta angle', units='°') self.p2_mon.setLabel('left', 'Normalized intensity', units='c/s') self.p2_mon.setLabel('bottom', '2theta angle', units='°') self.p3.setLabel('left', 'Integrated peak intensity', units='c/s') #self.p3.setLabel('bottom','frame_number') self.p4.setLabel('left', 'Peak position') #self.p4.setLabel('bottom','frame_number') self.p5.setLabel('left', 'Potential wrt Ag/AgCl') self.p5.setLabel('bottom', 'frame_number') def update_bkg_signal(): selected = roi.getArrayRegion(self.app_ctr.img, self.img_pyqtgraph) self.bkg_intensity = selected.sum() # Callbacks for handling user interaction def updatePlot(): update_bkg_signal() self.app_ctr.run_update(bkg_intensity=self.bkg_intensity) #remove legend and plot again for legend in [ self.legend_p2, self.legend_p3, self.legend_p4, self.legend_p5 ]: try: legend.scene().removeItem(legend) except: pass self.legend_p2 = self.p2.addLegend() self.legend_p3 = self.p3.addLegend() self.legend_p4 = self.p4.addLegend() self.legend_p5 = self.p5.addLegend() self.p4.setLabel('left', self.comboBox_p4.currentText()) self.p5.setLabel('left', self.comboBox_p5.currentText()) if self.app_ctr.time_scan: plot_pxrd_fit_gui_pyqtgraph([self.p2_mon, self.p2], self.p3, self.p4, self.p5, self.app_ctr) self.p2.addItem(region, ignoreBounds=True) #re-add the region item self.p2_mon.addItem(region_mon, ignoreBounds=True) #re-add the region item else: plot_pxrd_fit_gui_pyqtgraph([self.p2_mon, self.p2], self.p3, None, self.p4, self.app_ctr) self.p3.addItem(region, ignoreBounds=True) self.p2_mon.addItem(region_mon, ignoreBounds=True) #re-add the region item #region.setRegion(self.region_bounds)#re-add the region item try: self.lcdNumber_potential.display(self.app_ctr.data[ self.app_ctr.img_loader.scan_number]['potential'][-1]) self.lcdNumber_current.display(self.app_ctr.data[ self.app_ctr.img_loader.scan_number]['current'][-1]) self.lcdNumber_intensity.display(self.app_ctr.data[ self.app_ctr.img_loader.scan_number]['peak_intensity'][-1]) except: pass self.lcdNumber_iso.display(isoLine.value()) def updatePlot_after_remove_point(): #not implemented for PXRD #global data try: selected = roi.getArrayRegion(self.app_ctr.bkg_sub.img, self.img_pyqtgraph) except: pass p2.plot(selected.sum(axis=0), clear=True) x, y = [int(each) for each in self.roi.pos()] w, h = [int(each) for each in self.roi.size()] self.iso.setData( pg.gaussianFilter( self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)], (2, 2))) self.iso.setPos(x, y) if self.app_ctr.img_loader.frame_number == 0: isoLine.setValue(self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)].mean()) else: pass #print(isoLine.value(),self.current_image_no) #plot others plot_bkg_fit_gui_pyqtgraph(self.p2, self.p3, self.p4, self.app_ctr.data, self.app_ctr.bkg_sub) self.lcdNumber_potential.display( self.app_ctr.data['potential'][-2]) self.lcdNumber_current.display(self.app_ctr.data['current'][-2]) self.lcdNumber_intensity.display( self.app_ctr.data['peak_intensity'][-2]) self.lcdNumber_iso.display(isoLine.value()) #roi.sigRegionChanged.connect(updatePlot) roi.sigRegionChanged.connect(updatePlot) self.updatePlot = updatePlot self.updatePlot2 = updatePlot_after_remove_point def updateIsocurve(): global isoLine, iso iso.setLevel(isoLine.value()) self.lcdNumber_iso.display(isoLine.value()) self.updateIsocurve = updateIsocurve isoLine.sigDragged.connect(updateIsocurve)
def setup_image(self): global img, roi, roi_bkg, p2, p2_r, p3_r, p3, p4, p4_r, isoLine, iso win = self.widget_image # Contrast/color control self.hist = pg.HistogramLUTItem() win.addItem(self.hist,row=0,col=0,rowspan=1,colspan=2) # A plot area (ViewBox + axes) for displaying the image p1 = win.addPlot(row=0,col=2,rowspan=1,colspan=2) # Item for displaying image data img = pg.ImageItem() p1.getViewBox().invertY(False) self.img_pyqtgraph = img p1.addItem(img) self.hist.setImageItem(img) # Custom ROI for selecting an image region roi = pg.ROI([100, 100], [200, 200]) self.roi = roi roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) p1.addItem(roi) # Custom ROI for monitoring bkg roi_bkg = pg.ROI([0, 100], [200, 200],pen = 'r') self.roi_bkg = roi_bkg roi_bkg.addScaleHandle([0.5, 1], [0.5, 0.5]) roi_bkg.addScaleHandle([0, 0.5], [0.5, 0.5]) p1.addItem(roi_bkg) # Isocurve drawing iso = pg.IsocurveItem(level=0.8, pen='g') iso.setParentItem(img) self.iso = iso # Draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.isoLine = isoLine self.hist.vb.addItem(isoLine) self.hist.vb.setMouseEnabled(y=True) # makes user interaction a little easier isoLine.setValue(0.8) isoLine.setZValue(100000) # bring iso line above contrast controls #set up the region selector for peak fitting self.region_cut_hor = pg.LinearRegionItem(orientation=pg.LinearRegionItem.Horizontal) self.region_cut_ver = pg.LinearRegionItem(orientation=pg.LinearRegionItem.Vertical) self.region_cut_hor.setRegion([180,220]) self.region_cut_ver.setRegion([180,220]) p1.addItem(self.region_cut_hor, ignoreBounds = True) p1.addItem(self.region_cut_ver, ignoreBounds = True) # double-y axis plot for structure data (strain and size) p2 = win.addPlot(row=1,col=1,colspan=2,rowspan=1, title = 'Strain (left,white) and size (right,blue)') p2.setLabel('bottom','frame_number') # p2.showAxis('right') # p2.setLabel('right','grain_size', pen = "b") #p2.setLogMode(y = True) p2_r = pg.ViewBox() p2.showAxis('right') p2.scene().addItem(p2_r) p2.getAxis('right').linkToView(p2_r) p2_r.setXLink(p2) # p2.getAxis('right').setLabel('grain_size', color='b') ## Handle view resizing def updateViews_p2(): ## view has resized; update auxiliary views to match p2_r.setGeometry(p2.vb.sceneBoundingRect()) ## need to re-update linked axes since this was called ## incorrectly while views had different shapes. ## (probably this should be handled in ViewBox.resizeEvent) p2_r.linkedViewChanged(p2.vb, p2_r.XAxis) updateViews_p2() p2.vb.sigResized.connect(updateViews_p2) # plot to show intensity(sig and bkg) over time p3 = win.addPlot(row=2,col=1,colspan=2,rowspan=1,title = 'Peak intensity(left,white) and bkg intensity (right,blue)') #p3.setLabel('left','Integrated Intensity', units='c/s') p3_r = pg.ViewBox() p3.showAxis('right') p3.scene().addItem(p3_r) p3.getAxis('right').linkToView(p3_r) p3_r.setXLink(p3) #p3.getAxis('right').setLabel('bkg', color='b') ## Handle view resizing def updateViews_p3(): ## view has resized; update auxiliary views to match p3_r.setGeometry(p3.vb.sceneBoundingRect()) ## need to re-update linked axes since this was called ## incorrectly while views had different shapes. ## (probably this should be handled in ViewBox.resizeEvent) p3_r.linkedViewChanged(p3.vb, p3_r.XAxis) updateViews_p3() p3.vb.sigResized.connect(updateViews_p3) # plot to show current/potential over time p4 = win.addPlot(row=3,col=1,colspan=2,rowspan=1, title = 'Potential (left,white) and current(right,blue)') #p4.setMaximumHeight(200) p4.setLabel('bottom','frame number') p4_r = pg.ViewBox() p4.showAxis('right') p4.scene().addItem(p4_r) p4.getAxis('right').linkToView(p4_r) p4_r.setXLink(p4) #p4.getAxis('right').setLabel('bkg', color='b') ## Handle view resizing def updateViews_p4(): ## view has resized; update auxiliary views to match p4_r.setGeometry(p4.vb.sceneBoundingRect()) ## need to re-update linked axes since this was called ## incorrectly while views had different shapes. ## (probably this should be handled in ViewBox.resizeEvent) p4_r.linkedViewChanged(p4.vb, p4_r.XAxis) updateViews_p4() p4.vb.sigResized.connect(updateViews_p4) #plot the peak fit results(horizontally) p5 = win.addPlot(row=1,col=0,colspan=1,rowspan=1,title = 'peak fit result_horz') p6 = win.addPlot(row=2,col=0,colspan=1,rowspan=1,title = 'peak fit result_vert') p6.setLabel('bottom','q') p7 = win.addPlot(row=3,col=0,colspan=1,rowspan=1,title = 'Peak intensity') p7.setLabel('bottom','pixel index') #add slider to p2 to exclude the abnormal points self.region_abnormal = pg.LinearRegionItem(orientation=pg.LinearRegionItem.Vertical) self.region_abnormal.setZValue(100) self.region_abnormal.setRegion([0, 5]) p2.addItem(self.region_abnormal, ignoreBounds = True) self.p1 = p1 self.p2 = p2 self.p2_r = p2_r self.p3 = p3 self.p3_r = p3_r self.p4 = p4 self.p4_r = p4_r self.p5 = p5 self.p6 = p6 self.p7 = p7 # zoom to fit image p1.autoRange() def update_bkg_signal(): selected = self.roi_bkg.getArrayRegion(self.app_ctr.img, self.img_pyqtgraph) self.bkg_intensity = selected.sum() #self.bkg_clip_image = selected #self.app_ctr.bkg_clip_image = selected self.update_bkg_signal = update_bkg_signal # Callbacks for handling user interaction def updatePlot(): #global data try: selected = self.roi.getArrayRegion(self.app_ctr.bkg_sub.img, self.img_pyqtgraph) except: pass self.reset_peak_center_and_width() if self.stop: self.update_bkg_signal() self.app_ctr.run_update(bkg_intensity=self.bkg_intensity) else: pass ##update iso curves x, y = [int(each) for each in self.roi.pos()] w, h = [int(each) for each in self.roi.size()] self.iso.setData(pg.gaussianFilter(self.app_ctr.bkg_sub.img[y:(y+h),x:(x+w)], (2, 2))) self.iso.setPos(x,y) #update bkg roi self.roi_bkg.setSize([w,h]) self.roi_bkg.setPos([x-w,y]) if self.app_ctr.img_loader.frame_number ==0: isoLine.setValue(self.app_ctr.bkg_sub.img[y:(y+h),x:(x+w)].mean()) else: pass #plot others plot_xrv_gui_pyqtgraph(self.p1,[self.p2,self.p2_r], [self.p3,self.p3_r], [self.p4,self.p4_r],self.p5, self.p6, self.p7,self.app_ctr) # add slider afterwards to have it show up on th plot self.p2.addItem(self.region_abnormal, ignoreBounds = True) #show values for current status self.lcdNumber_potential.display(self.app_ctr.data['potential'][-1]) self.lcdNumber_current.display(self.app_ctr.data['current'][-1]) self.lcdNumber_intensity.display(self.app_ctr.data['peak_intensity'][-1]) self.lcdNumber_iso.display(isoLine.value()) roi.sigRegionChanged.connect(updatePlot) self.updatePlot = updatePlot def updateIsocurve(): global isoLine, iso iso.setLevel(isoLine.value()) self.lcdNumber_iso.display(isoLine.value()) self.updateIsocurve = updateIsocurve isoLine.sigDragged.connect(updateIsocurve)
def setup_image(self): # Interpret image data as row-major instead of col-major global img, roi, roi_bkg, data, p2, isoLine, iso win = self.widget_image # print(dir(win)) win.setWindowTitle('pyqtgraph example: Image Analysis') # A plot area (ViewBox + axes) for displaying the image p1 = win.addPlot() # Item for displaying image data img = pg.ImageItem() self.img_pyqtgraph = img p1.addItem(img) # Custom ROI for selecting an image region ver_width, hor_width = self.app_ctr.cen_clip roi = pg.ROI(pos=[hor_width * 2 * 0.2, 0.], size=[hor_width * 2 * 0.6, ver_width * 2]) #roi = pg.ROI([100, 100], [100, 100]) self.roi = roi roi.addScaleHandle([0.5, 1], [0.5, 0.5]) roi.addScaleHandle([0, 0.5], [0.5, 0.5]) roi.addRotateHandle([0., 0.], [0.5, 0.5]) p1.addItem(roi) roi_peak = pg.ROI( pos=[hor_width - self.app_ctr.bkg_sub.peak_width, 0.], size=[self.app_ctr.bkg_sub.peak_width * 2, ver_width * 2], pen='g') #roi = pg.ROI([100, 100], [100, 100]) self.roi_peak = roi_peak p1.addItem(roi_peak) # Custom ROI for monitoring bkg roi_bkg = pg.ROI(pos=[hor_width * 2 * 0.2, 0.], size=[hor_width * 2 * 0.1, ver_width * 2], pen='r') # roi_bkg = pg.ROI([0, 100], [100, 100],pen = 'r') self.roi_bkg = roi_bkg # roi_bkg.addScaleHandle([0.5, 1], [0.5, 0.5]) # roi_bkg.addScaleHandle([0, 0.5], [0.5, 0.5]) p1.addItem(roi_bkg) #roi.setZValue(10) # make sure ROI is drawn above image # Isocurve drawing iso = pg.IsocurveItem(level=0.8, pen='g') iso.setParentItem(img) self.iso = iso #iso.setZValue(5) # Contrast/color control hist = pg.HistogramLUTItem() self.hist = hist hist.setImageItem(img) win.addItem(hist) # Draggable line for setting isocurve level isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.isoLine = isoLine hist.vb.addItem(isoLine) hist.vb.setMouseEnabled( y=True) # makes user interaction a little easier isoLine.setValue(0.8) isoLine.setZValue(100000) # bring iso line above contrast controls # Another plot area for displaying ROI data win.nextRow() p2 = win.addPlot(colspan=2, title='ROI image profile') p2.setMaximumHeight(200) p2.setLabel('left', 'Intensity', units='c/s') p2.setLabel('bottom', 'Pixel number') #p2.setLogMode(y = True) # plot to show intensity over time win.nextRow() p3 = win.addPlot(colspan=2) p3.setMaximumHeight(200) p3.setLabel('left', 'Integrated Intensity', units='c/s') # plot to show intensity over time win.nextRow() p4 = win.addPlot(colspan=2) p4.setMaximumHeight(200) p4.setLabel('bottom', 'frame number') region_roi = pg.LinearRegionItem() region_roi.setZValue(10) region_roi.setRegion([10, 15]) # Generate image data #data = np.random.normal(size=(500, 600)) #data[20:80, 20:80] += 2. #data = pg.gaussianFilter(data, (3, 3)) #data += np.random.normal(size=(500, 600)) * 0.1 #img.setImage(data) ##hist.setLevels(data.min(), data.max()) # build isocurves from smoothed data ##iso.setData(pg.gaussianFilter(data, (2, 2))) # set position and scale of image #img.scale(0.2, 0.2) #img.translate(-50, 0) # zoom to fit imageo self.p1 = p1 self.p2 = p2 self.p3 = p3 self.p4 = p4 p1.autoRange() def update_bkg_signal(): selected = roi_bkg.getArrayRegion(self.app_ctr.img, self.img_pyqtgraph) self.bkg_intensity = selected.mean() #self.bkg_clip_image = selected #self.app_ctr.bkg_clip_image = selected def update_bkg_clip(): selected = roi_bkg.getArrayRegion(self.app_ctr.img, self.img_pyqtgraph) #self.bkg_intensity = selected.sum() #self.bkg_clip_image = selected self.app_ctr.bkg_clip_image = selected # Callbacks for handling user interaction def updatePlot(begin=False): # t0 = time.time() update_bkg_signal() #global data try: selected = roi.getArrayRegion(self.app_ctr.bkg_sub.img, self.img_pyqtgraph) except: #selected = roi.getArrayRegion(data, self.img_pyqtgraph) pass self.p3.setLabel('left', self.comboBox_p3.currentText()) self.p4.setLabel('left', self.comboBox_p4.currentText()) # p2.plot(selected.sum(axis=int(self.app_ctr.bkg_sub.int_direct=='y')), clear=True) self.reset_peak_center_and_width() if self.tag_reprocess: self.app_ctr.run_update_one_specific_frame( self.app_ctr.bkg_sub.img, self.bkg_intensity, poly_func=['Vincent', 'traditional'][int( self.radioButton_traditional.isChecked())], frame_offset=int(self.lineEdit_frame_index_offset.text())) else: self.app_ctr.run_update( bkg_intensity=self.bkg_intensity, begin=begin, poly_func=['Vincent', 'traditional'][int( self.radioButton_traditional.isChecked())]) # t1 = time.time() ##update iso curves x, y = [int(each) for each in self.roi.pos()] w, h = [int(each) for each in self.roi.size()] self.iso.setData( pg.gaussianFilter( self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)], (2, 2))) self.iso.setPos(x, y) #update peak roi self.roi_peak.setSize([self.app_ctr.bkg_sub.peak_width * 2, h]) self.roi_peak.setPos( [x + w / 2. - self.app_ctr.bkg_sub.peak_width, y]) #update bkg roi self.roi_bkg.setSize([w / 2 - self.app_ctr.bkg_sub.peak_width, h]) self.roi_bkg.setPos([x, y]) # t2 = time.time() # print(t1-t0,t2-t1) if self.app_ctr.img_loader.frame_number == 0: isoLine.setValue(self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)].mean()) else: pass #print(isoLine.value(),self.current_image_no) #plot others #plot_bkg_fit_gui_pyqtgraph(self.p2, self.p3, self.p4,self.app_ctr) if self.tag_reprocess: index_frame = int(self.lineEdit_frame_index_offset.text()) plot_bkg_fit_gui_pyqtgraph(self.p2, self.p3, self.p4, self.app_ctr, index_frame) self.lcdNumber_frame_number.display( self.app_ctr.img_loader.frame_number + 1 + index_frame + 1) try: self.lcdNumber_potential.display( self.app_ctr.data['potential'][index_frame]) self.lcdNumber_current.display( self.app_ctr.data['current'][index_frame]) except: pass self.lcdNumber_intensity.display( self.app_ctr.data['peak_intensity'][index_frame]) self.lcdNumber_signal_noise_ratio.display( self.app_ctr.data['peak_intensity'][index_frame] / self.app_ctr.data['noise'][index_frame]) else: plot_bkg_fit_gui_pyqtgraph(self.p2, self.p3, self.p4, self.app_ctr) try: self.lcdNumber_potential.display( self.app_ctr.data['potential'][-1]) self.lcdNumber_current.display( self.app_ctr.data['current'][-1]) except: pass self.lcdNumber_intensity.display( self.app_ctr.data['peak_intensity'][-1]) self.lcdNumber_signal_noise_ratio.display( self.app_ctr.data['peak_intensity'][-1] / self.app_ctr.data['noise'][-1]) self.lcdNumber_iso.display(isoLine.value()) # if self.run_mode and ((self.app_ctr.data['peak_intensity'][-1]/self.app_ctr.data['peak_intensity_error'][-1])<1.5): if self.run_mode and ((self.app_ctr.data['peak_intensity'][-1] / self.app_ctr.data['noise'][-1]) < self.doubleSpinBox_SN_cutoff.value()): self.pushButton_remove_current_point.click() def updatePlot_after_remove_point(): #global data try: selected = roi.getArrayRegion(self.app_ctr.bkg_sub.img, self.img_pyqtgraph) except: #selected = roi.getArrayRegion(data, self.img_pyqtgraph) pass p2.plot(selected.sum(axis=0), clear=True) self.reset_peak_center_and_width() #self.app_ctr.run_update() ##update iso curves x, y = [int(each) for each in self.roi.pos()] w, h = [int(each) for each in self.roi.size()] self.iso.setData( pg.gaussianFilter( self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)], (2, 2))) self.iso.setPos(x, y) if self.app_ctr.img_loader.frame_number == 0: isoLine.setValue(self.app_ctr.bkg_sub.img[y:(y + h), x:(x + w)].mean()) else: pass #print(isoLine.value(),self.current_image_no) #plot others plot_bkg_fit_gui_pyqtgraph(self.p2, self.p3, self.p4, self.app_ctr) try: self.lcdNumber_potential.display( self.app_ctr.data['potential'][-2]) self.lcdNumber_current.display( self.app_ctr.data['current'][-2]) except: pass self.lcdNumber_intensity.display( self.app_ctr.data['peak_intensity'][-2]) self.lcdNumber_signal_noise_ratio.display( self.app_ctr.data['peak_intensity'][-2] / self.app_ctr.data['noise'][-2]) self.lcdNumber_iso.display(isoLine.value()) self.updatePlot = updatePlot self.updatePlot2 = updatePlot_after_remove_point self.update_bkg_clip = update_bkg_clip #roi.sigRegionChanged.connect(updatePlot) roi.sigRegionChanged.connect(self.update_ss_factor) def updateIsocurve(): global isoLine, iso iso.setLevel(isoLine.value()) self.lcdNumber_iso.display(isoLine.value()) self.updateIsocurve = updateIsocurve isoLine.sigDragged.connect(updateIsocurve)
def init_graphics(self): """Initialise the important graphics items""" m, n = 1280, 1024 self.image = pg.ImageItem(np.zeros((m,n))) self.zoom = pg.ImageItem(np.zeros((50,50))) self.residuals = pg.ImageItem(np.zeros((50,50))) self.residuals.setLevels(self._residual_levels) self.x_fit = pg.PlotDataItem(np.zeros(m), pen={'width':2}) self.x_slice = pg.PlotDataItem(np.zeros(m), pen=None, symbol='o', pxMode=True, symbolSize=4) self.y_fit = pg.PlotDataItem(np.zeros(n), pen={'width':2}) self.y_slice = pg.PlotDataItem(np.zeros(n), pen=None, symbol='o', pxMode=True, symbolSize=4) # Only the residuals have any sort of false color - initialise the # lookup table and the legend cmap = self.get_color_map() self.residual_LUT = cmap.getLookupTable(nPts=256) self.res_legend = pg.GradientLegend(size=(10,255), offset=(0,20)) self.res_legend.setGradient(cmap.getGradient()) n_ticks = 5 self.res_legend.setLabels({"{}".format(level):val for (level, val) in zip( np.linspace(*self._residual_levels, n_ticks), np.linspace(0, 1, n_ticks))}) ypen = pg.mkPen(color=(255,255,0,85), width=3) # Centroid position markers in main image, aligned with x,y self.fit_v_line = pg.InfiniteLine(pos=1, angle=90, pen=ypen) self.fit_h_line = pg.InfiniteLine(pos=1, angle=0, pen=ypen) # Plot fading recent position markers n_history = 5 self.history = collections.deque(maxlen=n_history) self.history_plot = pg.ScatterPlotItem() self.history_brushes = [pg.mkBrush( color=(255,255,0,int((i+1)*255/n_history))) for i in range(n_history)] # User marked position rpen = pg.mkPen(color=(255,0,0,127), width=3, style=QtCore.Qt.DotLine) self.mark_v_line = pg.InfiniteLine(pos=1, angle=90, pen=rpen) self.mark_h_line = pg.InfiniteLine(pos=1, angle=0, pen=rpen) self.mark_widgets.extend([ self.mark_v_line, self.mark_h_line, ]) # Mouse cursor wpen = pg.mkPen(color=(255,255,255,63), width=3) red = pg.mkColor(255,0,0,223) yellow = pg.mkColor(255,255,0,223) self.cursor_v = pg.InfiniteLine(pos=1, angle=90, pen=wpen) self.cursor_h = pg.InfiniteLine(pos=1, angle=0, pen=wpen) self.cursor_text = pg.TextItem() self.cursor_delta = pg.TextItem(anchor=(-0.1, -0.1), color=red) self.beam_delta = pg.TextItem(anchor=(-0.1, -0.1), color=yellow) self.zoom_text = pg.TextItem(anchor=(-0.1, -0.1), color=yellow) self.residuals_text = pg.TextItem(anchor=(-0.1, -0.1)) self.mark_widgets.append(self.cursor_delta) self.mark_widgets.append(self.beam_delta) # Centroid position markers in zoomed image, aligned with beam # ellipse axes zoom_centre = QtCore.QPointF(25,25) self.fit_maj_line = pg.InfiniteLine(pos=zoom_centre, angle=90, pen=ypen) self.fit_min_line = pg.InfiniteLine(pos=zoom_centre, angle=0, pen=ypen) # Shows 1/e^2 ellipse of beam isopen = pg.mkPen(color=(255,255,0,85), width=3, style=QtCore.Qt.DotLine) self.isocurve = pg.IsocurveItem(pen=isopen) self.isocurve.setParentItem(self.zoom)
def __init__(self): #TemplateBaseClass.__init__(self) #self.win =QtGui.QGridLayout() self.win = pg.LayoutWidget() # Main layout self.win.setWindowTitle('TOF Scan Viewer') #Loadfile button self.loadbutton = QtGui.QPushButton('Load Data') self.loadbutton.clicked.connect(self.OpenFile) #Take reference button self.refbutton = QtGui.QPushButton('Save Reference') self.refbutton.clicked.connect(self.SaveReference) #Checkboxes self.checkbox0 = QtGui.QCheckBox( 'Reference') #View the data feeded by the digitizer self.checkbox0.clicked.connect(self.updatePlot) self.checkboxStream1 = QtGui.QCheckBox( 'Stream from scanfile') #View the data feeded by the digitizer self.checkboxStream1.clicked.connect(self.StreamOnOff) self.checkbox2 = QtGui.QCheckBox('Norm Dscan') self.checkbox2.clicked.connect(self.NormalizeDscan) self.checkbox3 = QtGui.QCheckBox('Norm TOF') self.checkbox3.clicked.connect(self.NormalizeTOF) self.realtimegraph = pg.GraphicsLayoutWidget() self.scangraph = pg.GraphicsLayoutWidget() # GUI layout #self.win.addWidget(QtGui.QLabel('Real time single shot data '),row=0,col=0) #self.win.addWidget(QtGui.QLabel('Real time accumulated data'),row=0,col=2) #self.win.addWidget(self.realtimegraph,row=1,col=0,colspan=4) #self.win.addWidget(QtGui.QLabel('Time of Flight scan'),row=2,col=0) self.win.addWidget(self.loadbutton, row=3, col=0) self.win.addWidget(self.refbutton, row=4, col=0) self.win.addWidget(self.checkbox0, row=5, col=0) self.win.addWidget(self.checkboxStream1, row=6, col=0) self.win.addWidget(self.checkbox2, row=7, col=0) self.win.addWidget(self.checkbox3, row=8, col=0) self.win.addWidget(self.scangraph, row=2, col=1, rowspan=25, colspan=3) self.realtimegraph.setMaximumHeight(200) self.win.resize(1250, 1250) self.win.show() # Graph layout self.prealtime1 = self.realtimegraph.addPlot(row=0, col=0) self.prealtime1.setLabel(axis='left', text='Signal (mV) ') self.prealtime1.setLabel(axis='bottom', text='Tof (ns)') self.prealtime2 = self.realtimegraph.addPlot(row=0, col=2) self.prealtime2.setLabel(axis='left', text='Signal (mV) ') self.prealtime2.setLabel(axis='bottom', text='Tof (ns)') self.p1 = self.scangraph.addPlot(row=0, col=0, colspan=2) self.p1.setLabel(axis='left', text='Delay (fs)') self.p1.setLabel(axis='bottom', text='Tof (ns)') # Item for displaying image data self.img = pg.ImageItem() self.p1.addItem(self.img) # Custom ROI for selecting an image region self.roi = pg.ROI( [-8, 14], [1000, 100]) # first vector =[x0,y0], second vector =[lx,ly] self.roi.addScaleHandle([0.5, 1], [0.5, 0.5]) self.roi.addScaleHandle([0, 0.5], [0.5, 0.5]) self.p1.addItem(self.roi) self.roi.setZValue(10) # make sure ROI is drawn above image self.roi.sigRegionChanged.connect(self.updatePlot) # Isocurve drawing self.iso = pg.IsocurveItem(level=0.8, pen='g') self.iso.setParentItem(self.img) self.iso.setZValue(5) # Contrast/color control self.hist = pg.HistogramLUTItem() self.hist.setImageItem(self.img) self.scangraph.addItem(self.hist) # Draggable line for setting isocurve level self.isoLine = pg.InfiniteLine(angle=0, movable=True, pen='g') self.hist.vb.addItem(self.isoLine) self.hist.vb.setMouseEnabled( y=False) # makes user interaction a little easier self.isoLine.setValue(0.8) self.isoLine.setZValue(1000) # bring iso line above contrast controls self.isoLine.sigDragged.connect(self.updateIsocurve) # Another plot area for displaying ROI data self.scangraph.nextRow() self.p0 = self.scangraph.addPlot(row=1, col=0) self.p0.setLabel(axis='left', text='Signal (arb. u)') self.p0.setLabel(axis='bottom', text='Delay (fs)') #self.p0.setMaximumWidth(250) #self.p0.setMaximumHeight(250) #self.p0.rotate(90) #self.p0.translate(0,-250) self.p0.invertX(True) self.isoLine0 = pg.InfiniteLine(angle=90, movable=True, pen='g') self.p0.vb.addItem(self.isoLine0) self.isoLine0.setValue(2.0) self.isoLine0.setZValue(1000) self.scangraph.nextCol() self.p2 = self.scangraph.addPlot(row=1, col=1, colspan=1) self.p2.setLabel(axis='left', text='Signal (arb. u)') self.p2.setLabel(axis='bottom', text='Tof (ns)') #self.p2.setMaximumHeight(250) #Initialize the image self.scan = np.random.normal(size=(100, 200)) self.scan[20:80, 20:80] += 2. self.scan = pg.gaussianFilter(self.scan, (3, 3)) self.scan += np.random.normal(size=(100, 200)) * 0.1 self.activeimg = self.scan self.img.setImage(self.activeimg) self.img.scale(1, 1) self.img.translate(0, 0) self.hist.setLevels(self.activeimg.min(), self.activeimg.max()) self.p1.autoRange() # Infos from filedata self.pname = '' self.fname = '' # Initialise useful variables self.normDscan = [] self.normTOF = [] self.refDscan = [] self.refTOF = [] self.refx0 = [] self.refy0 = [] #Timer object for realtime data self.timer = QtCore.QTimer() self.timer.timeout.connect(self.updatePlot)