def setup_overlay(self): color = np.array([[0, 0, 0, 0], self.color], dtype=np.ubyte) color_map = ColorMap([0, 1], color) self.overlay.setVisible(False) lut = color_map.getLookupTable(0, 1, 2) self.overlay.setLookupTable(lut) self.overlay.setZValue(11)
def add_difference_overlay(self, diff): diff = -diff diff[diff > 0.0] = 1.0 pos = np.array([0, 1]) color = np.array([[0, 0, 0, 0], [255, 0, 0, 255]], dtype=np.ubyte) map = ColorMap(pos, color) self.image_after_overlay.setOpacity(1) self.image_after_overlay.setImage(diff) lut = map.getLookupTable(0, 1, 2) self.image_after_overlay.setLookupTable(lut)
def setColorMap(self, map=None): if not map: if not self._cm_colors.any(): return pos = np.linspace(self.cm_min/float(self.data_max_int), self.cm_max/float(self.data_max_int), num=len(self._cm_colors)) map = ColorMap(pos, self._cm_colors) self.getView().setBackgroundColor(map.map(0)) lut = map.getLookupTable(0.0,1.0,self.data_max_int, alpha=False) self.getImageItem().setLookupTable(lut) self.getImageItem().setLevels([self.cm_min/float(self.data_max_int),float(self.data_max_int)])
def add_difference_overlay(self, diff, nan_change): diff = np.absolute(diff) diff[diff > OVERLAY_THRESHOLD] = 1.0 diff[nan_change] = 1.0 pos = np.array([0, 1]) color = np.array([[0, 0, 0, 0], OVERLAY_COLOUR_DIFFERENCE], dtype=np.ubyte) map = ColorMap(pos, color) self.image_diff_overlay.setVisible(True) self.image_diff_overlay.setImage(diff) lut = map.getLookupTable(0, 1, 2) self.image_diff_overlay.setLookupTable(lut)
def setColorMap(self, map=None): if not map: if not self._cm_colors.any(): return pos = np.linspace(0.0, 1.0, num=len(self._cm_colors)) # take default values map = ColorMap(pos, self._cm_colors) self.getView().setBackgroundColor(map.map(0)) lut = map.getLookupTable(0.0, 1.0, self.data_max_int, alpha=False) self.getImageItem().setLookupTable(lut) self.getImageItem().setLevels([ self.cm_min, float(self.data_max_int) ]) # set levels from min to max of image (may improve min here)
def __init__(self): super(Bp2DWidget, self).__init__() # M.B. plot add to params self.setXRange(-60, 60) self.setYRange(-60, 60) self.img = ImageItem() self.addItem(self.img) _translate = QCoreApplication.translate self.setLabels(title=_translate("Bp2DWidget", "Beam pattern"), left=_translate("Bp2DWidget", "Elevation, °"), bottom=_translate("Bp2DWidget", "Azimuth, °")) self.setLogMode() colormap = ColorMap(*zip(*Gradients["bipolar"]["ticks"])) self.img.setLookupTable(colormap.getLookupTable())
def setColorMap(self, cmap=None): """ Update the image colormap. Parameters ---------- cmap : ColorMap """ if not cmap: if not self._cm_colors.any(): return # Take default values pos = np.linspace(0.0, 1.0, num=len(self._cm_colors)) cmap = ColorMap(pos, self._cm_colors) self.getView().setBackgroundColor(cmap.map(0)) lut = cmap.getLookupTable(0.0, 1.0, alpha=False) self.getImageItem().setLookupTable(lut)
def set_current_colormap(self, name): # Change colormap of plot_item index = self._name_to_index(name) pos = self.colormaps[index].pos colors = self.colormaps[index].colors for plot_item in self.plot_item: plot_item.setColorMap(ColorMap(pos, colors))
def __init__(self): super(Bp3DWidget, self).__init__() self.frame = QFrame() layout = QVBoxLayout() colormap = ColorMap(*zip(*Gradients["bipolar"]["ticks"])).getLookupTable() / 255.0 self.colormap = ListedColormap(colormap) self.plotter = QtInteractor(self.frame) layout.addWidget(self.plotter.interactor) self.frame.setLayout(layout) self.setLayout(layout)
def setColorMap(self, cmap=None): """ Update the image colormap Parameters ---------- cmap : ColorMap """ if self.data_max_int is None: return if not cmap: if not self._cm_colors.any(): return pos = np.linspace(0.0, 1.0, num=len(self._cm_colors)) # take default values cmap = ColorMap(pos, self._cm_colors) self.getView().setBackgroundColor(cmap.map(0)) lut = cmap.getLookupTable(0.0, 1.0, self.data_max_int, alpha=False) self.getImageItem().setLookupTable(lut) self.getImageItem().setLevels([ self.cm_min, float(min(self.cm_max, self.data_max_int)) ]) # set levels from min to max of image (may improve min here)
def color_map_to_pyqtgraph(map): """ Converts a colormap from matplotlib to a colormap for pyqtgraph. :param map: matplotlib colormap :return: pyqtgraph colormap """ length = len(map.colors) pos = [i / length for i in range(length)] color = map.colors color_count = len(color[0]) color_mode = None if color_count == 3: color_mode = ColorMap.RGB for entry in color: entry.append(1.) return ColorMap(pos, color, color_mode)
def add_image( self, array: np.ndarray, plot_pos: int, labels: dict, normalize: bool = True, invert_y: bool = True, cmap_style: str = "diverging", **kwargs: t.Optional[dict], ) -> PlotItem: remote_plot = self.get_remote_plots()[plot_pos] remote_plot_item = remote_plot._view.centralWidget # noqa remote_plot_item.clear() if "levels" in kwargs.keys(): levels = kwargs.pop("levels") auto_levels = False else: levels = None auto_levels = True if normalize: array = self.normalize_array(array) if cmap_style == "diagnostic": colormap = ColorMap(pos=np.linspace( -1, 1, len(SANITY_PLOT_COLORS[cmap_style])), color=np.array(SANITY_PLOT_COLORS[cmap_style])) lut = colormap.getLookupTable( start=-1, stop=1, nPts=1024, ) elif cmap_style == "dissimilarity": colormap = ColorMap(pos=np.linspace( 0, 1, len(SANITY_PLOT_COLORS[cmap_style])), color=np.array(SANITY_PLOT_COLORS[cmap_style])) lut = colormap.getLookupTable( start=1, stop=0, nPts=1024, ) else: raise ValueError("Invalid colormap style requested.") if auto_levels: image_item = remote_plot.pg.ImageItem(image=array, lut=lut) else: image_item = remote_plot.pg.ImageItem(image=array, lut=lut, autoLevels=auto_levels, levels=levels) if not auto_levels: image_item.setLevels(levels) remote_plot_item.addItem(image_item, **kwargs) self._set_labels_on_plot(remote_plot_item, labels) remote_plot_item.hideAxis('top') remote_plot_item.hideAxis('right') remote_plot_item.invertY(invert_y) return remote_plot_item
def cmapToColormap(cmap: ListedColormap) -> ColorMap: """ Converts matplotlib cmap to pyqtgraph ColorMap. """ colordata = (np.array(cmap.colors) * 255).astype(np.uint8) indices = np.linspace(0., 1., len(colordata)) return ColorMap(indices, colordata)
def __init__(self, imodel, iview, geom, parent=None): QObject.__init__(self, parent) self.imodel = imodel self.dmodel = imodel.model self.iview = iview self.iview.ui.menuBtn.hide() self.iview.ui.roiBtn.hide() # Thanks CXIVIEW, Anton & Valerio pos = np.array([0.0, 0.5, 1.0]) color = np.array( [[255, 255, 255, 255], [128, 128, 128, 255], [0, 0, 0, 255]], dtype=np.ubyte) new_color_map = ColorMap(pos, color) self.iview.ui.histogram.gradient.setColorMap(new_color_map) self.lastrow = -1 self.curFileName = None self.curFile = None self.canDraw = self.dmodel.canSaveLst() self.checkEvent = "event" in self.dmodel.cols self.yxmap = None self.slab_shape = None self.img_shape = None self.geom_coffset = 0 self.geom_pixsize = None self.im_out = None self.resolutionLambda = None self.pixRadiusToRes = None self.hkl = None self.hklLookup = None self.imodel.dataChanged.connect(self.draw) self.iview.view.menu.addSeparator() openGeomAct = self.iview.view.menu.addAction("Load CrystFEL Geometry") openGeomAct.triggered.connect(self.openGeom) peakmenu = self.iview.view.menu.addMenu("Peaks") self.peakActionGroup = QActionGroup(self) self.peakActionGroup.setExclusive(True) self.peakActionGroup.triggered.connect(self.drawPeaks) peakNone = peakmenu.addAction("None") peakNone.setCheckable(True) peakNone.setChecked(True) peakNone.setData(0) self.peakActionGroup.addAction(peakNone) peakCXI = peakmenu.addAction("CXI") peakCXI.setCheckable(True) peakCXI.setEnabled(self.dmodel.canSaveLst()) peakCXI.setData(1) self.peakActionGroup.addAction(peakCXI) peakStream = peakmenu.addAction("Stream") peakStream.setCheckable(True) peakStream.setEnabled(self.dmodel.hasStreamPeaks()) peakStream.setData(2) self.peakActionGroup.addAction(peakStream) self.peakCanvas = ScatterPlotItem() self.iview.getView().addItem(self.peakCanvas) reflectionmenu = self.iview.view.menu.addMenu("Reflections") self.reflectionActionGroup = QActionGroup(self) self.reflectionActionGroup.setExclusive(True) self.reflectionActionGroup.triggered.connect(self.drawReflections) refNone = reflectionmenu.addAction("None") refNone.setCheckable(True) refNone.setChecked(True) refNone.setData(0) self.reflectionActionGroup.addAction(refNone) refStream = reflectionmenu.addAction("Stream") refStream.setCheckable(True) refStream.setEnabled(self.dmodel.hasStreamReflections()) refStream.setData(1) self.reflectionActionGroup.addAction(refStream) self.reflectionCanvas = ScatterPlotItem() self.iview.getView().addItem(self.reflectionCanvas) self.drawResRingsAct = self.iview.view.menu.addAction( "Resolution Rings") self.drawResRingsAct.setCheckable(True) self.drawResRingsAct.setChecked(False) self.drawResRingsAct.triggered.connect(self.drawResRings) self.drawResRingsAct.setEnabled(self.yxmap is not None) self.resolutionRingsCanvas = ScatterPlotItem() self.iview.getView().addItem(self.resolutionRingsCanvas) self.resRingsTextItems = [] for x in self.dmodel.cfg.viewerResolutionRingsAngstroms: self.resRingsTextItems.append(TextItem('', anchor=(0.5, 0.8))) self.iview.getView().addItem(self.resRingsTextItems[-1]) self.drawResolutionLimitAct = self.iview.view.menu.addAction( "Resolution Limit Ring") self.drawResolutionLimitAct.setCheckable(True) self.drawResolutionLimitAct.setChecked(False) self.drawResolutionLimitAct.triggered.connect(self.drawResLimitRing) self.drawResolutionLimitAct.setEnabled( self.yxmap is not None and 'reslim' in self.dmodel.cols) self.resolutionLimitCanvas = ScatterPlotItem() self.iview.getView().addItem(self.resolutionLimitCanvas) if geom is not None: self.loadGeom(geom) self.toolTipsAct = self.iview.view.menu.addAction( "Show Position in Tool Tip") self.toolTipsAct.setCheckable(True) self.toolTipsAct.setChecked(True) self.iview.scene.sigMouseMoved.connect(self.mouseMove) self.draw()
def getContextMenus(self, *, rect=None, event=None): if self.menu is None: self.menu = QtGui.QMenu() self.menu.clear() # Add color selector if self.gradientSelectorMenu is None: l = 80 self.gradientSelectorMenu = QtGui.QMenu() self.gradientSelectorMenu.setTitle("Color Scale") gradients = graphicsItems.GradientEditorItem.Gradients for g in gradients: if g in COLORMAPS: cmap = COLORMAPS[g] else: pos = [x[0] for x in gradients[g]['ticks']] colors = [x[1] for x in gradients[g]['ticks']] mode = ColorMap.RGB if gradients[g][ 'mode'] == 'rgb' else ColorMap.HSV_POS cmap = ColorMap(pos, colors, mode=mode) COLORMAPS[g] = cmap px = QtGui.QPixmap(l, 15) p = QtGui.QPainter(px) grad = cmap.getGradient(QtCore.QPointF(0, 0), QtCore.QPointF(l, 0)) brush = QtGui.QBrush(grad) p.fillRect(QtCore.QRect(0, 0, l, 15), brush) p.end() label = QtGui.QLabel() label.setPixmap(px) label.setContentsMargins(1, 1, 1, 1) act = QtGui.QWidgetAction(self) act.setDefaultWidget(label) act.triggered.connect(partial(self.changeColorScale, name=g)) act.name = g self.gradientSelectorMenu.addAction(act) self.menu.addMenu(self.gradientSelectorMenu) # Actions that use the scale box if rect is not None: xrange = rect.left(), rect.right() yrange = rect.top(), rect.bottom() qaction = QtGui.QAction("Colour By Marquee", self.menu) qaction.triggered.connect( partial(self.colorByMarquee, xrange=xrange, yrange=yrange)) self.menu.addAction(qaction) qaction = QtGui.QAction("Plane Fit", self.menu) qaction.triggered.connect( partial(self.planeFit, xrange=xrange, yrange=yrange)) self.menu.addAction(qaction) qaction = QtGui.QAction("Level Columns", self.menu) qaction.triggered.connect( partial(self.levelColumns, xrange=xrange, yrange=yrange)) self.menu.addAction(qaction) self.menu.setTitle("Image Item") return self.menu
def view_generate_pg_colormap(self): self.pos = np.linspace( 0.0, 1.0, self._ca_algo.number_of_reserved_ids + int(self.lineEdit_number_of_grains.text())) self.cmap = ColorMap(pos=self.pos, color=self._ca_algo.color_id) self.graphicsView.setColorMap(self.cmap)
def setData(self, *args): """ Set the data to be drawn. Parameters ---------- x, y : np.ndarray, optional, default None 2D array containing the coordinates of the polygons z : np.ndarray 2D array containing the value which will be maped into the polygons colors. If x and y is None, the polygons will be displaced on a grid otherwise x and y will be used as polygons vertices coordinates as:: (x[i+1, j], y[i+1, j]) (x[i+1, j+1], y[i+1, j+1]) +---------+ | z[i, j] | +---------+ (x[i, j], y[i, j]) (x[i, j+1], y[i, j+1]) "ASCII from: <https://matplotlib.org/3.2.1/api/_as_gen/ matplotlib.pyplot.pcolormesh.html>". """ # Prepare data cd = self._prepareData(args) # Has the view bounds changed shapeChanged = False if self.qpicture is None: shapeChanged = True elif len(args) == 1: if args[0].shape[0] != self.x[:, 1][-1] or args[0].shape[ 1] != self.y[0][-1]: shapeChanged = True elif len(args) == 3: if np.any(self.x != args[0]) or np.any(self.y != args[1]): shapeChanged = True self.qpicture = QtGui.QPicture() p = QtGui.QPainter(self.qpicture) # We set the pen of all polygons once if self.edgecolors is None: p.setPen(fn.mkPen(QtGui.QColor(0, 0, 0, 0))) else: p.setPen(fn.mkPen(self.edgecolors)) if self.antialiasing: p.setRenderHint(QtGui.QPainter.RenderHint.Antialiasing) ## Prepare colormap # First we get the LookupTable pos = [i[0] for i in Gradients[self.cmap]['ticks']] color = [i[1] for i in Gradients[self.cmap]['ticks']] cmap = ColorMap(pos, color) lut = cmap.getLookupTable(0.0, 1.0, 256) # Second we associate each z value, that we normalize, to the lut vmin, vmax = self.z.min(), self.z.max() if self.levels is not None: vmin, vmax = self.levels vmin = max(vmin, self.z.min()) vmax = min(vmax, self.z.max()) norm = self.z - vmin norm_max = vmax - vmin norm = norm / norm_max norm = (norm * (len(lut) - 1)).astype(int) norm[norm < 0] = 0 norm[norm > 255] = 255 # Go through all the data and draw the polygons accordingly for xi in range(self.z.shape[0]): for yi in range(self.z.shape[1]): # Set the color of the polygon first c = lut[norm[xi][yi]] p.setBrush(fn.mkBrush(QtGui.QColor(c[0], c[1], c[2]))) polygon = QtGui.QPolygonF([ QtCore.QPointF(self.x[xi][yi], self.y[xi][yi]), QtCore.QPointF(self.x[xi + 1][yi], self.y[xi + 1][yi]), QtCore.QPointF(self.x[xi + 1][yi + 1], self.y[xi + 1][yi + 1]), QtCore.QPointF(self.x[xi][yi + 1], self.y[xi][yi + 1]) ]) # DrawConvexPlygon is faster p.drawConvexPolygon(polygon) p.end() self.update() self.prepareGeometryChange() if shapeChanged: self.informViewBoundsChanged()