def setGroovePixmapFromProfile(self, profile, colormap=None): """Set the pixmap displayed in the slider groove from histogram values. :param Union[numpy.ndarray,None] profile: 1D array of values to display :param Union[~silx.gui.colors.Colormap,str] colormap: The colormap name or object to convert profile values to colors """ if profile is None: self.setSliderPixmap(None) return profile = numpy.array(profile, copy=False) if profile.size == 0: self.setSliderPixmap(None) return if colormap is None: colormap = colors.Colormap() elif isinstance(colormap, str): colormap = colors.Colormap(name=colormap) assert isinstance(colormap, colors.Colormap) rgbImage = colormap.applyToData(profile.reshape(1, -1))[:, :, :3] qimage = convertArrayToQImage(rgbImage) qpixmap = qt.QPixmap.fromImage(qimage) self.setGroovePixmap(qpixmap)
def testUint8(self): lut = numpy.array([[255, 0, 0], [200, 0, 0], [150, 0, 0]], dtype="uint") colors.registerLUT("test_type", lut) colormap = colors.Colormap(name="test_type") lut = colormap.getNColors(3) self.assertEqual(lut.shape, (3, 4)) self.assertEqual(lut[0, 0], 255)
def testFloatRGB(self): lut = numpy.array([[1.0, 0, 0], [0.5, 0, 0], [0, 0, 0]], dtype="float") colors.registerLUT("test_type", lut) colormap = colors.Colormap(name="test_type") lut = colormap.getNColors(3) self.assertEqual(lut.shape, (3, 4)) self.assertEqual(lut[0, 0], 255)
def testGroove(self): """Test Groove pixmap""" profile = list(range(100)) for cmap in ('jet', colors.Colormap('viridis')): with self.subTest(str(cmap)): self.slider.setGroovePixmapFromProfile(profile, cmap) pixmap = self.slider.getGroovePixmap() self.assertIsInstance(pixmap, qt.QPixmap) self.assertEqual(pixmap.width(), len(profile))
def __createDetectorColormapMesh(self): if self.__geometry is not None: if self.__detector is not None: self.__geometry.detector = self.__detector pixels = self.__geometry.calc_pos_zyx(corners=True) pixels = numpy.array(pixels) pixels = numpy.moveaxis(pixels, 0, -1) else: pixels = self.__detector.get_pixel_corners() # Merge all pixels together pixels = pixels[...] vertices = numpy.reshape(pixels, (-1, 3)) if self.__image is not None: pixelValues = self.__image pixelValues = pixelValues.reshape(-1) else: pixelValues = numpy.zeros(vertices.shape[0] // 4) if self.__mask is not None: mask = self.__mask.reshape(-1) if pixelValues.dtype.kind in "ui": pixelValues = pixelValues.astype(numpy.float) pixelValues[mask != 0] = numpy.float("nan") values = numpy.empty(shape=(vertices.shape[0])) values[0::4] = pixelValues values[1::4] = pixelValues values[2::4] = pixelValues values[3::4] = pixelValues plus = numpy.array([0, 1, 2, 2, 3, 0], dtype=numpy.uint32) indexes = (numpy.atleast_2d( 4 * numpy.arange(vertices.shape[0] // 4, dtype=numpy.uint32)).T + plus).ravel() indexes = indexes.astype(numpy.uint32) colormap = self.__colormap if colormap is None: colormap = colors.Colormap(name="inferno", normalization=colors.Colormap.LOGARITHM) item = mesh.ColormapMesh() item.moveToThread(qt.QApplication.instance().thread()) item.setData(mode="triangles", position=vertices, value=values, indices=indexes, copy=False) item.setColormap(colormap) self.__detectorItem = item return True
def __displayResult(self, result, resetZoom=False): self._plot.clear() if isinstance(result, containers.Integrate1dResult): self._plot.setGraphXLabel("Radial") self._plot.setGraphYLabel("Intensity") self._plot.addHistogram(legend="result1d", align="center", edges=result.radial, color="blue", histogram=result.intensity, resetzoom=False) elif isinstance(result, containers.Integrate2dResult): def computeLocation(result): # Assume that axes are linear if result.intensity.shape[1] > 1: scaleX = (result.radial[-1] - result.radial[0]) / ( result.intensity.shape[1] - 1) else: scaleX = 1.0 if result.intensity.shape[0] > 1: scaleY = (result.azimuthal[-1] - result.azimuthal[0]) / ( result.intensity.shape[0] - 1) else: scaleY = 1.0 halfPixel = 0.5 * scaleX, 0.5 * scaleY origin = (result.radial[0] - halfPixel[0], result.azimuthal[0] - halfPixel[1]) return origin, (scaleX, scaleY) self._plot.setGraphXLabel("Radial") self._plot.setGraphYLabel("Azimuthal") origin, scale = computeLocation(result) colormap = colors.Colormap("inferno", normalization=colors.Colormap.LOGARITHM) self._plot.addImage(legend="result2d", data=result.intensity, origin=origin, scale=scale, colormap=colormap, resetzoom=False) else: logger.error("Unsupported result type %s", type(result)) if resetZoom: self._plot.resetZoom()
def plot2Dsilx(nodeData): from silx.gui.plot import Plot2D from silx.gui import colors saveType = nodeData[0] savedColumns = nodeData[4] for fname, props in savedColumns.items(): maps = read2D(saveType, fname, props) # applied only to one 2D map: plot = Plot2D() plot.setGraphTitle(nodeData[1] + ' ' + saveType) plot.getXAxis().setLabel(label=nodeData[3][0]) plot.getYAxis().setLabel(label=nodeData[3][1]) xOrigin, xScale = 0, 1 yOrigin, yScale = 0, 1 plot.addImage(maps[0], colormap=colors.Colormap('viridis'), origin=(xOrigin, yOrigin), scale=(xScale, yScale)) # plot.saveGraph('test.png') plot.show() # end plot2Dsilx
def replot(self, keepExtent=True): if csi.DEBUG_LEVEL > 50: print('enter replot() of {0}'.format(self.node.name)) if self.onTransform: return if len(csi.allLoadedItems) == 0: return node = self.node if keepExtent: self._storePlotState() # # self.plot.clear() # yUnits = node.getPropList('plotUnit', keys=yNames) # yLabels = node.getPropList('plotLabel', keys=yNames) if node.plotDimension == 1: self.plot.clearCurves() self.plot.clearImages() nPlottedItems = 0 leftAxisColumns, rightAxisColumns = [], [] leftAxisUnits, rightAxisUnits = [], [] for item in csi.allLoadedItems: if not self.shouldPlotItem(item): continue try: x = getattr(item, node.plotXArray) except AttributeError: continue if item.originNode is node: convs = [ cN for (yN, cN) in zip( node.arrays, item.dataFormat['conversionFactors']) if yN in node.plotYArrays ] else: convs = [None for yN in node.plotYArrays] for yN, cN in zip(node.plotYArrays, convs): try: y = getattr(item, yN) except AttributeError: continue curveLabel = item.alias + '.' + yN plotProps = dict(item.plotProps[node.name][yN]) symbolsize = plotProps.pop('symbolsize', 2) z = 1 if item in csi.selectedItems else 0 self.plot.addCurve(x, y, legend=curveLabel, color=item.color, z=z, **plotProps) nPlottedItems += 1 symbol = plotProps.get('symbol', None) if symbol is not None: curve = self.plot.getCurve(curveLabel) if curve is not None: if self.backend['backend'] == 'opengl': # don't know why it is small with opengl symbolsize *= 2 curve.setSymbolSize(symbolsize) curve = self.plot.getCurve(curveLabel) if curve is None: continue yaxis = curve.getYAxis() if yaxis == 'left': if yN not in leftAxisColumns: leftAxisColumns.append(yN) if isinstance(cN, type("")): if cN not in leftAxisUnits: leftAxisUnits.append(cN) else: unit = node.getProp(yN, 'plotUnit') if unit: if unit not in leftAxisUnits: leftAxisUnits.append(unit) if yaxis == 'right': if yN not in rightAxisColumns: rightAxisColumns.append(yN) if isinstance(cN, type("")): if cN not in rightAxisUnits: rightAxisUnits.append(cN) else: unit = node.getProp(yN, 'plotUnit') if unit: if unit not in rightAxisUnits: rightAxisUnits.append(unit) if nPlottedItems == 0: return self.plotLeftYLabel = self._makeYLabel(leftAxisColumns, leftAxisUnits) self.plot.setGraphYLabel(label=self.plotLeftYLabel, axis='left') self.plotRightYLabel = self._makeYLabel(rightAxisColumns, rightAxisUnits) self.plot.setGraphYLabel(label=self.plotRightYLabel, axis='right') if node.plotDimension == 2: self.plot.clearCurves() self.plot.clearImages() if len(csi.selectedItems) > 0: item = csi.selectedItems[0] # it could be the last one but # then when goint with arrows up and down in the data tree and # passing a group that becomes selected, the displayed item # jumps between the first and the last elif len(csi.allLoadedItems) > 0: item = csi.allLoadedItems[-1] else: return try: image = getattr(item, self.node.plot2DArray) except AttributeError: return xOrigin, xScale = self.getCalibration(item, 'x') yOrigin, yScale = self.getCalibration(item, 'y') self.plot.addImage(image, colormap=colors.Colormap(COLORMAP), origin=(xOrigin, yOrigin), scale=(xScale, yScale)) if node.plotDimension == 3: self.plot._plot.clearImages() item = None if len(csi.selectedItems) > 0: item = csi.selectedItems[0] elif len(csi.allLoadedItems) > 0: item = csi.allLoadedItems[-1] else: return try: stack = getattr(item, self.node.plot3DArray) if item else None except AttributeError: return if item: calibrations = [self.getCalibration(item, ax) for ax in 'xyz'] self.plot.setStack(stack, calibrations=calibrations) if keepExtent: self._restorePlotState() if hasattr(self.transformWidget, 'extraPlot'): self.transformWidget.extraPlot() # if self.wasNeverPlotted and node.plotDimension == 1: # self.plot.resetZoom() self.wasNeverPlotted = False if csi.DEBUG_LEVEL > 50: print('exit replot() of {0}'.format(self.node.name))
def __createDetectorMesh(self): if self.__geometry is not None: if self.__detector is not None: self.__geometry.detector = self.__detector pixels = self.__geometry.calc_pos_zyx(corners=True) pixels = numpy.array(pixels) pixels = numpy.moveaxis(pixels, 0, -1) else: pixels = self.__detector.get_pixel_corners() height, width, _, _, = pixels.shape nb_vertices = width * height * 6 # Allocate contiguous memory positions_array = numpy.empty((nb_vertices, 3), dtype=numpy.float32) colors_array = numpy.empty((nb_vertices, 4), dtype=numpy.float32) # Merge all pixels together pixels = pixels[...] pixels = numpy.reshape(pixels, (-1, 4, 3)) image = self.__image mask = self.__mask colormap = self.__colormap if colormap is None: colormap = colors.Colormap("inferno") # Normalize the colormap as a RGBA float lookup table lut = colormap.getNColors(256) lut = lut / 255.0 cursor_color = colors.cursorColorForColormap(colormap.getName()) cursor_color = numpy.array(colors.rgba(cursor_color)) # Normalize the image as lookup table to colormap lookup table if image is not None: image = image.view() image.shape = -1 image = numpy.log(image) info = silx.math.combo.min_max(image, min_positive=True, finite=True) image = (image - info.min_positive) / float(info.maximum - info.min_positive) image = (image * 255.0).astype(int) image = image.clip(0, 255) if mask is not None: mask = mask.view() mask.shape = -1 masked_color = numpy.array([1.0, 0.0, 1.0, 1.0]) default_color = numpy.array([0.8, 0.8, 0.8, 1.0]) triangle_index = 0 color_index = 0 self.emitProgressValue(10, force=True) for npixel, pixel in enumerate(pixels): percent = 10 + int(90 * (npixel / len(pixels))) self.emitProgressValue(percent) if self.isInterruptionRequested(): return False masked = False if mask is not None: masked = mask[npixel] != 0 if masked: color = masked_color elif image is not None: color_id = image[color_index] color = lut[color_id] else: color = default_color positions_array[triangle_index + 0] = pixel[0] positions_array[triangle_index + 1] = pixel[1] positions_array[triangle_index + 2] = pixel[2] colors_array[triangle_index + 0] = color colors_array[triangle_index + 1] = color colors_array[triangle_index + 2] = color triangle_index += 3 positions_array[triangle_index + 0] = pixel[2] positions_array[triangle_index + 1] = pixel[3] positions_array[triangle_index + 2] = pixel[0] colors_array[triangle_index + 0] = color colors_array[triangle_index + 1] = color colors_array[triangle_index + 2] = color triangle_index += 3 color_index += 1 item = mesh.Mesh() item.moveToThread(qt.QApplication.instance().thread()) item.setData(position=positions_array, color=colors_array, copy=False) self.__detectorItem = item return True