def compareGraphsVisually(graph1, graph2, fig=None): """ compareGraphsVisually(graph1, graph2, fig=None) Show the two graphs together in a figure. Matched nodes are indicated by lines between them. """ # Get figure if isinstance(fig,int): fig = vv.figure(fig) elif fig is None: fig = vv.figure() # Prepare figure and axes fig.Clear() a = vv.gca() a.cameraType = '3d'; a.daspectAuto = False # Draw both graphs graph1.Draw(lc='b', mc='b') graph2.Draw(lc='r', mc='r') # Set the limits a.SetLimits() # Make a line from the edges pp = Pointset(3) for node in graph1: if hasattr(node, 'match') and node.match is not None: pp.append(node); pp.append(node.match) # Plot edges vv.plot(pp, lc='g', ls='+')
def __init__(self): # Create figure and axes vv.figure() self._a = a = vv.gca() vv.title("Hold mouse to draw lines. Use 'rgbcmyk' and '1-9' keys.") # Set axes a.SetLimits((0, 1), (0, 1)) a.cameraType = "2d" a.daspectAuto = False a.axis.showGrid = True # Init variables needed during drawing self._active = None self._pp = Pointset(2) # Create null and empty line objects self._line1 = None self._line2 = vv.plot(vv.Pointset(2), ls="+", lc="c", lw="2", axes=a) # Bind to events a.eventMouseDown.Bind(self.OnDown) a.eventMouseUp.Bind(self.OnUp) a.eventMotion.Bind(self.OnMotion) a.eventKeyDown.Bind(self.OnKey)
def draw( self ): """Draw data.""" if len(self.fitResults) == 0: return # Make sure our figure is the active one vv.figure(self.fig.nr) if not hasattr( self, 'subplot1' ): self.subplot1 = vv.subplot(211) #self.subplot1.position = (30, 2, -32, -32) self.subplot2 = vv.subplot(212) #self.subplot1.position = (30, 2, -32, -32) a, ed = numpy.histogram(self.fitResults['tIndex'], self.Size[0]/6) print((float(numpy.diff(ed[:2])))) self.subplot1.MakeCurrent() vv.cla() vv.plot(ed[:-1], a/float(numpy.diff(ed[:2])), lc='b', lw=2) #self.subplot1.set_xticks([0, ed.max()]) #self.subplot1.set_yticks([0, numpy.floor(a.max()/float(numpy.diff(ed[:2])))]) self.subplot2.MakeCurrent() vv.cla() #cs = csa = numpy.cumsum(a) vv.plot(ed[:-1], csa/float(csa[-1]), lc='g', lw=2) #self.subplot2.set_xticks([0, ed.max()]) #self.subplot2.set_yticks([0, a.sum()]) self.fig.DrawNow() self.subplot1.position = (20, 2, -22, -32) self.subplot2.position = (20, 2, -22, -32)
def plot(image): # ax = vv.gca() # ms = vv.Mesh(ax) logging.warning([image.shape, image.spacing]) vol = image[:, :, :, 0] logging.warning([vol.min(), vol.max()]) vol = util.normalize(vol, 'ADCm') logging.warning([vol.min(), vol.max()]) vol = vv.Aarray(vol, image.spacing) cmap = None # cmap = vv.CM_VIRIDIS render_style = 'mip' # render_style = 'iso' # render_style = 'ray' # render_style = 'edgeray' # render_style = 'litray' vv.figure() vv.xlabel('x axis') vv.ylabel('y axis') vv.zlabel('z axis') a1 = vv.subplot(111) t1 = vv.volshow(vol, cm=cmap, renderStyle=render_style) t1.isoThreshold = 0.7 vv.title(render_style) # a1.camera = a2.camera = a3.camera vv.ColormapEditor(a1)
def _createWindow(self, name, im, axis): vv.figure() vv.gca() vv.clf() fig = vv.imshow(im) dims = im.shape ''' Change color bounds ''' if im.dtype == np.uint8: fig.clim.Set(0, 255) else: fig.clim.Set(0., 1.) fig.GetFigure().title = name ''' Show ticks on axes? ''' if not axis: fig.GetAxes().axis.visible = False bgcolor = (0.,0.,0.) else: fig.GetAxes().axis.showBox = False bgcolor = (1.,1.,1.) ''' Set background color ''' fig.GetFigure().bgcolor = bgcolor fig.GetAxes().bgcolor = bgcolor ''' Setup keyboard event handler ''' fig.eventKeyDown.Bind(self._keyHandler) win = {'name':name, 'canvas':fig, 'shape':dims, 'keyEvent':None, 'text':[]} self.open_windows.append(win) return win
def main(select=3, **kwargs): """Script main function. select: int 1: Medical data 2: Blocky data, different every time 3: Two donuts 4: Ellipsoid """ import visvis as vv # noqa: delay import visvis and GUI libraries # Create test volume if select == 1: vol = vv.volread('stent') isovalue = kwargs.pop('level', 800) elif select == 2: vol = vv.aVolume(20, 128) isovalue = kwargs.pop('level', 0.2) elif select == 3: with timer('computing donuts'): vol = donuts() isovalue = kwargs.pop('level', 0.0) # Uncommenting the line below will yield different results for # classic MC # vol *= -1 elif select == 4: vol = ellipsoid(4, 3, 2, levelset=True) isovalue = kwargs.pop('level', 0.0) else: raise ValueError('invalid selection') # Get surface meshes with timer('finding surface lewiner'): vertices1, faces1 = marching_cubes_lewiner(vol, isovalue, **kwargs)[:2] with timer('finding surface classic'): vertices2, faces2 = marching_cubes_classic(vol, isovalue, **kwargs) # Show vv.figure(1) vv.clf() a1 = vv.subplot(121) vv.title('Lewiner') m1 = vv.mesh(np.fliplr(vertices1), faces1) a2 = vv.subplot(122) vv.title('Classic') m2 = vv.mesh(np.fliplr(vertices2), faces2) a1.camera = a2.camera # visvis uses right-hand rule, gradient_direction param uses left-hand rule m1.cullFaces = m2.cullFaces = 'front' # None, front or back vv.use().Run()
def refresh(self): if len(self._value) > 1: vv.figure(self._fig.nr) a = vv.gca() view = a.GetView() a.Clear() vv.volshow3(self._value, renderStyle="mip", cm=self._colorMap) if not self._first: a = vv.gca() a.SetView(view) self._first = False
def initControl(self): self._form = QtGui.QWidget();layout = QtGui.QVBoxLayout();layout.setMargin(0);self._form.setLayout( layout ) self._app = vv.use('pyqt4') self._first=True Figure = self._app.GetFigureClass() self._fig = Figure(self._form) vv.figure(self._fig.nr) policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) widget = self._fig._widget widget.setSizePolicy(policy) layout.addWidget(widget)
def figure(figure=None): f = None if figure == None: f = vv.figure() else: try: f = vv.figure(figure) except: f = vv.figure() f._widget.show() f._widget.raise_() return f
def _call_new_item(self, key, item_type, *args, **kwargs): if key in self.items: # an item with that key already exists # should raise an exception or warning pass else: # make this the current figure vv.figure(self.figure) # create a new dictionary of options for plotting plot_kwargs = dict() if 'line_width' in kwargs: value = kwargs.pop('line_width') plot_kwargs['lw'] = value if 'marker_width' in kwargs: value = kwargs.pop('marker_width') plot_kwargs['mw'] = value if 'marker_edge_width' in kwargs: value = kwargs.pop('marker_edge_width') plot_kwargs['mew'] = value if 'line_color' in kwargs: value = kwargs.pop('line_color') plot_kwargs['lc'] = value if 'marker_color' in kwargs: value = kwargs.pop('marker_color') plot_kwargs['mc'] = value if 'marker_edge_color' in kwargs: value = kwargs.pop('marker_edge_color') plot_kwargs['mec'] = value if 'line_style' in kwargs: value = kwargs.pop('line_style') plot_kwargs['ls'] = value if 'marker_style' in kwargs: value = kwargs.pop('marker_style') plot_kwargs['ms'] = value if 'adjust_axes' in kwargs: value = kwargs.pop('adjust_axes') plot_kwargs['axesAdjust'] = value # create the plot item if item_type == 'circular': data = pythics.lib.CircularArray(cols=2, length=kwargs['length']) item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs) elif item_type == 'growable': data = pythics.lib.GrowableArray(cols=2, length=kwargs['length']) item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs) else: data = np.array([]) item = vv.plot(np.array([]), np.array([]), axes=self.axes, **plot_kwargs) self.items[key] = (item_type, data, item)
def initForm(self): self._form = QtGui.QWidget();layout = QtGui.QVBoxLayout();layout.setMargin(0);self._form.setLayout( layout ) self._app = vv.use('pyqt4') self._app.Create() self._first=True Figure = self._app.GetFigureClass() self._fig = Figure(self._form) vv.figure(self._fig.nr) policy = QtGui.QSizePolicy(QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) widget = self._fig._widget widget.setSizePolicy(policy) widget.setMinimumSize(100, 100) layout.addWidget(widget) self._colorMap = vv.CM_AUTUMN self._colors_limits = None
def show(self): import visvis as vv # If there are many tests, make a selection if len(self._tests) > 1000: tests = random.sample(self._tests, 1000) else: tests = self._tests # Get ticks nn = [test[0] for test in tests] # Create figure vv.figure(1) vv.clf() # Prepare kwargs plotKwargsText = {'ms':'.', 'mc':'b', 'mw':5, 'ls':''} plotKwargsBin = {'ms':'.', 'mc':'r', 'mw':5, 'ls':''} # File size against number of elements vv.subplot(221) vv.plot(nn, [test[2][0] for test in tests], **plotKwargsText) vv.plot(nn, [test[2][1] for test in tests], **plotKwargsBin) vv.legend('text', 'binary') vv.title('File size') # Speed against number of elements vv.subplot(223) vv.plot(nn, [test[1][4] for test in tests], **plotKwargsText) vv.plot(nn, [test[1][6] for test in tests], **plotKwargsBin) vv.legend('text', 'binary') vv.title('Save time') # Speed (file) against number of elements vv.subplot(224) vv.plot(nn, [test[1][5] for test in tests], **plotKwargsText) vv.plot(nn, [test[1][7] for test in tests], **plotKwargsBin) vv.legend('text', 'binary') vv.title('Load time')
def set_plot_properties(self, **kwargs): # make this the current figure vv.figure(self.figure) if 'antialiasing' in kwargs: value = kwargs.pop('antialiasing') p_w.setAntialiasing(value) if 'background' in kwargs: value = kwargs.pop('background') p_w.setBackground(value) if 'aspect_ratio' in kwargs: # 'auto', 'equal', or a number value = kwargs.pop('aspect_ratio') if value == 'auto': self.axes.daspectAuto = True elif value == 'equal': self.axes.daspectAuto = False self.axes.daspect = (1, 1) if 'x_auto_scale' in kwargs: value = kwargs.pop('x_auto_scale') if 'y_auto_scale' in kwargs: value = kwargs.pop('y_auto_scale') if 'x_scale' in kwargs: value = kwargs.pop('x_scale') if 'y_scale' in kwargs: value = kwargs.pop('y_scale') if 'title' in kwargs: value = kwargs.pop('title') vv.title(value) if 'x_label' in kwargs: value = kwargs.pop('x_label') self.axes.axis.xLabel = value if 'y_label' in kwargs: value = kwargs.pop('y_label') self.axes.axis.yLabel = value if 'x_grid' in kwargs: value = kwargs.pop('x_grid') p_i.showGrid(x=value) if 'y_grid' in kwargs: value = kwargs.pop('y_grid') p_i.showGrid(y=value)
def crop3d(vol, fig=None): """ crop3d(vol, fig=None) Manually crop a volume. In the given figure (or a new figure if None), three axes are created that display the transversal, sagittal and coronal MIPs (maximum intensity projection) of the volume. The user can then use the mouse to select a 3D range to crop the data to. """ app = vv.use() # Create figure? if fig is None: fig = vv.figure() figCleanup = True else: fig.Clear() figCleanup = False # Create three axes and a wibject to attach text labels to a1 = vv.subplot(221) a2 = vv.subplot(222) a3 = vv.subplot(223) a4 = vv.Wibject(fig) a4.position = 0.5, 0.5, 0.5, 0.5 # Set settings for a in [a1, a2, a3]: a.showAxis = False # Create cropper3D instance cropper3d = Cropper3D(vol, a1, a3, a2, a4) # Enter a mainloop while not cropper3d._finished: vv.processEvents() time.sleep(0.01) # Clean up figure (close if we opened it) fig.Clear() fig.DrawNow() if figCleanup: fig.Destroy() # Obtain ranges rx = cropper3d._range_transversal._rangex ry = cropper3d._range_transversal._rangey rz = cropper3d._range_coronal._rangey # Perform crop vol2 = vol[rz.min:rz.max, ry.min:ry.max, rx.min:rx.max] # Done return vol2
def createWindow(self, name, im, axis): vv.figure() vv.gca() vv.clf() fig = vv.imshow(im) dims = im.shape ''' Change color bounds ''' if im.dtype == np.uint8: fig.clim.Set(0, 255) else: fig.clim.Set(im.min(), im.max()) fig.GetFigure().title = name ''' Show ticks on axes? ''' if not axis: fig.GetAxes().axis.visible = False bgcolor = (0.,0.,0.) else: fig.GetAxes().axis.showBox = False bgcolor = (1.,1.,1.) fig.GetFigure().bgcolor = bgcolor fig.GetAxes().bgcolor = bgcolor fig.eventKeyUp.Bind(self.keyHandler) win = {'name':name, 'figure':fig, 'shape':dims, 'keyEvent':None} self.open_windows.append(win) return win
def gcf(): """ gcf() Get the current figure. If there is no figure yet, figure() is called to create one. To make a figure current, use Figure.MakeCurrent(). See also gca() """ if not BaseFigure._figures: # no figure yet return vv.figure() nr = BaseFigure._currentNr if not nr in BaseFigure._figures: # erroneous nr nr = BaseFigure._figures.keys()[0] BaseFigure._currentNr = nr return BaseFigure._figures[nr]
def getOpenGlInfo(): """ getOpenGlInfo() Get information about the OpenGl version on this system. Returned is a tuple (version, vendor, renderer, extensions) A figure is created and removed to create an openGl context if this is necessary. """ # Open figure first. On Windows we can try obtaining the information, # but I found that on Ubuntu a segfault will happen (but this might # very well have to do with the OpenGl drivers). fig = vv.figure() result = vv.misc.getOpenGlInfo() # Should we open a figure and try again? fig.Destroy() fig._ProcessGuiEvents() # so it can close return result
def __init__(self, c=None, p1=None, p2=None): # Init visualization fig = vv.figure(101); vv.clf() a = vv.gca() # Init patch self._patchSize = patchSize = 64 self._im = np.zeros((patchSize,patchSize), dtype=np.float32) self._t = vv.imshow(self._im, clim=(0,10)) # Init points if c is None: c = Point(14,12) if p1 is None: p1 = Point(12,16) if p2 is None: p2 = Point(16,16) # self._c = vv.plot(c, ls='', ms='+', mw=10, mc='k') self._p1 = vv.plot(p1, ls='', ms='.', mw=10, mc='r') self._p2 = vv.plot(p2, ls='', ms='.', mw=10, mc='b') # Init object being moved self._movedPoint = None # Enable callbacks for line in [self._c, self._p1, self._p2]: line.hitTest = True line.eventMouseDown.Bind(self.OnDown) line.eventMotion.Bind(self.OnMotion) line.eventMouseUp.Bind(self.OnUp) a.eventMotion.Bind(self.OnMotion) a.eventMouseUp.Bind(self.OnUp) # Start self.Apply()
s2 = loadvol(basedir, ptcode, ctcode, 'ring', staticref) except FileNotFoundError: s2 = loadvol(basedir, ptcode, ctcode, 'ring', staticref) vol = s2.vol s3 = loadvol(basedir, ptcode, ctcode, cropname, 'phases') vol0ori = s3.vol0 # todo: backward/forward based on how deforms were obtained?? # deforms was obtained as backward, from original phases to mean volume avgreg deform = pirt.DeformationFieldBackward(deforms[0]) # vol2 = pirt.interp.deform_backward(vol, deforms[0]) # te low level, gebruikt awarp niet vol2 = deform.inverse().as_backward().apply_deformation( vol0ori) # gebruikt pirt deformation.py vv.figure(1) vv.clf() a1 = vv.subplot(131) t1 = vv.volshow(vol) a1.daspect = (1, 1, -1) vv.title('vol average of cardiac cycle') # vv.figure(2); vv.clf() a2 = vv.subplot(132) t2 = vv.volshow(vol2) a2.daspect = (1, 1, -1) vv.title('vol 0 deformed to avg volume') # vv.figure(3); vv.clf() a3 = vv.subplot(133) t3 = vv.volshow2((vol2 - vol), clim=(-500, 500)) a3.daspect = (1, 1, -1) vv.title('difference')
def _Plot(self, *args): vv.figure(self.figure.nr) vv.clf() vv.plot([1,2,3,1,6]) vv.legend(['this is a line'])
# read # use floats to prevent strides etc. uint8 caused crash on qt backend. im = gl.glReadPixels(x, y, w, h, gl.GL_RGB, gl.GL_FLOAT) # reshape, flip, and store im.shape = h, w, 3 im = np.flipud(im) # done return im if __name__ == '__main__': # Prepare f = vv.figure() a1 = vv.subplot(211) a2 = vv.subplot(212) # Draw some data vv.plot([2, 3, 4, 2, 4, 3], axes=a1) f.DrawNow() # Take snapshots im1 = vv.getframe(f) im2 = vv.getframe(a1) # clear and show snapshots a1.Clear() a2.Clear() vv.imshow(im1, axes=a1, clim=(0, 1)) vv.imshow(im2, axes=a2, clim=(0, 1))
im = np.random.normal(0.0, 0.1, (101, 101)).astype('float32') # Create circle circLoc = circLocs[i] for y in range(im.shape[0]): for x in range(im.shape[1]): #if (y-circLoc[0])**2 + (x-circLoc[1])**2 < radius**2: # circles if abs(y - circLoc[0]) + abs( x - circLoc[1]) < radius * 1.1: # diamonds im[y, x] += 1.0 # Add ims.append(im) INDEXMAP = {0: 1, 1: 2, 2: 4, 3: 3} # map index to subplot location # Show images fig = vv.figure(1) vv.clf() fig.position = 200, 200, 500, 500 for i in range(4): j = INDEXMAP[i] # map index to subplot location a = vv.subplot(2, 2, j) vv.imshow(ims[i]) a.axis.visible = False # vv.screenshot('c:/almar/projects/fourBlocks_initial.jpg', vv.gcf(), sf=2, bg='w') ## Register groupwise # Init figure for registration fig = vv.figure(2) vv.clf() fig.position = 200, 100, 900, 500
Close a figure. fig can be a Figure object or an integer representing the id of the figure to close. Note that for the first case, you migh also call fig.Destroy(). """ if isinstance(fig, int): figDict = vv.BaseFigure._figures if fig in figDict: figDict[fig].Destroy() else: raise ValueError("A figure whith that id does not exist: " + str(fig)) elif isinstance(fig, vv.BaseFigure): fig.Destroy() else: raise ValueError("Invalid argument for vv.functions.close") if __name__ == "__main__": import time # Create figure fig = vv.figure(1) vv.processEvents() vv.processEvents() time.sleep(1.0) # Close it vv.close(1) # Note: you can also pus the fig object
ms.edgeColor = edgeColor ms.edgeShading = edgeShading ms.faceColor = faceColor ms.shininess = shininess ms.specular = specular ms.emission = emission ax.SetLimits(rangeX=[-depRange[0], depRange[0]], rangeY=[-depRange[0], depRange[0]], rangeZ=[-depRange[0], depRange[0]]) # Start of test code. if __name__ == '__main__': # Create figure fig = vv.figure() fig.position.w = 600 # Cartesian plot numOfPts = 2000 scale = 1 # Create random points xyz = 2 * scale * (np.random.rand(numOfPts, 3) - 0.5) # 2D sync function xyz[:, 2] = np.sinc(5 * (np.sqrt(xyz[:, 0]**2 + xyz[:, 1]**2))) #xyz[:,2] = scale - ( xyz[:,0]**2 + xyz[:,1]**2) # Plot vv.subplot(121)
def demo(*args, **kwargs): import math m = 80 # width of grid n = m ** 2 # number of points minVal = -2.0 maxVal = 2.0 delta = (maxVal - minVal) / (m - 1) X, Y = numpy.mgrid[minVal:maxVal + delta:delta, minVal:maxVal + delta:delta] X = X.flatten() Y = Y.flatten() Z = numpy.sin(X) * numpy.cos(Y) # Create the data point-matrix M = numpy.array([X, Y, Z]).T # Translation values (a.u.): Tx = 0.5 Ty = -0.3 Tz = 0.2 # Translation vector T = numpyTransform.translation(Tx, Ty, Tz) S = numpyTransform.scaling(1.0, N=4) # Rotation values (rad.): rx = 0.3 ry = -0.2 rz = 0.05 Rx = numpy.matrix([[1, 0, 0, 0], [0, math.cos(rx), -math.sin(rx), 0], [0, math.sin(rx), math.cos(rx), 0], [0, 0, 0, 1]]) Ry = numpy.matrix([[math.cos(ry), 0, math.sin(ry), 0], [0, 1, 0, 0], [-math.sin(ry), 0, math.cos(ry), 0], [0, 0, 0, 1]]) Rz = numpy.matrix([[math.cos(rz), -math.sin(rz), 0, 0], [math.sin(rz), math.cos(rz), 0, 0], [0, 0, 1, 0], [0, 0, 0, 1]]) # Rotation matrix R = Rx * Ry * Rz transformMat = numpy.matrix(numpy.identity(4)) transformMat *= T transformMat *= R transformMat *= S # Transform data-matrix plus noise into model-matrix D = numpyTransform.transformPoints(transformMat, M) # Add noise to model and data M = M + 0.01 * numpy.random.randn(n, 3) D = D + 0.01 * numpy.random.randn(n, 3) # Run ICP (standard settings) initialGuess = numpy.array([0.0, 0.0, 0.0, 0.0, 0.0, 0.0]) lowerBounds = numpy.array([-pi, -pi, -pi, -100.0, -100.0, -100.0]) upperBounds = numpy.array([pi, pi, pi, 100.0, 100.0, 100.0]) icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='fmincon', **kwargs) # icp = ICP(M, D, maxIterations=15, dataDownsampleFactor=1, minimizeMethod='point', **kwargs) transform, err, t = icp.runICP(x0=initialGuess, lb=lowerBounds, ub=upperBounds) # Transform data-matrix using ICP result Dicp = numpyTransform.transformPoints(transform[-1], D) # Plot model points blue and transformed points red if False: import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D fig = plt.figure() ax = fig.add_subplot(2, 2, 1, projection='3d') ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o') ax.scatter(D[:, 0], D[:, 1], D[:, 2], c='b', marker='^') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax = fig.add_subplot(2, 2, 2, projection='3d') ax.scatter(M[:, 0], M[:, 1], M[:, 2], c='r', marker='o') ax.scatter(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], c='b', marker='^') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') ax.set_zlabel('Z Label') ax = fig.add_subplot(2, 2, 3) ax.plot(t, err, 'x--') ax.set_xlabel('X Label') ax.set_ylabel('Y Label') plt.show() else: import visvis as vv app = vv.use() vv.figure() vv.subplot(2, 2, 1) vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o') vv.plot(D[:, 0], D[:, 1], D[:, 2], lc='r', ls='', ms='x') vv.xlabel('[0,0,1] axis') vv.ylabel('[0,1,0] axis') vv.zlabel('[1,0,0] axis') vv.title('Red: z=sin(x)*cos(y), blue: transformed point cloud') # Plot the results vv.subplot(2, 2, 2) vv.plot(M[:, 0], M[:, 1], M[:, 2], lc='b', ls='', ms='o') vv.plot(Dicp[:, 0], Dicp[:, 1], Dicp[:, 2], lc='r', ls='', ms='x') vv.xlabel('[0,0,1] axis') vv.ylabel('[0,1,0] axis') vv.zlabel('[1,0,0] axis') vv.title('ICP result') # Plot RMS curve vv.subplot(2, 2, 3) vv.plot(t, err, ls='--', ms='x') vv.xlabel('time [s]') vv.ylabel('d_{RMS}') vv.title('KD-Tree matching') if 'optAlg' in kwargs: opt2 = nlopt.opt(kwargs['optAlg'], 2) vv.title(opt2.get_algorithm_name()) del opt2 else: vv.title('KD-Tree matching') app.Run()
def show_result(self, how=None, fig=None): """ show_result(self, how=None, fig=None) Convenience method to show the registration result. Only works for two dimensional data. Requires visvis. """ # Check if dimension ok if self._ims[0].ndim != 2: raise RuntimeError('show_result only works for 2D data.') # Check if result is set if not self._deforms: raise RuntimeError('The result is not available; run register().') # Make how lower if string if isinstance(how, str): how = how.lower() # Import visvis import visvis as vv # Create figure if fig is None: fig = vv.figure() else: fig = vv.figure(fig.nr) fig.Clear() if how in [None, 'grid', 'diff', 'dx', 'dy']: # Title map title_map = ['Moving', 'Static', 'Deformed', 'Grid'] # Get deform deform = self.get_final_deform(0, 1) # Create third image im1_ = deform.apply_deformation(self._ims[0]) # Create fourth image if how in [None, 'grid']: im2_ = create_grid_image(im1_.shape, im1_.sampling) im2_ = deform.apply_deformation(im2_) elif how == 'diff': im2_ = np.abs(im1_ - self._ims[1]) title_map[3] = 'Diff' elif how == 'dx': im2_ = deform[1] title_map[3] = 'dx' elif how == 'dy': im2_ = deform[0] title_map[3] = 'dy' # Set images ims = [self._ims[0], self._ims[1], im1_, im2_] # Imshow all figures aa, tt = [], [] for i in range(len(ims)): a = vv.subplot(2, 2, i + 1) t = vv.imshow(ims[i]) vv.title(title_map[i]) a.axis.visible = False aa.append(a) tt.append(t) # Done return tuple(tt)
def plot_3d_orientation_map(name, lat_data, azth_data, radius_structure_elem=1, output_dir=None, width=512, height=512, camera_azth=44.5, camera_elev=35.8, camera_roll=0.0, camera_fov=35.0, camera_zoom=0.0035, camera_loc=(67.0, 81.6, 45.2), xlabel='', ylabel='', zlabel='', axis_color='w', background_color='k'): """Renders orientation data in 3D with RGB angular color-coding. Parameters ---------- name : str Indicates the name of the output png file. lat_data : 3D array Indicates the 3D array containing latitude / elevation angle at every point of the skeleton in radians. azth_data : 3D array Indicates the 3D array containing azimuth angle at every point of the skeleton in radians. radius_structure_elem : integer Indicates the size of the structure element of the dilation process to thicken the skeleton. output_dir : str Indicates the path to the output folder where the image will be stored. width : int Indicates the width of the visualization window. height : int Indicates the width of the visualization window. camera_azth : float Indicates the azimuth angle of the camera. camera_elev : float Indicates the latitude / elevation angle of the camera. camera_roll : float Indicates the roll angle of the camera. camera_fov : float Indicates the field of view of the camera. camera_zoom : float Indicates the zoom level of the camera. camera_loc : tuple Indicates the camera location. xlabel : str Indicates the label along the x-axis. ylabel : str Indicates the label along the y-axis. zlabel : str Indicates the label along the z-axis. axis_color : str Indicates the color of axes. background_color : str Indicates the background color of the figure. """ if not visvis_available: print( 'The visvis package is not found. The visualization cannot be done.' ) return rmin, rmax, cmin, cmax, zmin, zmax = _bbox_3D(azth_data) azth, lat = azth_data[rmin:rmax, cmin:cmax, zmin:zmax], \ np.abs(lat_data[rmin:rmax, cmin:cmax, zmin:zmax]) skel = azth.copy().astype(np.float32) skel[skel.nonzero()] = 1. azth = ndi.grey_dilation(azth, structure=morphology.ball(radius_structure_elem)) lat = ndi.grey_dilation(lat, structure=morphology.ball(radius_structure_elem)) skel = ndi.binary_dilation( skel, structure=morphology.ball(radius_structure_elem)) Z, Y, X = skel.nonzero() vol_orient = np.zeros(skel.shape + (3, ), dtype=np.float32) print(vol_orient.size, vol_orient[skel.nonzero()].size) for z, y, x in zip(Z, Y, X): vol_orient[z, y, x] = geo2rgb(lat[z, y, x], azth[z, y, x]) app = vv.use() fig = vv.figure() fig._currentAxes = None fig.relativeFontSize = 2. fig.position.w = width fig.position.h = height t = vv.volshow(vol_orient[:, :, :], renderStyle='iso') t.isoThreshold = 0.5 a = vv.gca() a.camera.azimuth = camera_azth a.camera.elevation = camera_elev a.camera.roll = camera_roll a.camera.fov = camera_fov a.camera.zoom = camera_zoom a.camera.loc = camera_loc a.bgcolor = background_color a.axis.axisColor = axis_color a.axis.xLabel = xlabel a.axis.yLabel = ylabel a.axis.zLabel = zlabel # def mouseUp(event): # print 'mouseUp!!' # a = vv.gca() # print a.camera.GetViewParams() # # a.eventMouseUp.Bind(mouseUp) # fig.eventMouseUp.Bind(mouseUp) # # a.Draw() # fig.DrawNow() if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) vv.screenshot(os.path.join(output_dir, f'{name}_3d_orientation.png'), sf=1, bg=background_color) app.Run()
#!/usr/bin/env python import visvis as vv # Create figure and make it wider than the default fig = vv.figure() fig.position.w = 700 # Create first axes a1 = vv.subplot(121) # Display an image im = vv.imread('lena.png') # returns a numpy array texture2d = vv.imshow(im) texture2d.interpolate = True # if False the pixels are visible when zooming in # Display two lines (values obtained via vv.ginput()) x = [220, 258, 308, 336, 356, 341, 318, 311, 253, 225, 220] y = [287, 247, 212, 201, 253, 318, 364, 385, 382, 358, 287] line1 = vv.plot(x, y, ms='.', mw=4, lw=2) # x = [237, 284, 326, 352, 381, 175, 195, 217, 232, 237] y = [385, 386, 394, 413, 507, 507, 476, 441, 399, 385] line2 = vv.plot(x, y, ms='s', mw=4, lw=2) # The appearance of the line objects can be set in their # constructor, or by using their properties line1.lc, line1.mc = 'g', 'b' line2.lc, line2.mc = 'y', 'r' # Display a legend
def _Plot(self, *args): vv.figure(self.figure.nr) vv.clf() vv.plot([1, 2, 3, 1, 6]) vv.legend(['this is a line'])
def plot_reference_sphere(theta=0, phi=0, isometric=True, ax=None, azimuth=None, elevation=None, degrees=True, labels=True, light_ambient=.6, zoom=1.4, arrow_color=(.25, .95, .8), close_figure=False): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION import visvis as vv if ax is None: app = vv.use() fig = vv.figure() ax = vv.subplot(111) else: app = None fig = ax.GetFigure() ax.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' # coordinate system length = 1.4 cyl_diameter = .05 for i in range(3): direction = np.zeros((3, )) direction[i] = 1 cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(cyl_diameter, cyl_diameter, length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = (.75, .75, .75) translation = np.zeros((3, )) translation[i] = length cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = (.75, .75, .75) # example direction length = 1 shrink = .825 direction = sph2cart(1, theta, phi, degrees=degrees).ravel() cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = arrow_color translation = direction * shrink cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = arrow_color # indicate unit sphere sphere = vv.solidSphere((0, 0, 0), N=100, M=100) sphere.faceColor = (.5, .5, .5, .25) # some lines on sphere indicating main axes phi = np.linspace(0, 2 * np.pi, 100) theta = np.ones_like(phi) * np.pi / 2. r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) theta = np.linspace(-np.pi, np.pi, 100) phi = np.ones_like(theta) * 0 r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) theta = np.linspace(-np.pi, np.pi, 100) phi = np.ones_like(theta) * np.pi / 2. r = np.ones_like(phi) xyz = sph2cart(r, theta, phi, degrees=False) vv.plot(xyz[:, 0], xyz[:, 1], xyz[:, 2], lw=1, lc=(.5, .5, .5), ls="-", mc='b', axesAdjust=False, axes=ax) # add pitch and roll axes aa = np.deg2rad(np.linspace(45, 315, 100) - 90) r = .25 + .025 d = 1.25 + .05 color = (.25, .25, .25) # pitch rotation (in x/z plane, i.e. around y-axis) xx = r * np.cos(aa) zz = r * np.sin(aa) yy = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[0], yy[0], zz[0]) direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if labels: vv.Text(ax, 'Pitch', x=0, y=1.25 * d, z=.25, fontSize=28, color=color) # roll rotation (in y/z plane, i.e. around x-axis) yy = r * np.cos(aa) zz = r * np.sin(aa) xx = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[-1], yy[-1], zz[-1]) direction = (xx[-1] - xx[-2], yy[-1] - yy[-2], zz[-1] - zz[-2]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if labels: vv.Text(ax, 'Roll', x=1.25 * d, y=-.8, z=0, fontSize=28, color=color) # set camera view zoom_ = vv.view()['zoom'] if isometric: vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION), zoom=zoom * zoom_, axes=ax) else: vv.view(dict(azimuth=90 + azimuth, elevation=elevation), zoom=zoom * zoom_, _axes=ax) ax.light0.ambient = light_ambient ax.light0.specular = .5 fig.DrawNow() if app is not None: app.ProcessEvents() img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None) if close_figure: vv.close(fig) fig = None return fig, img
def plot_mouse_head(show_now=False, size=(500, 500), ax=None, theta=0, phi=0, pitch=None, roll=None, isometric=True, azimuth=None, elevation=None, zoom=1.5, gravity_axes=True, head_axes=True, close_figure=False, color_mouse=(.5, .5, .5), color_head_axes=(.25, .95, .8), color_gravity_axes=(.75, .75, .75), backend='visvis', light_ambient=.6, light_specular=.5, arrow_kw=dict(length_cone=.1, radius_cone=.05, radius_shaft=.025)): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION t = np.arange(0, 1 * np.pi - 2 * np.pi / 10, np.pi / 10) r = 2 + np.cos(t) n = 20 if backend in ['mayavi', 'mlab']: from mayavi import mlab from tvtk.tools import visual fig = mlab.figure(bgcolor=(1, 1, 1), size=size) fig.scene.parallel_projection = True # head c = -3 [X, Y, Z] = cylinder(r, n=n) head = mlab.mesh(X, Y, c + Z * 6, color=(.5, .5, .5)) # nose [x, y, z] = sphere(20) nose = mlab.mesh(x * 1.5, y * 1.5, c + z * 1.5 + 6, color=(.5, .5, .5)) # EARS color = (.5, .5, .5) hsE1 = mlab.mesh((x * 1.0) - 2.427, (y * 1.8) - 1.763, c + (z * 0.4) + 0, color=color) hsE2 = mlab.mesh((x * 1.0) + 2.427, (y * 1.8) - 1.763, c + (z * 0.4) + 0, color=color) # EYES [x, y, z] = sphere(10) color = (.9, .9, .9) hsEYE1 = mlab.mesh((x * .8) - 1.2, (y * .8) - 1.6, c + (z * .8) + 3.5, color=color) hsEYE2 = mlab.mesh((x * .8) + 1.2, (y * .8) - 1.6, c + (z * .8) + 3.5, color=color) # pupils hsPUP1 = mlab.mesh((x * .3) - 1.476, (y * .3) - 1.98, c + (z * .3) + 4.147, color=(0.1, 0.1, 0.1)) hsPUP2 = mlab.mesh((x * .3) + 1.476, (y * .3) - 1.98, c + (z * .3) + 4.147, color=(0.1, 0.1, 0.1)) # whiskers Px = np.array([-1.154, -1.214, -1.154, +1.154, +1.214, +1.154]) Py = np.array([-0.375, 0, 0.375, -0.375, 0, 0.375]) Pz = np.ones(np.size(Px)) * 3.882 WL = np.array([[0.5, 2], [0.05, 0.4]]) # whisker length hsWHISK = [] for W in range(0, len(Px)): # W=0 if Px[W] < 0: XSIGN = -1 else: XSIGN = +1 if Py[W] < 0: YSIGN = -1 elif Py[W] == 0: YSIGN = 0 else: YSIGN = +1 x = np.append(Px[W], Px[W] + XSIGN * WL[0, :]) y = np.append(Py[W], Py[W] + YSIGN * WL[1, :]) z = np.append(Pz[W], Pz[W]) tck, u = interpolate.splprep([x, y], k=2) xi, yi = interpolate.splev(np.linspace(0, 1, 100), tck, der=0) zi = np.ones(np.size(yi)) * Pz[W] hsWHISK.append( mlab.plot3d(xi, yi, zi, color=(0, 0, 0), line_width=2)) # rotate all objects angle_x = -90 angle_y = 0 angle_z = -90 for actor in [head, nose, hsE1, hsE2, hsEYE1, hsEYE2, hsPUP1, hsPUP2]: actor.actor.actor.rotate_z(angle_z) actor.actor.actor.rotate_x(angle_x) actor.actor.actor.rotate_y(angle_y) # actor.actor.actor.rotate_y(phi) # actor.actor.actor.rotate_z(theta) actor.actor.actor.rotate_x(theta) actor.actor.actor.rotate_y(phi) for i in range(0, len(hsWHISK)): hsWHISK[i].actor.actor.rotate_z(angle_z) hsWHISK[i].actor.actor.rotate_x(angle_x) hsWHISK[i].actor.actor.rotate_y(angle_y) hsWHISK[i].actor.actor.rotate_x(theta) hsWHISK[i].actor.actor.rotate_y(phi) if head_axes: # axes of head-centered coordinate system visual.set_viewer(fig) arr1 = Arrow3D(0, 0, 0, 0, -6, 0, color=color_head_axes, **arrow_kw) for arr in [arr1]: # , arr2, arr3]: arr.actor.rotate_z(angle_z) arr.actor.rotate_x(angle_x) arr.actor.rotate_y(angle_y) arr.actor.rotate_x(theta) arr.actor.rotate_y(phi) if gravity_axes: # gravitational coordinate system visual.set_viewer(fig) arr1 = Arrow3D(0, 0, 0, -6, 0, 0, color=(.8, .8, .8), **arrow_kw) arr2 = Arrow3D(0, 0, 0, 0, -6, 0, color=(.5, .5, .5), **arrow_kw) arr3 = Arrow3D(0, 0, 0, 0, 0, 6, color=(.25, .25, .25), **arrow_kw) for arr in [arr1, arr2, arr3]: arr.actor.rotate_z(angle_z) arr.actor.rotate_x(angle_x) arr.actor.rotate_y(angle_y) if isometric: fig.scene.isometric_view() else: mlab.view(azimuth=azimuth, elevation=elevation, figure=fig) fig.scene.camera.zoom(zoom) if show_now: mlab.show() img = mlab.screenshot(figure=fig, mode='rgb', antialiased=False) elif backend in ['visvis']: import visvis as vv if ax is None: app = vv.use() fig = vv.figure() ax = vv.subplot(111) else: app = None fig = ax.GetFigure() ax.bgcolor = (1, 1, 1) ax.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' # head c = -3 [X, Y, Z] = cylinder(r, n=n) head = vv.surf(c + 6 * Z, X, Y) head.faceColor = color_mouse # nose [x, y, z] = sphere(20) nose = vv.surf(c + z * 1.5 + 6, x * 1.5, y * 1.5) nose.faceColor = color_mouse # ears color = (.5, .5, .5) ear1 = vv.surf(c + (z * 0.4) + 0, (x * 1.0) - 2.427, -1 * ((y * 1.8) - 1.763)) ear1.faceColor = color ear2 = vv.surf(c + (z * 0.4) + 0, (x * 1.0) + 2.427, -1 * ((y * 1.8) - 1.763)) ear2.faceColor = color_mouse # eyes [x, y, z] = sphere(10) color = (.9, .9, .9) eye1 = vv.surf(c + (z * .8) + 3.5, (x * .8) - 1.2, -1 * ((y * .8) - 1.6)) eye2 = vv.surf(c + (z * .8) + 3.5, (x * .8) + 1.2, -1 * ((y * .8) - 1.6)) [setattr(eye, 'faceColor', color) for eye in [eye1, eye2]] # pupils color = (.1, .1, .1) pupil1 = vv.surf(c + (z * .3) + 4.147 - .5, (x * .3) - 1.476 - .2, -1 * ((y * .3) - 1.98)) pupil2 = vv.surf(c + (z * .3) + 4.147 - .5, (x * .3) + 1.476 + .2, -1 * ((y * .3) - 1.98)) [setattr(pupil, 'faceColor', color) for pupil in [pupil1, pupil2]] # whiskers Px = np.array([-1.154, -1.214, -1.154, +1.154, +1.214, +1.154]) Py = np.array([-0.375, 0, 0.375, -0.375, 0, 0.375]) Pz = np.ones(np.size(Px)) * 3.882 WL = np.array([[0.5, 2], [0.05, 0.4]]) # whisker length whiskers = [] for W in range(0, len(Px)): # W=0 if Px[W] < 0: XSIGN = -1 else: XSIGN = +1 if Py[W] < 0: YSIGN = -1 elif Py[W] == 0: YSIGN = 0 else: YSIGN = +1 x = np.append(Px[W], Px[W] + XSIGN * WL[0, :]) y = np.append(Py[W], Py[W] + YSIGN * WL[1, :]) z = np.append(Pz[W], Pz[W]) tck, u = interpolate.splprep([x, y], k=2) xi, yi = interpolate.splev(np.linspace(0, 1, 100), tck, der=0) zi = np.ones(np.size(yi)) * Pz[W] whisker = vv.plot(zi, xi, -1 * yi, lw=2, lc=(0, 0, 0)) whiskers.append(whisker) if head_axes: # show vector indicating orientation of head length = 1 shrink = .825 if pitch is not None and roll is not None: # convert pitch/roll to spherical coordinates by rotating # a reference point around cartesian axes; note that x and # y are swapped in visvis p0 = np.array([0, 0, 1]) a = np.deg2rad(roll) Rx = np.array([[1, 0, 0], [0, np.cos(a), -np.sin(a)], [0, np.sin(a), np.cos(a)]]) b = np.deg2rad(pitch) Ry = np.array([[np.cos(b), 0, np.sin(b)], [0, 1, 0], [-np.sin(b), 0, np.cos(b)]]) direction = np.dot(Ry, np.dot(Rx, p0)) * length else: direction = sph2cart(length, theta, phi, degrees=True).ravel() cyl = vv.solidCylinder(translation=(0, 0, .25), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = (.25, .95, .8) cyl.do_not_rotate = True cyl.do_not_scale = True translation = direction * shrink + np.array([0, 0, .25]) cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = (.25, .95, .8) cone.do_not_rotate = True cone.do_not_scale = True if gravity_axes: # show vector indicating (negative) orientation of gravity length = 1 shrink = .825 color = (.75, .75, .75) direction = np.array([0, 0, 1]) cyl = vv.solidCylinder(translation=(0, 0, .25), scaling=(.05, .05, shrink * length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = color cyl.do_not_rotate = True cyl.do_not_scale = True translation = direction * shrink + np.array([0, 0, .25]) cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = color cone.do_not_rotate = True cone.do_not_scale = True # compute pitch and/or roll if not given if pitch is None or roll is None: # we have to find rotations (=angles) between the unit vector # in spherical coordinates (1, theta, phi) and the planes # for pitch (y/z) and roll (x/z); note that xyz is already # normaizeed (norm = 1) xyz = sph2cart(1, theta, phi, degrees=True).ravel() if pitch is None: # pitch (y/z plane with normal vector (1, 0, 0)) pitch = 90 - np.degrees(np.arccos(np.dot(xyz, [1, 0, 0]))) if roll is None: # roll (x/z plane with normal vector (0, -1, 0)) roll = 90 - np.degrees(np.arccos(np.dot(xyz, [0, -1, 0]))) for obj in ax.wobjects: if not hasattr(obj, 'do_not_scale'): rot = vv.Transform_Scale(sx=.25, sy=.25, sz=.25) obj.transformations.append(rot) if obj.__class__ != vv.core.axises.CartesianAxis and\ not hasattr(obj, 'do_not_rotate'): # note that x and y are swapped rot = vv.Transform_Rotate(pitch, ax=0, ay=1, az=0) obj.transformations.append(rot) rot = vv.Transform_Rotate(roll, ax=1, ay=0, az=0) obj.transformations.append(rot) zoom = vv.view()['zoom'] if isometric: vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION), zoom=4 * zoom, axes=ax) else: vv.view(dict(azimuth=90 + azimuth, elevation=elevation), zoom=4 * zoom, axes=ax) ax.light0.ambient = light_ambient ax.light0.specular = light_specular fig.DrawNow() if app is not None: app.ProcessEvents() img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None) if close_figure: vv.close(fig) fig = None return fig, img
def plot_density_sphere(xyz_centers, H, ax=None, method='hist', azimuth=None, elevation=None, backend='visvis', oversample=1, smoothing=None, zoom=1.7, cmap='jet', scaling='log', log_offset=-.1, clim=None, isometric=False, light_ambient=.6, light_specular=.5, avg_direction=None, pitch_label=True, roll_label=True, pitch_arrow=True, roll_arrow=True, arrow_color=(.25, .95, .8), close_figure=False): if azimuth is None: azimuth = DEFAULT_AZIMUTH if elevation is None: elevation = DEFAULT_ELEVATION scaling = scaling.lower() if scaling.startswith('log'): H = H / float(H.sum()) v = H > 0 if scaling == 'log': H[v] = np.log(H[v]) elif scaling == 'log2': H[v] = np.log2(H[v]) H[~v] = H[v].min() + log_offset if smoothing is not None and smoothing > 1: x = np.linspace(-3., 3., smoothing) xx, yy = np.meshgrid(x, x) G = np.exp((-xx**2 - yy**2)) H = signal.convolve2d(H, G / G.sum(), mode='same', boundary='wrap') if backend in ['mpl', 'matplotlib']: if ax is None: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') from matplotlib.colors import LightSource ls = LightSource(azdeg=315, altdeg=45) cm = getattr(plt.cm, cmap) colors = ls.shade(H, cmap=cm, blend_mode='soft', vert_exag=1) ax.plot_surface(xyz_centers[:, 0].reshape(H), xyz_centers[:, 1].reshape(H), xyz_centers[:, 2].reshape(H), cstride=1, rstride=1, facecolors=colors, linewidth=0, antialiased=False, shade=False) # add arrows in front of sphere import mousecam_helpers as helpers arrow_props = dict(arrowstyle='simple', mutation_scale=15, mutation_aspect=None, linewidth=.5, facecolor=3 * [.75], edgecolor=3 * [.1]) length = .6 arr = helpers.Arrow3D((1, 1 + length), (0, 0), (0, 0), **arrow_props) ax.add_artist(arr) arr = helpers.Arrow3D((0, 0), (1, 1 + length), (0, 0), **arrow_props) ax.add_artist(arr) arr = helpers.Arrow3D((0, 0), (0, 0), (1, 1 + length), **arrow_props) ax.add_artist(arr) extents = 3 * [[-.6, .6]] ax.auto_scale_xyz(*extents) ax.set_aspect('equal') ax.axis('off') ax.view_init(elev=elevation, azim=360 - azimuth) elif backend in ['mayavi', 'mlab']: from mayavi import mlab fig = mlab.figure(bgcolor=(1, 1, 1), size=(1000, 1000)) fig.scene.parallel_projection = True mlab.mesh(xyz_centers[:, 0].reshape(H.shape), xyz_centers[:, 1].reshape(H.shape), xyz_centers[:, 2].reshape(H.shape), scalars=H, colormap='jet') from tvtk.tools import visual visual.set_viewer(fig) arrow_kw = dict(color=(.75, .75, .75), length_cone=.1, radius_cone=.05, radius_shaft=.025) Arrow3D(0, 0, 0, 1.4, 0, 0, **arrow_kw) Arrow3D(0, 0, 0, 0, 1.4, 0, **arrow_kw) Arrow3D(0, 0, 0, 0, 0, 1.4, **arrow_kw) if isometric: fig.scene.isometric_view() else: mlab.view(azimuth=-azimuth, elevation=elevation, figure=fig) fig.scene.camera.zoom(zoom) ax = mlab.screenshot(figure=fig, mode='rgb', antialiased=False) elif backend in ['visvis']: import visvis as vv app = vv.use() fig = vv.figure() ax = vv.subplot(111) ax.axis.visible = 0 ax.axis.xLabel = 'x' ax.axis.yLabel = 'y' ax.axis.zLabel = 'z' length = 1.4 for i in range(3): direction = np.zeros((3, )) direction[i] = 1 cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, length), direction=tuple(direction), axesAdjust=False, axes=ax) cyl.faceColor = (.75, .75, .75) translation = np.zeros((3, )) translation[i] = length cone = vv.solidCone(translation=tuple(translation), scaling=(.1, .1, .2), direction=tuple(direction), axesAdjust=False, axes=ax) cone.faceColor = (.75, .75, .75) surf = vv.surf(xyz_centers[:, 0].reshape(H.shape), xyz_centers[:, 1].reshape(H.shape), xyz_centers[:, 2].reshape(H.shape), H, axes=ax) # set colormap cmap = cmap.lower() if cmap.endswith('_r'): cm = vv.colormaps[cmap[:-2]] cm = cm[::-1] else: cm = vv.colormaps[cmap] surf.colormap = cm if clim is not None: # apply colormap limits surf.clim = clim # ax.Draw() # add labels to indicate pitch and/or roll axes aa = np.deg2rad(np.linspace(45, 315, 100) - 90) r = .25 + .05 d = 1.25 + .25 color = (.25, .25, .25) if pitch_arrow: # pitch rotation (in x/z plane, i.e. around y-axis) xx = r * np.cos(aa) zz = r * np.sin(aa) yy = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[0], yy[0], zz[0]) direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if pitch_label: vv.Text(ax, 'Pitch', x=0, y=.9 * d, z=.5, fontSize=28, color=color) if roll_arrow: # roll rotation (in y/z plane, i.e. around x-axis) yy = r * np.cos(aa[::-1]) zz = r * np.sin(aa[::-1]) xx = d * np.ones_like(xx) vv.plot(xx, yy, zz, lw=5, lc=color, ls="-", axesAdjust=False, axes=ax) translation = (xx[0], yy[0], zz[0]) direction = (xx[0] - xx[1], yy[0] - yy[1], zz[0] - zz[1]) cone = vv.solidCone(translation=translation, scaling=(.05, .05, .1), direction=direction, axesAdjust=False, axes=ax) cone.faceColor = color if roll_label: vv.Text(ax, 'Roll', x=1.25 * d, y=-.8, z=0, fontSize=28, color=color) if avg_direction is not None: # indicate direction of avg head orientation avg_direction = avg_direction / np.sqrt(np.sum(avg_direction**2)) avg_direction *= length cyl = vv.solidCylinder(translation=(0, 0, 0), scaling=(.05, .05, length), direction=tuple(avg_direction), axesAdjust=False, axes=ax) cyl.faceColor = arrow_color cone = vv.solidCone(translation=tuple(avg_direction), scaling=(.1, .1, .2), direction=tuple(avg_direction), axesAdjust=False, axes=ax) cone.faceColor = arrow_color zoom_ = vv.view()['zoom'] if isometric: vv.view(dict(azimuth=90 + ISO_AZIMUTH, elevation=ISO_ELEVATION), zoom=zoom_ * zoom, axes=ax) else: vv.view(dict(azimuth=90 + azimuth, elevation=elevation), zoom=zoom * zoom_, axes=ax) ax.light0.ambient = light_ambient ax.light0.specular = light_specular fig.DrawNow() app.ProcessEvents() img = vv.screenshot(None, ob=ax, sf=2, bg=None, format=None) ax = img if close_figure: vv.close(fig) fig = None return fig, ax
m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # If necessary, use flat shading if N < 8 or M < 8: m.faceShading = 'flat' # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': import visvis as vv vv.figure() # Create rings m1 = solidRing((0, 0, 1), M=4) m2 = solidRing((0, 0, 2)) im = vv.imread('lena.png') m1.SetTexture(im)
# Get image im1 = vv.imread('astronaut.png')[:, :, 1].astype('float32') im1 = pirt.diffuse(im1, 1)[::2, ::2] / 255.0 # Deform image scale = im1.shape[0] * 0.4 rd = pirt.create_random_deformation(im1, 40, 40, mapping='backward', seed=1001) im2 = rd.apply_deformation(im1) # Add noise im1 += np.random.normal(0, 0.1, im1.shape) im2 += np.random.normal(0, 0.1, im1.shape) # Get figure vv.closeAll() fig = vv.figure(1) vv.clf() fig.position = 200, 100, 900, 500 # Init registration reg = pirt.GravityRegistration(im1, im2) # reg = pirt.DiffeomorphicDemonsRegistration(im1, im2) # reg = pirt.ElastixRegistration(im1, im2) if isinstance(reg, pirt.DiffeomorphicDemonsRegistration): reg.params.speed_factor = 2 reg.params.noise_factor = 0.1 reg.params.mapping = 'backward' reg.params.scale_sampling = 16 reg.params.final_grid_sampling = 35 if isinstance(reg, pirt.GravityRegistration):
# Perform the first (seeding) step out of 3 steps of stentDirect sd.Step1() vol = vol2 ## Visualization and interactive segmentation steps #todo: depending on the speedFactor fronts do not propagate from manually added seeds. # see costfunction, from speedfactor > 750 it works guiRemove = False # True for option to remove nodes/edges but takes longer clim = (0,3000) showVol = 'MIP' meshColor = None # or give FaceColor viewLR = {'azimuth': 90, 'roll': 0} fig = vv.figure(3); vv.clf() fig.position = 0.00, 22.00, 1920.00, 1018.00 # Show model Step 1 a1 = vv.subplot(131) label = DrawModelAxes(vol, sd._nodes1, a1, clim=clim, showVol=showVol, climEditor=True, removeStent=False) # lc, mc # Create axis for Step 2 a2 = vv.subplot(132) DrawModelAxes(vol, ax=a2, clim=clim, showVol=showVol, climEditor=False) # Create axis for Step 3 a3 = vv.subplot(133) DrawModelAxes(vol, ax=a3, clim=clim, showVol=showVol, climEditor=False) # _utils_GUI.vis_spared_edges(sd._nodes3)
# Perform the three steps of stentDirect sd.Step1() sd.Step2() # sd._nodes2 = stentgraph.StentGraph() # sd._nodes2.Unpack(ssdf.load('/home/almar/tmp.ssdf')) sd.Step3() # Create a mesh object for visualization (argument is strut tickness) if hasattr(sd._nodes3, 'CreateMesh'): bm = sd._nodes3.CreateMesh(0.6) # old else: bm = create_mesh(sd._nodes3, 0.6) # new # Create figue vv.figure(2); vv.clf() # Show volume and segmented stent as a graph a1 = vv.subplot(131) t = vv.volshow(vol) t.clim = 0, 3000 #sd._nodes1.Draw(mc='g', mw = 6) # draw seeded nodes #sd._nodes2.Draw(mc='g') # draw seeded and MCP connected nodes # Show cleaned up a2 = vv.subplot(132) sd._nodes3.Draw(mc='g', lc='b') # Show the mesh a3 = vv.subplot(133) a3.daspect = 1,-1,1
def __init__(self, dirsave, ptcode, ctcode, cropname, s, what='phases', axes=None, **kwargs): """ s is struct from loadvol """ self.fig = vv.figure(1) vv.clf() self.fig.position = 0.00, 29.00, 1680.00, 973.00 self.defaultzoom = 0.025 # check current zoom with foo.ax.GetView() self.what = what self.ptcode = ptcode self.dirsave = dirsave self.ctcode = ctcode self.cropname = cropname if self.what == 'phases': self.phase = 0 else: self.phase = self.what # avgreg # self.vol = s.vol0 self.s = s # s with vol(s) self.s_landmarks = vv.ssdf.new() self.graph = stentgraph.StentGraph() self.points = [] # selected points self.nodepoints = [] self.pointindex = 0 # for selected points try: self.vol = s.vol0 # when phases except AttributeError: self.vol = s.vol # when avgreg self.ax = vv.subplot(121) self.axref = vv.subplot(122) self.label = DrawModelAxes(self.vol, ax=self.ax) # label of clicked point self.axref.bgcolor = 0, 0, 0 self.axref.visible = False # create axis for buttons a_select = vv.Wibject(self.ax) # on self.ax or fig? a_select.position = 0.55, 0.7, 0.6, 0.5 # x, y, w, h # Create text objects self._labelcurrentIndexT = vv.Label(a_select) # for text title self._labelcurrentIndexT.position = 125, 180 self._labelcurrentIndexT.text = ' Total selected =' self._labelcurrentIndex = vv.Label(a_select) self._labelcurrentIndex.position = 225, 180 # Create Select button self._select = False self._butselect = vv.PushButton(a_select) self._butselect.position = 10, 150 self._butselect.text = 'Select' # Create Back button self._back = False self._butback = vv.PushButton(a_select) self._butback.position = 125, 150 self._butback.text = 'Undo' # Create Next/Save button self._finished = False self._butclose = vv.PushButton(a_select) self._butclose.position = 10, 230 self._butclose.text = 'Next/Save' # # Create Save landmarks button # self._save = False # self._butsave = vv.PushButton(a_select) # self._butsave.position = 125,230 # self._butsave.text = 'Save|Finished' # Create Reset-View button self._resetview = False self._butresetview = vv.PushButton(a_select) self._butresetview.position = 10, 180 self._butresetview.text = 'Default Zoom' # back to default zoom # bind event handlers self.fig.eventClose.Bind(self._onFinish) self._butclose.eventPress.Bind(self._onFinish) self._butselect.eventPress.Bind(self._onSelect) self._butback.eventPress.Bind(self._onBack) self._butresetview.eventPress.Bind(self._onView) # self._butsave.eventPress.Bind(self._onSave) self._updateTextIndex() self._updateTitle()
deforms = [[field[::2, ::2, ::2] for field in fields] for fields in deforms] deforms_f = [pirt.DeformationFieldForward(*f) for f in deforms] # Load mesh basedir2 = select_dir(r'C:\MedData\LSPEAS_Mimics', r'F:\LSPEAS_Mimics_backup', r'E:\LSPEAS_Mimics_backup') mesh = vv.meshRead(os.path.join(basedir2, ptcode + '_' + ctcode, meshfile)) # z is negative, must be flipped to match dicom orientation for vertice in mesh._vertices: vertice[-1] = vertice[-1] * -1 #mesh = vv.meshRead(r'D:\Profiles\koenradesma\Desktop\001_preavgreg 20150522 test itk.stl') # x and y values of vertices are negative (as in original dicom), flip to match local coordinates #mesh._vertices = mesh._vertices*-1 # when stl from itksnap ## Start vis f = vv.figure(1) vv.clf() f.position = 8.00, 31.00, 944.00, 1001.00 a = vv.gca() a.axis.axisColor = 1, 1, 1 a.axis.visible = False a.bgcolor = 0, 0, 0 a.daspect = 1, 1, -1 vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], ctcode)) vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') t = vv.volshow2(volavg, clim=(-550, 500)) # -750, 1000 # m = vv.mesh(mesh)
def plot_3d_diameter_map(name, data, unit_scale=1.0, measure_quantity='vox', radius_structure_elem=1, output_dir=None, width=512, height=512, camera_azth=44.5, camera_elev=35.8, camera_roll=0.0, camera_fov=35.0, camera_zoom=0.0035, camera_loc=(67.0, 81.6, 45.2), xlabel='', ylabel='', zlabel='', axis_color='w', background_color='k', cb_x_offset=10): """Renders orientation data in 3D with RGB angular color-coding. Parameters ---------- name : str Indicates the name of the output png file. data : 3D array Indicates the 3D array containing diameter at every point of the skeleton. unit_scale : float Indicates the scale factor of the data values. measure_quantity : str Indicates the name of measure of the values. radius_structure_elem : integer Indicates the size of the structure element of the dilation process to thicken the skeleton. output_dir : str Indicates the path to the output folder where the image will be stored. camera_azth : float Indicates the azimuth angle of the camera. width : int Indicates the width of the visualization window. height : int Indicates the width of the visualization window. camera_elev : float Indicates the latitude / elevation angle of the camera. camera_roll : float Indicates the roll angle of the camera. camera_fov : float Indicates the field of view of the camera. camera_zoom : float Indicates the zoom level of the camera. camera_loc : tuple Indicates the camera location. xlabel : str Indicates the label along the x-axis. ylabel : str Indicates the label along the y-axis. zlabel : str Indicates the label along the z-axis. axis_color : str Indicates the color of axes. background_color : str Indicates the background color of the figure. cb_x_offset : int Indicates the offset of the colorbar from the right window side. """ if not visvis_available: print( 'The visvis package is not found. The visualization cannot be done.' ) return rmin, rmax, cmin, cmax, zmin, zmax = _bbox_3D(data) dmtr = data[rmin:rmax, cmin:cmax, zmin:zmax] * unit_scale skel = np.zeros_like(dmtr, dtype=np.uint8) skel[dmtr.nonzero()] = 1 dmtr = ndi.grey_dilation(dmtr, structure=morphology.ball(radius_structure_elem)) skel = ndi.binary_dilation( skel, structure=morphology.ball(radius_structure_elem)).astype(np.float32) skel[skel.nonzero()] = 1. dmtr = dmtr * skel app = vv.use() fig = vv.figure() fig._currentAxes = None fig.relativeFontSize = 2. fig.position.w = width fig.position.h = height t = vv.volshow(dmtr[:, :, :], renderStyle='iso') t.isoThreshold = 0.5 t.colormap = vv.CM_JET a = vv.gca() a.camera.azimuth = camera_azth a.camera.elevation = camera_elev a.camera.roll = camera_roll a.camera.fov = camera_fov a.camera.zoom = camera_zoom a.camera.loc = camera_loc a.bgcolor = background_color a.axis.axisColor = axis_color a.axis.xLabel = xlabel a.axis.yLabel = ylabel a.axis.zLabel = zlabel cb = vv.colorbar() cb.SetLabel(f'Diameter, [{measure_quantity}]') cb._label.position.x += cb_x_offset if output_dir is not None: if not os.path.exists(output_dir): os.makedirs(output_dir) vv.screenshot(os.path.join(output_dir, f'{name}_3d_diameter.png'), sf=1, bg='w') app.Run()
pp1.append(400,200) pp2.append(400,200) # pp1.append(100,300) pp2.append(100,300) pp1.append(100,400) pp2.append(200,300) pp1.append(200,400) pp2.append(200,400) # pp1.append(300,400) pp2.append(300,400) pp1.append(400,400) pp2.append(300,300) pp1.append(400,300) pp2.append(400,300) # Deform def deform_and_show(injective): from_points_multiscale = pirt.DeformationFieldForward.from_points_multiscale deform = from_points_multiscale(im, 10, pp1, pp2, injective=injective, frozenedge=True) deform.show() # Show vv.figure(1); vv.clf() vv.subplot(131); deform_and_show(0); vv.title('Not injective') vv.subplot(132); deform_and_show(-0.9); vv.title('Truncated injective') vv.subplot(133); deform_and_show(+0.9); vv.title('Smooth injective')
# use floats to prevent strides etc. uint8 caused crash on qt backend. im = gl.glReadPixels(x, y, w, h, gl.GL_RGB, gl.GL_FLOAT) # reshape, flip, and store im.shape = h,w,3 im = np.flipud(im) # done return im if __name__ == '__main__': import time f = vv.figure() a1 = vv.subplot(211) a2 = vv.subplot(212) vv.plot([2,3,4,2,4,3], axes=a1) for i in range(4): # draw and wait a bit f.DrawNow() time.sleep(1) # make snapshots im1 = getframe(f) im2 = getframe(a1) # clear and show snapshots a1.Clear() a2.Clear()
# Load static CT image to add as reference s = loadvol(basedir, ptcode, ctcode, cropname, 'avgreg') vol = s.vol # Load the stent model and mesh s2 = loadmodel(basedir, ptcode, ctcode, cropname, modelname) model = s2.model ## Start visualization and GUI clim = (0,2500) showVol = 'MIP' fig = vv.figure(); vv.clf() fig.position = 9.00, 30.00, 944.00, 1002.00 a = vv.gca() label = DrawModelAxes(vol, model, a, getLabel=True, clim=clim, showVol=showVol, mw=10) vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], ctcode)) viewAP = {'zoom': 0.006,'fov': 0.0, 'daspect': (1.0, 1.0, -1.0), 'azimuth': 0.0, 'roll': 0.0} # Set view # a.SetView(viewAP) # Initialize labels t0 = vv.Label(a, '\b{Node nr|location}: ', fontSize=11, color='w') t0.position = 0.1, 25, 0.5, 20 # x (frac w), y, w (frac), h
mass = np.add(*massParts)**0.5 # Normalize mass = normalize(mass) # Truncate if truncate: mass[mass < 0] = 0.0 soft_limit(mass, 1) # todo: half limit #mass = mass**0.5 return mass # Show vv.figure(10) vv.clf() for i in range(3): a = vv.subplot(3, 3, i + 1) vv.imshow(ims[i]) a.axis.visible = False for i in range(3): a = vv.subplot(3, 3, i + 4) vv.imshow(getMass(ims[i])) a.axis.visible = False for i in range(3): a = vv.subplot(3, 3, i + 7) vv.hist(getMass(ims[i], False), 64) a.SetLimits()
D = {} for i in SIZE_TICKS: il = math.log(i,factor) for j,c in reversed(zip([1, 10,20,30],['','K', 'M', 'G'])): jj = float(factor)**j if i>=jj: i = '%1.0f %s%s' % (i/jj, c, unit) D[il] = i break return D SIZE_log = [math.log(i,2) for i in SIZE] BPS_log = [math.log(i,2) for i in BPS] TPM_log = [math.log(i,10) for i in TPM] fig = vv.figure(1); vv.clf() # a1 = vv.subplot(211) vv.plot(SIZE_log, BPS_log, ms='.') vv.ylabel('speed [bytes/s]') a1.axis.yTicks = logticks2() # a2 = vv.subplot(212) vv.plot(SIZE_log, TPM_log, ms='.') # 0.001 0.4 vv.ylabel('time per message [s]') a2.axis.yTicks = logticks10('s') for a in [a1, a2]: a.axis.xLabel = 'message size' a.axis.showGrid = True
cc = pirt.get_cubic_spline_coefs(tt[i], type) vv0[i] = cc[0] vv1[i] = cc[1] vv2[i] = cc[2] vv3[i] = cc[3] vvt[i] = sum(cc) # Interpolate (0 means Cardinal with tension 0) samples = np.arange(0,len(data)-1,0.05, dtype=np.float32) values1 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'linear') values2 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 'basis') values3 = pirt.warp(np.array(data, dtype=np.float32), samples, 3, 0) # Visualize fig = vv.figure(1); vv.clf() fig.position = 57.00, 45.00, 948.00, 969.00 vv.subplot(211) vv.title('The basis functions for the %s spline' % type) vv.plot(tt, vv0, lc='r') vv.plot(tt, vv1, lc='g') vv.plot(tt, vv2, lc='b') vv.plot(tt, vv3, lc='m') vv.plot(tt, vvt, lc='k', ls='--') vv.subplot(212) vv.plot(range(len(data)), data, ms='.', ls='') vv.plot(samples, values1, lc='r') vv.plot(samples, values2, lc='g') vv.plot(samples, values3, lc='b', lw=3)
def __init__(self, im, grid_sampling=40): # Store image self._im = im # Setup visualization self._fig = fig = vv.figure() self._a1 = a1 = vv.subplot(231); self._a2 = a2 = vv.subplot(232); self._a3 = a3 = vv.subplot(233); self._a4 = a4 = vv.subplot(234); self._a5 = a5 = vv.subplot(235); self._a6 = a6 = vv.subplot(236); # Text objects self._text1 = vv.Label(fig) self._text1.position = 5, 2 self._text2 = vv.Label(fig) self._text2.position = 5, 20 # Move axes a1.parent.position = 0.0, 0.1, 0.33, 0.45 a2.parent.position = 0.33, 0.1, 0.33, 0.45 a3.parent.position = 0.66, 0.1, 0.33, 0.45 a4.parent.position = 0.0, 0.55, 0.33, 0.45 a5.parent.position = 0.33, 0.55, 0.33, 0.45 a6.parent.position = 0.66, 0.55, 0.33, 0.45 # Correct axes, share camera cam = vv.cameras.TwoDCamera() for a in [a1, a2, a3, a4, a5, a6]: a.axis.visible = False a.camera = cam # Show images im0 = im*0 self._t1 = vv.imshow(im, axes=a1) self._t2 = vv.imshow(im, axes=a2) self._t3 = vv.imshow(im, axes=a3) self._t4 = vv.imshow(im0, axes=a4) self._t5 = vv.imshow(im0, axes=a5) self._t6 = vv.imshow(im0, axes=a6) # Init pointsets self._pp1 = Pointset(2) self._pp2 = Pointset(2) self._active = None self._lines = [] # Init lines to show all deformations tmp = vv.Pointset(2) self._line1 = vv.plot(tmp, ls='', ms='.', mc='c', axes=a2) self._line2 = vv.plot(tmp, ls='+', lc='c', lw='2', axes=a2) # Init grid properties self._sampling = grid_sampling self._levels = 5 self._multiscale = True self._injective = 0.5 self._frozenedge = 1 self._forward = True # Init grid self.DeformationField = DeformationFieldForward self._field1 = self.DeformationField(FieldDescription(self._im)) self._field2 = self.DeformationField(FieldDescription(self._im)) # Bind to events a2.eventMouseDown.Bind(self.on_down) a2.eventMouseUp.Bind(self.on_up) a2.eventMotion.Bind(self.on_motion) fig.eventKeyDown.Bind(self.on_key_down) #a1.eventDoubleClick.Bind(self.OnDone) # Apply self.apply()
R1_post_and_cl_point = point_in_pointcloud_closest_to_p(centerline1, R1_post) # calculate distance over centerline dist_for_R1_left = dist_over_centerline(centerline1, R1_left_and_cl_point[0], renal1_and_cl_point[0]) dist_for_R1_right = dist_over_centerline(centerline1, R1_right_and_cl_point[0], renal1_and_cl_point[0]) dist_for_R1_ant = dist_over_centerline(centerline1, R1_ant_and_cl_point[0], renal1_and_cl_point[0]) dist_for_R1_post = dist_over_centerline(centerline1, R1_post_and_cl_point[0], renal1_and_cl_point[0]) # Main outcome 1: distance 2nd ring valleys to renal # Main outcome 2: migration 2nd ring valleys from discharge to 1, 6, 12 months ## Visualize f = vv.figure(2) vv.clf() f.position = 0.00, 22.00, 1920.00, 1018.00 alpha = 0.5 if ctcode2: a1 = vv.subplot(121) else: a1 = vv.gca() show_ctvolume(vol1, model1, showVol=showVol, clim=clim0, isoTh=isoTh) pick3d(vv.gca(), vol1) model1.Draw(mc='b', mw=10, lc='g') vm = vv.mesh(modelmesh1) vm.faceColor = 'g' # m = vv.mesh(vessel1) # m.faceColor = (1,0,0, alpha) # red
g.setCurveMarker(curveID, 80) #MESHING: elType = 2 #Element type 2 is triangle. (3 is quad. See user manual for more element types) dofsPerNode= 2 #Degrees of freedom per node. mesher = GmshMeshGenerator(g) mesher.elSizeFactor = 0.05 mesher.elType = elType mesher.dofsPerNode = 2 #Mesh the geometry: # The first four return values are the same as those that trimesh2d() returns. # value elementmarkers is a list of markers, and is used for finding the marker of a given element (index). coords, edof, dofs, bdofs, elementmarkers = mesher.create() #VISUALISATION: #Hold left mouse button to pan. #Hold right mouse button to zoom. pcv.drawGeometry(g, labelCurves=True)#Draws the geometry. vv.figure() #New figure window pcv.drawMesh(coords=coords, edof=edof, dofsPerNode=dofsPerNode, elType=elType, filled=True, title="Example 02") #Draws the mesh. vv.gca().axis.showGrid = True #Show grid # Enter main loop: app = vv.use() app.Create() app.Run()
def plot3d(self, img, bodies={ 'pose3d': np.empty((0, 13, 3)), 'pose2d': np.empty((0, 13, 2)) }, hands={ 'pose3d': np.empty((0, 21, 3)), 'pose2d': np.empty((0, 21, 2)) }, faces={ 'pose3d': np.empty((0, 84, 3)), 'pose2d': np.empty((0, 84, 2)) }, body_with_wrists=[], body_with_head=[], interactive=False): """ :param img: a HxWx3 numpy array :param bodies: dictionnaroes with 'pose3d' (resp 'pose2d') with the body 3D (resp 2D) pose :param faces: same with face pose :param hands: same with hand pose :param body_with_wrists: list with for each body, a tuple (left_hand_id, right_hand_id) of the index of the hand detection attached to this body detection (-1 if none) for left and right hands :parma body_with_head: list with for each body, the index of the face detection attached to this body detection (-1 if none) :param interactive: whether to open the viewer in an interactive manner or not """ # body pose do not use the same coordinate systems bodies['pose3d'][:, :, 0] *= -1 bodies['pose3d'][:, :, 1] *= -1 # Compute 3D scaled representation of each part, stored in "points3d" hands, bodies, faces = [copy.copy(s) for s in (hands, bodies, faces)] parts = (hands, bodies, faces) for part in parts: part['points3d'] = np.zeros_like(part['pose3d']) for part_idx in range(len(part['pose3d'])): points3d = scale_orthographic(part['pose3d'][part_idx], part['pose2d'][part_idx]) part['points3d'][part_idx] = points3d # Various display tricks to make the 3D visualization of full-body nice # (1) for faces, add a Z offset to faces to align them with the body for body_id, face_id in enumerate(body_with_head): if face_id != -1: z_offset = bodies['points3d'][body_id, 12, 2] - np.mean( faces['points3d'][face_id, :, 2]) faces['points3d'][face_id, :, 2] += z_offset # (2) for hands, add a 3D offset to put them at the wrist location for body_id, (lwrist_id, rwrist_id) in enumerate(body_with_wrists): if lwrist_id != -1: hands['points3d'][lwrist_id, :, :] = bodies['points3d'][ body_id, 7, :] - hands['points3d'][lwrist_id, 0, :] if rwrist_id != -1: hands['points3d'][rwrist_id, :, :] = bodies['points3d'][ body_id, 6, :] - hands['points3d'][rwrist_id, 0, :] img = np.asarray(img) height, width = img.shape[:2] fig = vv.figure(1) fig.Clear() fig._SetPosition(0, 0, self.figsize[0], self.figsize[1]) if not interactive: fig._enableUserInteraction = False axes = vv.gca() # Hide axis axes.axis.visible = False scaling_factor = 1.0 / height # Camera interaction is not intuitive along z axis # We reference every object to a parent frame that is rotated to circumvent the issue ref_frame = vv.Wobject(axes) ref_frame.transformations.append(vv.Transform_Rotate(-90, 1, 0, 0)) ref_frame.transformations.append( vv.Transform_Translate(-0.5 * width * scaling_factor, -0.5, 0)) # Draw image if self.display2d: # Display pose in 2D img = visu.visualize_bodyhandface2d(img, dict_poses2d={ 'body': bodies['pose2d'], 'hand': hands['pose2d'], 'face': faces['pose2d'] }, lw=2, max_padding=0, bgr=False) XX, YY = np.meshgrid([0, width * scaling_factor], [0, 1]) img_z_offset = 0.5 ZZ = img_z_offset * np.ones(XX.shape) # Draw image embedded_img = vv.surf(XX, YY, ZZ, img) embedded_img.parent = ref_frame embedded_img.ambientAndDiffuse = 1.0 # Draw a grid on the bottom floor to get a sense of depth XX, ZZ = np.meshgrid( np.linspace(0, width * scaling_factor, 10), img_z_offset - np.linspace(0, width * scaling_factor, 10)) YY = np.ones_like(XX) grid3d = vv.surf(XX, YY, ZZ) grid3d.parent = ref_frame grid3d.edgeColor = (0.1, 0.1, 0.1, 1.0) grid3d.edgeShading = 'plain' grid3d.faceShading = None # Draw pose for part in parts: for part_idx in range(len(part['points3d'])): points3d = part['points3d'][part_idx] * scaling_factor # Draw bones J = len(points3d) is_body = (J == 13) ignore_neck = False if not is_body else body_with_head[ part_idx] != -1 bones, bonecolors, pltcolors = visu._get_bones_and_colors( J, ignore_neck=ignore_neck) for (kpt_id1, kpt_id2), color in zip(bones, bonecolors): color = color[2], color[1], color[0] # BGR vs RGB p1 = visu._get_xyz(points3d, kpt_id1) p2 = visu._get_xyz(points3d, kpt_id2) pointset = vv.Pointset(3) pointset.append(p1) pointset.append(p2) # Draw bones as solid capsules bone_radius = 0.005 line = vv.solidLine(pointset, radius=bone_radius) line.faceColor = color line.ambientAndDiffuse = 1.0 line.parent = ref_frame # Draw keypoints, except for faces if J != 84: keypoints_to_plot = points3d if ignore_neck: # for a nicer display, ignore head keypoint keypoints_to_plot = keypoints_to_plot[:12, :] # Use solid spheres for i in range(len(keypoints_to_plot)): kpt_wobject = vv.solidSphere( translation=keypoints_to_plot[i, :].tolist(), scaling=1.5 * bone_radius) kpt_wobject.faceColor = (255, 0, 0) kpt_wobject.ambientAndDiffuse = 1.0 kpt_wobject.parent = ref_frame # Use just an ambient lighting axes.light0.ambient = 0.8 axes.light0.diffuse = 0.2 axes.light0.specular = 0.0 cam = vv.cameras.ThreeDCamera() axes.camera = cam #z axis cam.azimuth = -45 cam.elevation = 20 cam.roll = 0 # Orthographic camera cam.fov = 0 if self.camera_zoom is None: cam.zoom *= 1.3 # Zoom a bit more else: cam.zoom = self.camera_zoom if self.camera_location is not None: cam.loc = self.camera_location cam.SetView() if interactive: self.app.Run() else: fig._widget.update() self.app.ProcessEvents() img3d = vv.getframe(vv.gcf()) img3d = np.clip(img3d * 255, 0, 255).astype(np.uint8) # Crop gray borders img3d = img3d[10:-10, 10:-10, :] return img3d, img
def refresh(self): vv.figure(self._fig.nr) # self._app = vv.use() self.paint(vv)
# Select dataset to register ptcode = 'LSPEAS_008' ctcode = '1month' cropname = 'stent' what = 'phases' # avgreg # Load volumes s = loadvol(basedir, ptcode, ctcode, cropname, what) vol = s.vol80 clim = (0, 2500) # clim = (-100,300) showVol = '2D' fig = vv.figure(2) vv.clf() fig.position = 0.00, 22.00, 1920.00, 1018.00 label = DrawModelAxes(vol, clim=clim, showVol=showVol) # lc, mc a = vv.gca() # bind rotate view [a,d rotate; z,x axes] fig.eventKeyDown.Bind(lambda event: _utils_GUI.RotateView(event, [a])) ## Pseudocode # get start points [voxels] # centerline stent # points on stent #
def __init__(self,ptcode,ctcode,basedir, seed_th=[600], show=True, normalize=False, modelname='model'): import os import numpy as np import visvis as vv from visvis import ssdf from stentseg.utils import PointSet, _utils_GUI from stentseg.utils.datahandling import select_dir, loadvol, loadmodel from stentseg.stentdirect.stentgraph import create_mesh from stentseg.stentdirect import stentgraph, StentDirect, getDefaultParams from stentseg.stentdirect import AnacondaDirect, EndurantDirect, NellixDirect from stentseg.utils.visualization import show_ctvolume from stentseg.utils.picker import pick3d, label2worldcoordinates, label2volindices import scipy from scipy import ndimage import copy # Select dataset to register cropname = 'prox' # phase = 10 #dataset = 'avgreg' #what = str(phase) + dataset # avgreg what = 'avgreg' # Load volumes s = loadvol(basedir, ptcode, ctcode, cropname, what) # sampling was not properly stored after registration for all cases: reset sampling vol_org = copy.deepcopy(s.vol) s.vol.sampling = [vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]] # z,y,x s.sampling = s.vol.sampling vol = s.vol ## Initialize segmentation parameters stentType = 'nellix' # 'zenith';'nellix' runs modified pruning algorithm in Step3 p = getDefaultParams(stentType) p.seed_threshold = seed_th # step 1 [lower th] or [lower th, higher th] # p.seedSampleRate = 7 # step 1, nellix p.whatphase = what ## Perform segmentation # Instantiate stentdirect segmenter object if stentType == 'anacondaRing': sd = AnacondaDirect(vol, p) # inherit _Step3_iter from AnacondaDirect class #runtime warning using anacondadirect due to mesh creation, ignore elif stentType == 'endurant': sd = EndurantDirect(vol, p) elif stentType == 'nellix': sd = NellixDirect(vol, p) else: sd = StentDirect(vol, p) ## show histogram and normalize # f = vv.figure(3) # a = vv.gca() # vv.hist(vol, drange=(300,vol.max())) # normalize vol to certain limit if normalize: sd.Step0(3071) vol = sd._vol # b= vv.hist(vol, drange=(300,3071)) # b.color = (1,0,0) ## Perform step 1 for seeds sd.Step1() ## Visualize if show: fig = vv.figure(2); vv.clf() fig.position = 0.00, 22.00, 1920.00, 1018.00 clim = (0,2000) # Show volume and model as graph a1 = vv.subplot(121) a1.daspect = 1,1,-1 # t = vv.volshow(vol, clim=clim) t = show_ctvolume(vol, axis=a1, showVol='MIP', clim =clim, isoTh=250, removeStent=False, climEditor=True) label = pick3d(vv.gca(), vol) sd._nodes1.Draw(mc='b', mw = 2) # draw seeded nodes #sd._nodes2.Draw(mc='b', lc = 'g') # draw seeded and MCP connected nodes vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') # Show volume and cleaned up graph a2 = vv.subplot(122) a2.daspect = 1,1,-1 sd._nodes1.Draw(mc='b', mw = 2) # draw seeded nodes # t = vv.volshow(vol, clim=clim) # label = pick3d(vv.gca(), vol) # sd._nodes2.Draw(mc='b', lc='g') # sd._nodes3.Draw(mc='b', lc='g') vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') # # Show the mesh #=============================================================================== # a3 = vv.subplot(133) # a3.daspect = 1,1,-1 # t = vv.volshow(vol, clim=clim) # pick3d(vv.gca(), vol) # #sd._nodes3.Draw(mc='b', lc='g') # m = vv.mesh(bm) # m.faceColor = 'g' # # _utils_GUI.vis_spared_edges(sd._nodes3) # vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') #=============================================================================== # Use same camera a1.camera = a2.camera #= a3.camera switch = True a1.axis.visible = switch a2.axis.visible = switch #a3.axis.visible = switch ## Store segmentation to disk # Get graph model model = sd._nodes1 # Build struct s2 = vv.ssdf.new() s2.sampling = s.sampling s2.origin = s.origin s2.stenttype = s.stenttype s2.croprange = s.croprange for key in dir(s): if key.startswith('meta'): suffix = key[4:] s2['meta'+suffix] = s['meta'+suffix] s2.what = what s2.params = p s2.stentType = stentType # Store model (not also volume) s2.model = model.pack() # Save filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, modelname+ what) ssdf.save(os.path.join(basedir, ptcode, filename), s2) print('saved to disk as {}.'.format(filename) ) ## Make model dynamic (and store/overwrite to disk) #=============================================================================== # # import pirt # from stentsegf.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges # # # Load deforms # s = loadvol(basedir, ptcode, ctcode, cropname, '10deforms') # deformkeys = [] # for key in dir(s): # if key.startswith('deform'): # deformkeys.append(key) # deforms = [s[key] for key in deformkeys] # deforms = [pirt.DeformationFieldBackward(*fields) for fields in deforms] # paramsreg = s.params # # # Load model # s = loadmodel(basedir, ptcode, ctcode, cropname, 'model'+what) # model = s.model # # # Combine ... # incorporate_motion_nodes(model, deforms, s.origin) # incorporate_motion_edges(model, deforms, s.origin) # # # Save back # filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'model'+what) # s.model = model.pack() # s.paramsreg = paramsreg # ssdf.save(os.path.join(basedir, ptcode, filename), s) # print('saved to disk as {}.'.format(filename) ) #===============================================================================
@vv.misc.PropWithDraw def whiskers(): """ Get/Set the style of the whiskers. """ def fget(self): return self._boxes[0]._whiskers def fset(self, value): for box in self._boxes: box.SetWhiskers(value) return locals() if __name__ == '__main__': vv.figure(1); vv.clf() a = vv.gca() d1 = np.random.normal(1, 4, (1000,1000)) d2 = np.random.normal(2, 3, (20,)) d3 = np.random.uniform(-1, 3, (100,)) d4 = [1,2,1,2.0, 8, 2, 3, 1, 2, 2, 3, 2, 2.1, 8, 8, 8, 8, 8, 1.2, 1.3, 0, 0, 1.5, 2] b = boxplot((d1,d2,d3, d4), width=0.8, whiskers='violin') ## dd = d4 stat = StatData(dd) bins1, values1 = stat.histogram_np(normed=True) bins2, values2 = stat.histogram() bins3, values3 = stat.kde( ) vv.figure(2); vv.clf() vv.bar(bins2, values2)#, lc='r', ms='.', mc='r')
# For fast step 3 testing: save output from step 2 and load afterwards for use #ssdf.save(r'C:\Users\Maaike\Dropbox\ut ma3\research aortic stent grafts\data_nonecg-gated\tmp_nodes2\tmp_nodes2_700_100_006.ssdf', sd._nodes2.pack()) #sd._nodes2 = stentgraph.StentGraph() #sd._nodes2.unpack(ssdf.load(r'C:\Users\Maaike\Dropbox\ut ma3\research aortic stent grafts\data_nonecg-gated\tmp_nodes2\tmp_nodes2_700_100_006.ssdf')) sd.Step3() # Create a mesh object for visualization (argument is strut tickness) if hasattr(sd._nodes3, 'CreateMesh'): bm = sd._nodes3.CreateMesh(0.6) # old else: bm = create_mesh(sd._nodes3, 0.6) # new ## Create figure fig = vv.figure(1) vv.clf() fig.position = 0, 22, 1366, 706 #fig.position = -1413.00, -2.00, 1366.00, 706.00 # Show volume and model as graph a1 = vv.subplot(131) t = vv.volshow(vol) t.clim = 0, 3000 #sd._nodes1.Draw(mc='g', mw = 6) # draw seeded nodes sd._nodes2.Draw(mc='b', lc='g') # draw seeded and MCP connected nodes # Show volume and cleaned up graph a2 = vv.subplot(132) t = vv.volshow(vol) t.clim = 0, 3000
# if translation is not None: m.translation = translation if scaling is not None: m.scaling = scaling if direction is not None: m.direction = direction if rotation is not None: m.rotation = rotation # Set flat shading? if N<8 or M<8: m.faceShading = 'flat' # Adjust axes if axesAdjust: if axes.daspectAuto is None: axes.daspectAuto = False axes.cameraType = '3d' axes.SetLimits() # Done axes.Draw() return m if __name__ == '__main__': vv.figure() m1 = solidCylinder(N=6) m2 = solidCylinder(translation=(0,0,0.1), scaling=(0.5,0.5,2.5))
model = s2.model modelmesh = create_mesh(model, 0.6) # Param is thickness showAxis = True # True or False showVol = 'MIP' # MIP or ISO or 2D or None ringpart = True # True; False nstruts = 8 clim0 = (0,3000) # clim0 = -550,500 clim2 = (0,4) radius = 0.07 dimensions = 'xyz' isoTh = 250 ## Visualize with GUI f = vv.figure(3); vv.clf() f.position = 968.00, 30.00, 944.00, 1002.00 a = vv.gca() show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) model.Draw(mc='b', mw = 10, lc='g') vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Analysis for model LSPEAS %s - %s' % (ptcode[7:], ctcode)) a.axis.axisColor= 1,1,1 a.bgcolor= 0,0,0 a.daspect= 1, 1, -1 # z-axis flipped a.axis.visible = showAxis # Initialize labels GUI from visvis import Pointset from stentseg.stentdirect import stentgraph
#!/usr/bin/env python """ This example demonstrates rendering a color volume. We demonstrate two renderers capable of rendering color data: the colormip and coloriso renderer. """ import visvis as vv app = vv.use() # Load volume vol = vv.volread("stent") # Create figure and make subplots with different renderers vv.figure(1) vv.clf() RS = ["mip", "iso", "edgeray", "ray", "litray"] a0 = None tt = [] for i in range(5): a = vv.subplot(3, 2, i + 2) t = vv.volshow(vol) vv.title("Renderstyle " + RS[i]) t.colormap = vv.CM_HOT t.renderStyle = RS[i] t.isoThreshold = 200 # Only used in iso render style tt.append(t) if a0 is None: a0 = a else: a.camera = a0.camera
def main(): reqlog = logging.getLogger('requests') reqlog.setLevel(logging.ERROR) log = logging.getLogger(__name__) server = subprocess.Popen([sys.executable, '../dora/server/server.py']) time.sleep(5) try: # Set up a sampling problem: target_samples = 100 n_train = 20 lower = [1., 1.] upper = [3., 3.] acq_name = 'prod_max' initialiseArgs = {'lower': lower, 'upper': upper, 'acq_name': acq_name, 'n_train': n_train} # Initialise the sampler sampler_info = requests.post('http://localhost:5000/samplers', json=initialiseArgs).json() log.info("Model Info: " + str(sampler_info)) # Set up plotting: plots = {'fig': vv.figure(), 'count': 0, 'shape': (2, 3)} plot_triggers = [22, 30, 40, 50, 65, target_samples-1] # Run the active sampling: for i in range(target_samples): log.info('Iteration: %d' % i) # post a request to the sampler for a query location req = requests.post(sampler_info['obs_uri']) query_loc = req.json() # Evaluate the sampler's query on the forward model characteristic = np.array(query_loc['query']) uid = query_loc['uid'] uid, measurement = simulate_measurement_vector(characteristic, uid) # log.info('Generated measurement ' + measurement.__repr__()) # Update the sampler with the new observation put_response = requests.put(query_loc['uri'], json=measurement.tolist()) if i in plot_triggers: log.info("Plotting") plot_progress(plots, sampler_info) print('Finished.') # # Retrieve Training Data: # log.info('Retrieving training data') # training_data = requests.get(sampler_info['training_data_uri']).json() # log.info('X:' + str(training_data['X'])) # log.info('y:' + str(training_data['y'])) # log.info('Virtual X:' + str(training_data['virtual_X'])) # log.info('Virtual y:' + str(training_data['virtual_y'])) vv.use().Run() except Exception: etype, evalue, etraceback = sys.exc_info() tb = traceback.extract_tb(etraceback) print(tb.to_dict()) server.terminate()