def ShowImg (self) : """ Draw image """ if self._abort_img : # Exit return # Get image img = self.dev.StopImgAqusition() # Display image try : if img <> RETURN_FAIL : self._img_plot.SetData(img) except AttributeError : visvis.cla() visvis.clf() self._img_plot = visvis.imshow(img) visvis.title ('Camera view') ax = visvis.gca() ax.axis.xTicks = [] ax.axis.yTicks = [] # Start acquisition of histogram self.dev.StartImgAqusition() wx.CallAfter(self.ShowImg)
def PlotReferencePhase (self, event) : """ Plot reference phase """ visvis.cla(); visvis.clf(); # get actual amplitude and phased phase = self.GetReferencePhase()[0] ampl = np.ones(phase.size) ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(ampl, phase) # Wrap the phase in radians phase %= (2*np.pi) # Get the phase in unites of 2*pi phase /= (2*np.pi) visvis.subplot(211) visvis.plot(phase) visvis.ylabel ('Reference phase') visvis.xlabel ('puls shaper pixel number') visvis.title ('Current reference phase (in unites of 2*pi)') visvis.subplot(212) visvis.plot( self.corrections, lc='r',ms='*', mc='r' ) visvis.ylabel ('Value of coefficients') visvis.xlabel ('coefficient number') visvis.title ('Value of corrections')
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 show(items, normals=None): """Function that shows a mesh object. """ for item in items: vv.clf() # convert to visvis.Mesh class new_normals = [] new_vertices = [] for k, v in item.vertices.iteritems(): new_normals.append(item.normal(k)) new_vertices.append(v) mesh = item.to_visvis_mesh() mesh.SetVertices(new_vertices) mesh.SetNormals(new_normals) mesh.faceColor = 'y' mesh.edgeShading = 'plain' mesh.edgeColor = (0, 0, 1) axes = vv.gca() if axes.daspectAuto is None: axes.daspectAuto = False axes.SetLimits() if normals is not None: for normal in normals: sl = solidLine(normal, 0.15) sl.faceColor = 'r' # Show title and enter main loop vv.title('Show') app = vv.use() app.Run()
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 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 drawNodalValues(nodeVals, coords, edof, dofsPerNode, elType, clim=None, axes=None, axesAdjust=True, doDrawMesh=True, title=None): ''' Draws scalar nodal values in 2D or 3D. Returns the Mesh object that represents the mesh. Parameters: nodeVals - An N-by-1 array or a list of scalars. The Scalar values at the nodes. nodeVals[i] should be the value of node i coords - An N-by-2 or N-by-3 array. Row i contains the x,y,z coordinates of node i. edof - An E-by-L array. Element topology. (E is the number of elements and L is the number of dofs per element) dofsPerNode - Integer. Dofs per node. elType - Integer. Element Type. See Gmsh manual for details. Usually 2 for triangles or 3 for quadrangles. clim - 2-tuple. Colorbar limits (min, max). Defines the value range of the colorbar. Defaults to None, in which case min/max are set to min/max of nodeVals. axes - Visvis Axes. The Axes where the model will be drawn. If unspecified the current Axes will be used, or a new Axes will be created if none exist. axesAdjust - Boolean. True if the view should be changed to show the whole model. Default True. doDrawMesh - Boolean. True if mesh wire should be drawn. Default True. title - String. Changes title of the figure. Default "Node Values". ''' axes, verts, faces, verticesPerFace, is3D = _preMeshDrawPrep(axes, coords, edof, dofsPerNode, elType) m = vv.Mesh(parent=axes, vertices=verts, faces=faces, values=nodeVals, verticesPerFace=verticesPerFace) if clim != None: #Set colorbar limits. m.clim = clim setClim = False else: setClim = True edgeSh = 'plain' if doDrawMesh else None m.faceShading, m.edgeShading = ('smooth', edgeSh)#NOTE: It seems colormap coloring breaks when faceshading='plain'. 'smooth' must be used. m.ambient = 1 m.diffuse = 0 m.specular = 0 #Disable specular. m.SetValues(nodeVals, setClim) #Set the values again, because it doesn't work in the constructor for unknown reasons axes.light0.ambient = 1.0 axes.light0.diffuse = 0.0 #Only ambient light to avoid shadows m.colormap = vv.colormaps['jet'] _makeColorBar("Node values", axes) # Adjust axes: if axesAdjust: _adjustaxes(axes, is3D) vv.title(title, axes) return m
def drawDisplacements(displacements, coords, edof, dofsPerNode, elType, nodeVals=None, clim=None, axes=None, axesAdjust=True, doDrawUndisplacedMesh=True, magnfac=1.0, title=None): ''' Draws mesh with displacements in 2D or 3D. Scalar nodal values can also be drawn on the mesh. Returns the displaced Mesh object. Parameters: displacements-An N-by-1 array (or matrix). Row i contains the displacement of dof i. N-by-2 or N-by-3 arrays are also accepted, in which case row i contains the x,y,z displacements of node i. coords - An N-by-2 or N-by-3 array. Row i contains the x,y,z coordinates of node i. edof - An E-by-L array. Element topology. (E is the number of elements and L is the number of dofs per element) dofsPerNode - Integer. Dofs per node. elType - Integer. Element Type. See Gmsh manual for details. Usually 2 for triangles or 3 for quadrangles. nodeVals - An N-by-1 array or a list of scalars. The Scalar values at the nodes. nodeVals[i] should be the value of node i. clim - 2-tuple. Colorbar limits (min, max). Defines the value range of the colorbar. Defaults to None, in which case min/max are set to min/max of nodeVals. axes - Visvis Axes. The Axes where the model will be drawn. If unspecified the current Axes will be used, or a new Axes will be created if none exist. axesAdjust - Boolean. True if the view should be changed to show the whole model. Default True. doDrawMesh - Boolean. True if mesh wire should be drawn. Default True. magnfac - Float. Magnification factor. Displacements are multiplied by this value. Use this to make small displacements more visible. title - String. Changes title of the figure. Default None (in which case title depends on other parameters). ''' if displacements.shape[1] != coords.shape[1]: displacements = np.reshape(displacements, (-1, coords.shape[1])) displaced = np.asarray(coords + magnfac * displacements) if doDrawUndisplacedMesh: drawMesh(coords, edof, dofsPerNode, elType, axes, axesAdjust, title=title, color=(0.5, 0.5, 0.5), filled=False) if nodeVals != None: m = drawNodalValues(nodeVals, displaced, edof, dofsPerNode, elType, clim=clim, axes=axes, axesAdjust=axesAdjust, doDrawMesh=True, title=title) else: m = drawMesh(displaced, edof, dofsPerNode, elType, axes, axesAdjust, title=title) if title != None: vv.title(title, axes) return m
def ScanVoltage (self) : """ Using the iterator <self.scan_pixel_voltage_pair> record the spectral response by applying the voltages """ # Pause calibration, if user requested try : if self.pause_calibration : return except AttributeError : return try : param = self.scan_pixel_voltage_pair.next() self.PulseShaper.SetUniformMasks(*param) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Save the spectrum try : self.SpectraGroup["voltages_%d_%d" % param] = spectrum except RuntimeError : print "There was RuntimeError while saving scan voltages_%d_%d" % param # Plot the spectra visvis.gca().Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Scanning progress info self.scanned += 1. percentage_completed = 100.*self.scanned/self.scan_length seconds_left = ( time.clock() - self.initial_time )*(100./percentage_completed - 1.) # convert to hours:min:sec m, s = divmod(seconds_left, 60) h, m = divmod(m, 60) title_info = param + (percentage_completed, h, m, s) visvis.title ("Scanning spectrum by applying voltages %d/%d. Progress: %.1f%% completed. Time left: %d:%02d:%02d." % title_info) self.fig.DrawNow() # Measure the next pair wx.CallAfter(self.ScanVoltage) except StopIteration : # Perform processing of the measured data wx.CallAfter(self.ExtractPhaseFunc, filename=self.calibration_file.filename) # All voltages are scanned self.StopAllJobs() # Sop using the shaper self.PulseShaper.StopDevice()
def __init__(self, sampleinterval=0.1, timewindow=10.0, size=(600, 350)): # Data stuff self._interval = int(sampleinterval * 1000) self._bufsize = int(timewindow / sampleinterval) self.databuffer = collections.deque([0.0] * self._bufsize, self._bufsize) self.x = np.linspace(-timewindow, 0.0, self._bufsize) self.y = np.zeros(self._bufsize, dtype=np.float) # Visvis stuff self.app = vv.use("qt4") vv.title("Dynamic Plotting with VisVis") self.line = vv.plot(self.x, self.y, lc="b", lw=3, ms="+") vv.xlabel("time") vv.ylabel("amplitude") self.ax = vv.gca() self.timer = vv.Timer(self.app, 50, oneshot=False) self.timer.Bind(self.updateplot) self.timer.Start()
def DrawSpectrum (self, event) : """ Draw spectrum interactively """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL : return # Display the spectrum if len(spectrum.shape) > 1: try : self.__interact_2d_spectrum__.SetData(spectrum) except AttributeError : visvis.cla(); visvis.clf(); # Spectrum is a 2D image visvis.subplot(211) self.__interact_2d_spectrum__ = visvis.imshow(spectrum, cm=visvis.CM_JET) visvis.subplot(212) # Plot a vertical binning spectrum = spectrum.sum(axis=0) # Linear spectrum try : self.__interact_1d_spectrum__.SetYdata(spectrum) except AttributeError : if self.wavelengths is None : self.__interact_1d_spectrum__ = visvis.plot (spectrum, lw=3) visvis.xlabel ("pixels") else : self.__interact_1d_spectrum__ = visvis.plot (self.wavelengths, spectrum, lw=3) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") if self.is_autoscaled_spectrum : # Smart auto-scale linear plot try : self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum, self.spectrum_plot_limits) except AttributeError : self.spectrum_plot_limits = GetSmartAutoScaleRange(spectrum) visvis.gca().SetLimits ( rangeY=self.spectrum_plot_limits ) # Display the current temperature try : visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() ) except AttributeError : pass
def draw_spectrum (event) : """Timer function """ spectrum = self.Spectrometer.AcquiredData() if spectrum == RETURN_FAIL : return # Display the spectrum ############### Take the log of spectrum ########## #spectrum = spectrum / float(spectrum.max()) #np.log10(spectrum, out=spectrum) ############################## ax = visvis.gca() ax.Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") # Display the current temperature visvis.title ("Temperature %d (C)" % self.Spectrometer.GetTemperature() )
def psf_volume(stack, xyz_ratio, filepath): app = vv.use() # Init a figure with two axes a1 = vv.subplot(121) vv.title('PSF Volume') a2 = vv.subplot(122) vv.title('PSF XYZ Cross Sections') # show t1 = vv.volshow(stack, axes=a1) # volume t2 = vv.volshow2(stack, axes=a2) # cross-section interactive # set labels for both axes vv.xlabel('Pixel X', axes=a1) vv.ylabel('Pixel Y', axes=a1) vv.zlabel('Z-Slice', axes=a1) vv.xlabel('Pixel X', axes=a2) vv.ylabel('Pixel Y', axes=a2) vv.zlabel('Z-Slice', axes=a2) # set colormaps t1.colormap = vv.CM_JET t2.colormap = vv.CM_JET # set correct aspect ration corresponding to voxel size a1.daspect = 1, 1, xyz_ratio a2.daspect = 1, 1, xyz_ratio # show grid a1.axis.showGrid = 1 a2.axis.showGrid = 1 # run visvis and show results app.Run() # save screenshot if filepath != 'nosave': print 'Saving PSF volume.' savename = filepath[:-4] + '_PSF_3D.png' # sf: scale factor vv.screenshot(savename, sf=1, bg='w')
def drawMesh(coords, edof, dofsPerNode, elType, axes=None, axesAdjust=True, title=None, color=(0,0,0), faceColor=(1,1,1), filled=False): ''' Draws wire mesh of model in 2D or 3D. Returns the Mesh object that represents the mesh. Parameters: coords - An N-by-2 or N-by-3 array. Row i contains the x,y,z coordinates of node i. edof - An E-by-L array. Element topology. (E is the number of elements and L is the number of dofs per element) dofsPerNode - Integer. Dofs per node. elType - Integer. Element Type. See Gmsh manual for details. Usually 2 for triangles or 3 for quadrangles. axes - Visvis Axes. The Axes where the model will be drawn. If unspecified the current Axes will be used, or a new Axes will be created if none exist. axesAdjust - Boolean. True if the view should be changed to show the whole model. Default True. title - String. Changes title of the figure. Default "Mesh". color - 3-tuple or char. Color of the wire. Defaults to black (0,0,0). Can also be given as a character in 'rgbycmkw'. faceColor - 3-tuple or char. Color of the faces. Defaults to white (1,1,1). Parameter filled must be True or faces will not be drawn at all. filled - Boolean. Faces will be drawn if True. Otherwise only the wire is drawn. Default False. ''' #Prep: axes, verts, faces, verticesPerFace, is3D = _preMeshDrawPrep(axes, coords, edof, dofsPerNode, elType) #Create mesh: m = vv.Mesh(parent=axes, vertices=verts, faces=faces, values=color, verticesPerFace=verticesPerFace) #Settings: fShade = 'plain' if filled else None m.faceShading, m.edgeShading = (fShade, 'plain') m.edgeColor = color m.faceColor = faceColor m.specular = 0 #Adjust axes: if axesAdjust: _adjustaxes(axes, is3D) #Set title and return: vv.title(title, axes) return m
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 ShowSpectra_by_VaryingPixelBundle (self) : """ This method is affiliated to the method <self.VaryPixelBundle> """ # Exit if the iterator is not defined try : self.pixel_bundel_value_iter except AttributeError : return try : voltage = self.pixel_bundel_value_iter.next() # Set the mask for pixel bundle width = self.SettingsNotebook.CalibrateShaper.pixel_bundle_width.GetValue() / 2 start_pixel_bundle = self.pixel_to_vary.GetValue() mask = np.copy(self.fixed_mask) if width: mask[max(start_pixel_bundle-width, 0):min(mask.size, start_pixel_bundle+width)] = voltage else: # Enforce single pixel width mask[min(max(start_pixel_bundle,0),mask.size)] = voltage self.PulseShaper.SetMasks( mask, self.fixed_mask) # Getting spectrum spectrum = self.Spectrometer.AcquiredData() # Plot the spectra visvis.gca().Clear() visvis.plot (self.wavelengths, spectrum) visvis.xlabel("wavelength (nm)") visvis.ylabel("counts") visvis.title ("Voltage %d / %d " % (voltage, self.fixed_mask[0]) ) self.fig.DrawNow() # Going to the next iteration wx.CallAfter (self.ShowSpectra_by_VaryingPixelBundle) except StopIteration : # Finish the job self.StopAllJobs()
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 GetDeltaScan (self, event) : """ Measure spectra by varying parameter delta in reference phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL : raise RuntimeError ("Optimization cannot be started since calibration file was not loaded") miips_settings = self.GetSettings() ##################################################################### # Get range of coefficient coeff_range = np.linspace( miips_settings["coeff_min"], miips_settings["coeff_max"], miips_settings["coeff_num"] ) # Get reference phase based on the corrections already obtained reference_phase, X, polynomial_basis = self.GetReferencePhase(miips_settings) # Get new polynomial new_coeffs = np.zeros(miips_settings["polynomial_order"] + 1) new_coeffs[-1] = 1 current_polynomial = polynomial_basis(new_coeffs)(X) # Chose max amplitude max_ampl = miips_settings["max_ampl"]*np.ones(self.num_pixels) # Adjusting button's settings button = event.GetEventObject() button.SetLabel (button._stop_label) button.SetBackgroundColour('red') button.Bind( wx.EVT_BUTTON, button._stop_method) self.need_abort = False for scan_num, coeff in enumerate(coeff_range) : # Get current phase mask current_phase = coeff*current_polynomial current_phase += reference_phase # Check for consistency current_phase %= 1 # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, current_phase) wx.Yield() # abort, if requested if self.need_abort : break # Get spectrum spectrum = self.DevSpectrometer.AcquiredData() # Vertical binning spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum ) try : spectral_scans except NameError : # Allocate space for spectral scans spectral_scans = np.zeros( (coeff_range.size, spectrum.size), dtype=spectrum.dtype ) # Save spectrum spectral_scans[ scan_num ] = spectrum # Display the currently acquired data try : spectral_scan_2d_img.SetData(spectral_scans) except NameError : visvis.cla(); visvis.clf(); spectral_scan_2d_img = visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints') visvis.xlabel ('wavelegth') ####################################################### # Get current wavelength wavelength = self.DevSpectrometer.GetWavelengths() # Adding the scan to log self.scan_log.append( { "spectral_scans" : spectral_scans, "reference_phase" : reference_phase, "current_polynomial": current_polynomial, "coeff_range" : coeff_range, "wavelength" : wavelength } ) # Plotting fit visvis.cla(); visvis.clf(); ################ Find the value of coeff such that it maximizes the total intensity of SHG # Method 1: use polynomial filter # Ignored not scanned parameter spectral_sum = spectral_scans.sum(axis=1) indx = np.nonzero(spectral_sum > 0) # Fit the total spectral intensity with chosen polynomials spectral_sum_fit = polynomial_basis.fit(coeff_range[indx], spectral_sum[indx] , 10) # Find extrema of the polynomial fit opt_coeff = spectral_sum_fit.deriv().roots() # Find maximum fit_max_sum_val = opt_coeff[ np.argmax(spectral_sum_fit(opt_coeff)) ].real print "\n\nOptimal value of the coefficient (using the polynomial fit) is ", fit_max_sum_val # Method 2: Use Gaussian filter # Smoothing spectral scans filtered_spectral_scans = gaussian_filter(spectral_scans, (2, 0.5) ) gauss_max_sum_val = coeff_range[ np.argmax(filtered_spectral_scans.sum(axis=1)) ] print "\nOptimal value of the coefficient (using the Gaussian filter) is ", gauss_max_sum_val # If the difference between methods is great then use the Gaussian filter if abs(gauss_max_sum_val - fit_max_sum_val)/np.abs([gauss_max_sum_val, fit_max_sum_val]).max() > 0.3 : max_sum_val = gauss_max_sum_val else : max_sum_val = fit_max_sum_val self.current_coeff_val.SetValue( max_sum_val ) filtered_spectral_scans[ np.searchsorted(coeff_range, max_sum_val) ][0:-1:2] = spectral_scans.min() ################ Plotting results #################### #spectral_scan_2d_img.SetData(spectral_scans) #spectral_scan_2d_img.SetClim( spectral_scans.min(), spectral_scans.max() ) visvis.subplot(121) visvis.title("Raw spectral scans") visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth') visvis.subplot(122) visvis.title("Finding maximum") visvis.imshow(filtered_spectral_scans, cm=visvis.CM_JET) visvis.ylabel ('coefficeints'); visvis.xlabel ('wavelegth') # Readjust buttons settings self.StopScannning(event)
def drawGeometry(geoData, axes=None, axesAdjust=True, drawPoints=True, labelPoints=True, labelCurves=True, title=None, fontSize=11, N=20): ''' Draws the geometry (points and curves) in geoData Parameters: geoData - GeoData object. Geodata contains geometric information of the model. axes - Visvis Axes. The Axes where the model will be drawn. If unspecified the current Axes will be used, or a new Axes will be created if none exist. axesAdjust - Boolean. If True the view will be changed to show the whole model. Default True. drawPoints - Boolean. If True points will be drawn. labelPoints- Boolean. If True Points will be labeled. The format is: ID[marker]. If a point has marker==0 only the ID is written. labelCurves- Boolean. If True Curves will be labeled. The format is: ID(elementsOnCurve)[marker]. fontSize - Integer. Size of the text in the text labels. Default 11. N - Integer. The number of discrete points per curve segment. Default 20. Increase for smoother curves. Decrease for better performance. ''' if axes is None: axes = vv.gca() axes.bgcolor = (0.7, 0.7, 0.7) if drawPoints: P = np.array(geoData.getPointCoords()) #M-by-3 list of M points. plotArgs = {'mc':'r', 'mw':5, 'lw':0, 'ms':'o', 'axesAdjust':False, 'axes':axes} if geoData.is3D: vv.plot(P[:,0], P[:,1], P[:,2], **plotArgs) else: vv.plot(P[:,0], P[:,1], **plotArgs) if labelPoints: #Write text label at the points: for (ID, (xyz, elSize, marker)) in geoData.points.items(): #[[x, y, z], elSize, marker] text = " " + str(ID) + ("[%s]"%marker if marker is not 0 else '') addText(text, xyz, fontSize=fontSize-1, color=(0.5,0,0.5), axes=axes) for(ID, (curveName, pointIDs, marker, elementsOnCurve, _, _)) in geoData.curves.items(): points = geoData.getPointCoords(pointIDs) if curveName == "Spline": P = _catmullspline(points, N) if curveName == "BSpline": P = _bspline(points, N) if curveName == "Circle": P = _circleArc(*points, pointsOnCurve=N) if curveName == "Ellipse": P = _ellipseArc(*points, pointsOnCurve=N) plotArgs = {'lc':'k', 'ms':None, 'axesAdjust':False, 'axes':axes} #Args for plot style. Black lines with no symbols at points. if geoData.is3D: vv.plot(P[:,0], P[:,1], P[:,2], **plotArgs) else: vv.plot(P[:,0], P[:,1], **plotArgs) if labelCurves: midP = P[int(P.shape[0]*7.0/12), :].tolist() # Sort of midpoint along the curve. Where the text goes. #Create the text for the curve. Includes ID, elementsOnCurve, and marker: text = " "+str(ID) text += "(%s)"%(elementsOnCurve) if elementsOnCurve is not None else '' text += "[%s]"%(marker) if marker is not 0 else '' #Something like "4(5)[8]" addText(text, midP, fontSize=fontSize, axes=axes) if title != None: vv.title(title, axes) if axesAdjust: _adjustaxes(axes, geoData.is3D) axes.daspectAuto = False axes.daspect = (1,1,1)
""" This example demonstrates rendering a color volume. This example demonstrates two render styles. Note that all render styles are capable of rendering color data. """ import numpy as np import visvis as vv app = vv.use() # Use vv.aVolume to create random bars for each color plane N = 64 vol = np.empty((N,N,N,3), dtype='float32') for i in range(3): vol[:,:,:,i] = vv.aVolume(10,N) # Show vv.figure() a1 = vv.subplot(121); t1 = vv.volshow(vol[:,:,:,:], renderStyle = 'mip') vv.title('color MIP render') a2 = vv.subplot(122); t2 = vv.volshow(vol[:,:,:,:], renderStyle = 'iso') t2.isoThreshold = 0.5 vv.title('color ISO-surface render') # Share cameras a1.camera = a2.camera # Run app app.Run()
#!/usr/bin/env python import visvis as vv from visvis.pypoints import Aarray app = vv.use() # Let's say we have lena, but only the even pixels in the y dimension. # So each pixel should have twice the size in the y direction. im = vv.imread('lena.png') im = im[::2,:,:] # Init a figure with two axes vv.figure() a1 = vv.subplot(121); vv.title('pixel units') a2 = vv.subplot(122); vv.title('real-world units') # Method 1: scale the whole scene # Use this if you want the axis to depict pixel units. t1 = vv.imshow(im, axes=a1) a1.daspect = 1,-2 # daspect works x,y,z, the y-axis is flipped for images # Method 2: use the Aarray class to scale the image # You could use this is you know the physical dimensions of a pixel, # to have the axis depict, for example, mm. im2 = Aarray(im,(2,1,1)) # sampling is given in y,x,color order t2 = vv.imshow(im2, axes=a2) app.Run()
def drawElementValues(ev, coords, edof, dofsPerNode, elType, displacements=None, clim=None, axes=None, axesAdjust=True, doDrawMesh=True, doDrawUndisplacedMesh=False, magnfac=1.0, title=None): ''' Draws scalar element values in 2D or 3D. Returns the world object elementsWobject that represents the mesh. Parameters: ev - An N-by-1 array or a list of scalars. The Scalar values of the elements. ev[i] should be the value of element i. coords - An N-by-2 or N-by-3 array. Row i contains the x,y,z coordinates of node i. edof - An E-by-L array. Element topology. (E is the number of elements and L is the number of dofs per element) dofsPerNode - Integer. Dofs per node. elType - Integer. Element Type. See Gmsh manual for details. Usually 2 for triangles or 3 for quadrangles. displacements - An N-by-2 or N-by-3 array. Row i contains the x,y,z displacements of node i. clim - 2-tuple. Colorbar limits (min, max). Defines the value range of the colorbar. Defaults to None, in which case min/max are set to min/max of nodeVals. axes - Visvis Axes. The Axes where the model will be drawn. If unspecified the current Axes will be used, or a new Axes will be created if none exist. axesAdjust - Boolean. True if the view should be changed to show the whole model. Default True. doDrawMesh - Boolean. True if mesh wire should be drawn. Default True. doDrawUndisplacedMesh - Boolean. True if the wire of the undisplaced mesh should be drawn on top of the displaced mesh. Default False. Use only if displacements != None. magnfac - Float. Magnification factor. Displacements are multiplied by this value. Use this to make small displacements more visible. title - String. Changes title of the figure. Default "Element Values". ''' #Since vis.Mesh does not allow setting different colours for different faces, we need # a custom world object (WObject) for this function. # http://code.google.com/p/visvis/wiki/example_customWobject # http://code.google.com/p/visvis/wiki/creatingWibjectsAndWobjects if doDrawUndisplacedMesh: drawMesh(coords, edof, dofsPerNode, elType, axes, axesAdjust, color=(0.5, 0.5, 0.5)) if displacements is not None: if displacements.shape[1] != coords.shape[1]: displacements = np.reshape(displacements, (-1, coords.shape[1])) coords = np.asarray(coords + magnfac * displacements) axes, verts, faces, verticesPerFace, is3D = _preMeshDrawPrep(axes, coords, edof, dofsPerNode, elType) #This is done because 3D elements are made up of several faces. #TODO: Discard inner faces that are not visible. fPerElms = { 1:0, 2:1, 3:1, 4:4, 5:6} #TODO: Extend with more element types facesPerElement = fPerElms[elType] #Repeat the element values so that we get the value of each face: faceVals = np.repeat(ev, facesPerElement, axis=0) c = _elementsWobject(axes, faceVals, verts, faces, verticesPerFace, doDrawMesh, clim) #Creates the world object that gets drawn on screen. _makeColorBar("Element values", axes) #Finds or creates colorbar and sets the label. # Adjust axes if axesAdjust: _adjustaxes(axes, is3D) vv.title(title, axes) return c
def ExtractPhaseFunc(self, event=None, filename=None): """ This function is the last stage of calibration, when measured data is mathematically processed to obtain the calibration curves. """ # If filename is not specified, open the file dialogue if filename is None: filename = self.LoadSettings(title="Load calibration file...") # Update the name of pulse shaper calibration file import os self.SettingsNotebook.PulseShaper.SetSettings( {"calibration_file_name": os.path.abspath(filename)}) visvis.clf() # Loading the file calibration file with h5py.File(filename, 'a') as calibration_file: ############### Loading data #################### wavelengths = calibration_file["calibration_settings/wavelengths"][ ...] fixed_voltage = calibration_file[ "calibration_settings/fixed_voltage"][...] pulse_shaper_pixel_num = calibration_file[ "calibration_settings/pulse_shaper_pixel_num"][...] initial_pixel = calibration_file[ "settings/CalibrateShaper/initial_pixel"][...] final_pixel = calibration_file[ "settings/CalibrateShaper/final_pixel"][...] pixel_bundle_width = calibration_file[ "settings/CalibrateShaper/pixel_bundle_width"][...] pixel_to_lamba = str( calibration_file["settings/CalibrateShaper/pixel_to_lamba"][ ...]) # Convert to dict pixel_to_lamba = eval("{%s}" % pixel_to_lamba) # Loading scans of slave and masker masks master_mask_scans = [] slave_mask_scans = [] for key, spectrum in calibration_file[ "spectra_from_uniform_masks"].items(): master_volt, slave_volt = map(int, key.split('_')[-2:]) if master_volt == fixed_voltage: slave_mask_scans.append((slave_volt, spectrum[...])) if slave_volt == fixed_voltage: master_mask_scans.append((master_volt, spectrum[...])) # Sort by voltage master_mask_scans.sort() slave_mask_scans.sort() # Extract spectral scans and voltages for each mask master_mask_voltage, master_mask_scans = zip(*master_mask_scans) master_mask_voltage = np.array(master_mask_voltage) master_mask_scans = np.array(master_mask_scans) slave_mask_voltage, slave_mask_scans = zip(*slave_mask_scans) slave_mask_voltage = np.array(slave_mask_voltage) slave_mask_scans = np.array(slave_mask_scans) ################### Find the edges of pixels ################# # function that converts pixel number to pulse shaper # `pixel_to_lamba` is a dictionary with key = pixel, value = lambda deg = 1 #min(1,len(pixel_to_lamba)-1) print np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), 1) pixel2lambda_func = np.poly1d( np.polyfit(pixel_to_lamba.keys(), pixel_to_lamba.values(), deg=deg)) #lambda2pixel_func = np.poly1d( np.polyfit(pixel_to_lamba.values(), pixel_to_lamba.keys(), deg=deg ) ) # Get pixels_edges in shaper pixels pixels_edges_num = np.arange(initial_pixel, final_pixel, pixel_bundle_width) if pixels_edges_num[-1] < final_pixel: pixels_edges_num = np.append(pixels_edges_num, [final_pixel]) # Get pixels_edges in logical_pixel_lambda pixels_edges = pixel2lambda_func(pixels_edges_num) # Get pixels_edges in positions of the spectrometer spectra pixels_edges = np.abs(wavelengths - pixels_edges[:, np.newaxis]).argmin(axis=1) # Sorting indx = np.argsort(pixels_edges) pixels_edges = pixels_edges[indx] pixels_edges_num = pixels_edges_num[indx] # Plot visvis.cla() visvis.clf() visvis.plot(pixel_to_lamba.values(), pixel_to_lamba.keys(), ls=None, ms='*', mc='g', mw=15) visvis.plot(wavelengths[pixels_edges], pixels_edges_num, ls='-', lc='r') visvis.xlabel('wavelength (nm)') visvis.ylabel('pulse shaper pixel') visvis.legend(['measured', 'interpolated']) self.fig.DrawNow() ################ Perform fitting of the phase masks ################# master_mask_fits = self.FitSpectralScans(master_mask_scans, master_mask_voltage, pixels_edges) slave_mask_fits = self.FitSpectralScans(slave_mask_scans, slave_mask_voltage, pixels_edges) ################# Perform fitting of dispersion and phase functions ################# master_mask_TC_fitted, master_mask_scans, master_mask_disp_ph_curves = \ self.GetDispersionPhaseCurves (wavelengths, master_mask_scans, master_mask_voltage, pixels_edges, master_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) slave_mask_TC_fitted, slave_mask_scans, slave_mask_disp_ph_curves = \ self.GetDispersionPhaseCurves (wavelengths, slave_mask_scans, slave_mask_voltage, pixels_edges, slave_mask_fits, pixel2lambda_func, pulse_shaper_pixel_num ) ################ Saving fitting parameters #################### ################################################################# # Save surface calibration try: del calibration_file["calibrated_surface"] except KeyError: pass CalibratedSurfaceGroupe = calibration_file.create_group( "calibrated_surface") master_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group( "master_mask") for key, value in master_mask_disp_ph_curves.items(): master_mask_calibrated_surface[key] = value slave_mask_calibrated_surface = CalibratedSurfaceGroupe.create_group( "slave_mask") for key, value in slave_mask_disp_ph_curves.items(): slave_mask_calibrated_surface[key] = value ################################################################# # Clear the group, if it exits try: del calibration_file["calibrated_pixels"] except KeyError: pass # This group is self consistent, thus the redundancy in saved data (with respect to other group in the file) CalibratedPixelsGroupe = calibration_file.create_group( "calibrated_pixels") CalibratedPixelsGroupe["pixels_edges"] = pixels_edges # Finding spectral bounds for each pixel pixels_spectral_bounds = zip(wavelengths[pixels_edges[:-1]], wavelengths[pixels_edges[1:]]) # Pulse shaper pixel bounds pixels_bounds = zip(pixels_edges_num[:-1], pixels_edges_num[1:]) PixelsGroup = CalibratedPixelsGroupe.create_group("pixels") for pixel_num, master_mask_calibration, slave_mask_calibration, \ spectral_bound, pixel_bound in zip( range(len(master_mask_fits)), \ master_mask_fits, slave_mask_fits, pixels_spectral_bounds, pixels_bounds ) : pixel = PixelsGroup.create_group("pixel_%d" % pixel_num) pixel["spectral_bound"] = spectral_bound pixel["pixel_bound"] = pixel_bound # Saving fitted calibration data in the tabular form pixel["voltage_master_mask"] = master_mask_calibration[0] pixel["phase_master_mask"] = master_mask_calibration[1] pixel["voltage_slave_mask"] = slave_mask_calibration[0] pixel["phase_slave_mask"] = slave_mask_calibration[1] ################ Plotting results of calibration #################### visvis.cla() visvis.clf() visvis.subplot(2, 2, 1) visvis.imshow(master_mask_scans, cm=visvis.CM_JET) visvis.title("Master mask (measured data)") visvis.ylabel('voltage') visvis.xlabel('wavelength (nm)') visvis.subplot(2, 2, 3) visvis.imshow(master_mask_TC_fitted, cm=visvis.CM_JET) visvis.title("Master mask (fitted data)") visvis.ylabel('voltage') visvis.xlabel('wavelength (nm)') visvis.subplot(2, 2, 2) visvis.imshow(slave_mask_scans, cm=visvis.CM_JET) visvis.title("Slave mask (measured data)") visvis.ylabel('voltage') visvis.xlabel('wavelength (nm)') visvis.subplot(2, 2, 4) visvis.imshow(slave_mask_TC_fitted, cm=visvis.CM_JET) visvis.title("Slave mask (fitted data)") visvis.ylabel('voltage') visvis.xlabel('wavelength (nm)')
# Smooth a bit im = lena.copy() im[1:,:,:] = lena[:-1,:,:] im[:-1,:,:] += lena[1:,:,:] im[:,:-1,:] += lena[:,1:,:] im[:,1:,:] += lena[:,:-1,:] im /= 4 # Prepare figure vv.figure() # Without color, with colormap a1 = vv.subplot(121) m1 = vv.surf(im[:,:,0]) m1.colormap = vv.CM_HOT vv.title('With colormap') # With color a2 = vv.subplot(122) m2 = vv.surf(im[:,:,0], im) vv.title('With original texture') # Flip y-axis, otherwise the image is upside down a1.daspect = 1,-1,1 a2.daspect = 1,-1,1 # Enter mainloop app=vv.use() app.Run()
def showModelsStatic(ptcode,codes, vols, ss, mm, vs, showVol, clim, isoTh, clim2, clim2D, drawMesh=True, meshDisplacement=True, drawModelLines=True, showvol2D=False, showAxis=False, drawVessel=False, vesselType=1, meshColor=None, **kwargs): """ show one to four models in multipanel figure. Input: arrays of codes, vols, ssdfs; params from show_models_static Output: axes, colorbars """ # init fig f = vv.figure(1); vv.clf() # f.position = 0.00, 22.00, 1920.00, 1018.00 mw = 5 if drawMesh == True: lc = 'w' meshColor = meshColor else: lc = 'g' # create subplots if isinstance(codes, str): # if 1 ctcode, otherwise tuple of strings a1 = vv.subplot(111) axes = [a1] elif codes == (codes[0],codes[1]): a1 = vv.subplot(121) a2 = vv.subplot(122) axes = [a1,a2] elif codes == (codes[0],codes[1], codes[2]): a1 = vv.subplot(131) a2 = vv.subplot(132) a3 = vv.subplot(133) axes = [a1,a2,a3] elif codes == (codes[0],codes[1], codes[2], codes[3]): a1 = vv.subplot(141) a2 = vv.subplot(142) a3 = vv.subplot(143) a4 = vv.subplot(144) axes = [a1,a2,a3,a4] elif codes == (codes[0],codes[1], codes[2], codes[3], codes[4]): a1 = vv.subplot(151) a2 = vv.subplot(152) a3 = vv.subplot(153) a4 = vv.subplot(154) a5 = vv.subplot(155) axes = [a1,a2,a3,a4,a5] else: a1 = vv.subplot(111) axes = [a1] for i, ax in enumerate(axes): ax.MakeCurrent() vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], codes[i])) t = show_ctvolume(vols[i], ss[i].model, axis=ax, showVol=showVol, clim=clim, isoTh=isoTh, **kwargs) label = pick3d(ax, vols[i]) if drawModelLines == True: ss[i].model.Draw(mc='b', mw = mw, lc=lc) if showvol2D: for i, ax in enumerate(axes): t2 = vv.volshow2(vols[i], clim=clim2D, axes=ax) cbars = [] # colorbars if drawMesh: for i, ax in enumerate(axes): m = vv.mesh(mm[i], axes=ax) if meshDisplacement: m.clim = clim2 m.colormap = vv.CM_JET #todo: use colormap Viridis or Magma as JET is not linear (https://bids.github.io/colormap/) cb = vv.colorbar(ax) cbars.append(cb) elif meshColor is not None: if len(meshColor) == 1: m.faceColor = meshColor[0] # (0,1,0,1) else: m.faceColor = meshColor[i] else: m.faceColor = 'g' if drawVessel: for i, ax in enumerate(axes): v = showVesselMesh(vs[i], ax, type=vesselType) for ax in axes: ax.axis.axisColor = 1,1,1 ax.bgcolor = 25/255,25/255,112/255 # midnightblue # http://cloford.com/resources/colours/500col.htm ax.daspect = 1, 1, -1 # z-axis flipped ax.axis.visible = showAxis # set colorbar position for cbar in cbars: p1 = cbar.position cbar.position = (p1[0], 20, p1[2], 0.98) # x,y,w,h # bind rotate view and view presets [1,2,3,4,5] f = vv.gcf() f.eventKeyDown.Bind(lambda event: _utils_GUI.RotateView(event,axes,axishandling=False) ) f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event,axes) ) return axes, cbars
def showVolPhases(basedir, vols=None, ptcode=None, ctcode=None, cropname=None, showVol='iso', mipIsocolor=False, isoTh=310, slider=False, clim=(0,3000), clim2D=(-550, 500), fname=None): """ Show vol phases in motion container showVol= mip or iso or 2D; Provide either vols or location """ if vols is None: # Load volumes s = loadvol(basedir, ptcode, ctcode, cropname, 'phases', fname=fname) vols = [] for key in dir(s): if key.startswith('vol'): vols.append(s[key]) # Start vis f = vv.figure(1); vv.clf() f.position = 9.00, 38.00, 992.00, 944.00 a = vv.gca() a.daspect = 1, 1, -1 a.axis.axisColor = 1,1,1 a.axis.visible = False a.bgcolor = 0,0,0 if showVol=='mip': if not ptcode is None and not ctcode is None: vv.title('Maximum intensity projection cine-loop of the original ECG-gated CT volumes of patient %s at %s ' % (ptcode[8:], ctcode)) else: vv.title('Maximum intensity projection cine-loop of the original ECG-gated CT volumes ') else: if not ptcode is None and not ctcode is None: vv.title('ECG-gated CT scan cine-loop of the original ECG-gated CT volumes of patient %s at %s ' % (ptcode[8:], ctcode)) else: vv.title('ECG-gated CT scan cine-loop of the original ECG-gated CT volumes ') # Setup data container container = vv.MotionDataContainer(a) for vol in vols: if showVol == '2D': t = vv.volshow2(vol, clim=clim2D) # -750, 1000 t.parent = container else: t = vv.volshow(vol, clim=clim, renderStyle = showVol) t.parent = container if showVol == 'iso': t.isoThreshold = isoTh # iso or mip work well t.colormap = {'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)]} if mipIsocolor: t.colormap = {'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)]} # bind ClimEditor to figure if slider: if showVol=='mip': c = vv.ClimEditor(vv.gcf()) c.position = (10, 50) f.eventKeyDown.Bind(lambda event: _utils_GUI.ShowHideSlider(event, c) ) if showVol=='iso': c = IsoThEditor(vv.gcf()) c.position = (10, 50) f.eventKeyDown.Bind(lambda event: _utils_GUI.ShowHideSlider(event, c) ) f.eventKeyDown.Bind(lambda event: _utils_GUI.ViewPresets(event, [a]) ) print('------------------------') print('Use keys 1, 2, 3, 4 and 5 for preset anatomic views') print('Use v for a default zoomed view') print('Use x to show and hide axis') print('------------------------') return t
# Step B: Crop and Save SSDF vols = [vol] for cropname in cropnames: savecropvols(vols, ssdf_basedir, ptcode, ctcode, cropname, stenttype) ## Visualize result s1 = loadvol(ssdf_basedir, ptcode, ctcode, cropnames[0], what ='phase') vol = s1.vol # Visualize and compare colormap = {'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)]} import visvis as vv fig = vv.figure(1); vv.clf() fig.position = 0, 22, 1366, 706 a = vv.gca() a.daspect = 1,1,-1 t1 = vv.volshow(vol, clim=(0, 2500), renderStyle='iso') # iso or mip t1.isoThreshold = 400 t1.colormap = colormap t2 = vv.volshow2(vol, clim=(-550, 500)) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') # vv.title('One volume at %i procent of cardiac cycle' % phase ) vv.title('Static CT Volume' )
axes = [] # 1 model if codes == ctcode1: ax = drawmodelphasescycles(vol1, model1, modelori1, showVol, isoTh=isoTh, removeStent=removeStent, showmodelavgreg=showmodelavgreg, showvol=showvol, phases=phases, colors=colors, meshWithColors=meshWithColors, stripSizeZ=stripSizeZ) vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], ctcode1)) axes.append(ax) # 2 models if len(codes) == 2: a1 = vv.subplot(121) ax = drawmodelphasescycles(vol1, model1, modelori1, showVol, isoTh=isoTh, removeStent=removeStent, showmodelavgreg=showmodelavgreg, showvol=showvol, phases=phases, colors=colors,
s = ssdf.load( '/home/almar/data/dicom/cropped/croppedReg_pat01_gravity.bsdf') vol = s.vol ## # 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 #vv.CM_CT1 t.renderStyle = RS[i] tt.append(t) if a0 is None: a0 = a else: a.camera = a0.camera # Create colormap editor in first axes cme = vv.ColormapEditor(vv.gcf(), *tt[3:]) # Run app app.Create() app.Run()
## Start vis f = vv.figure(nr); vv.clf() if nr == 1: f.position = 8.00, 30.00, 1216.00, 960.00 else: f.position = 968.00, 30.00, 1216.00, 960.00 a = vv.gca() a.axis.axisColor = 1,1,1 a.axis.visible = False a.bgcolor = 0,0,0 a.daspect = 1, 1, -1 t = show_ctvolume(vol, model, showVol=showVol, clim=clim0, isoTh=isoTh) vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') if meshWithColors=='displacement': vv.title('Dynamic model for patient %s at %s (colorbar \b{%s} of motion in mm in %s)' % (ptcode[7:], ctcode, motion, dimension)) elif meshWithColors=='curvature': vv.title('Dynamic model for patient %s at %s (colorbar \b{%s} in cm^{-1})' % (ptcode[7:], ctcode, 'curvature change')) else: vv.title('Dynamic model for patient %s at %s ' % (ptcode[7:], ctcode)) # viewringcrop = {'daspect': (1.0, 1.0, -1.0), 'azimuth': 32.9516129032258, # 'elevation': 14.162658990412158, 'roll': 0.0, # 'loc': (166.79323747325407, 162.4692971514962, 52.28745470591859), # 'fov': 0.0, 'zoom': 0.026156241036960133} # m = vv.mesh(modelmesh) # # m.faceColor = 'g' # m.clim = 0, 5 # m.colormap = vv.CM_JET # Add motion
class OurCamera1(vv.cameras.TwoDCamera): _NAMES = ('our1', 8) # a string name to be able to set cameraType # an int so it has an index, allowing changing the camera via a shortcut class OurCamera2(vv.cameras.TwoDCamera): _NAMES = ('our2', 9) # Draw an image im = vv.imread('lena.png') vv.imshow(im) vv.title('Press ALT+8 for cam1 and ALT+9 for cam2') # Get axes a = vv.gca() # Add cameras and select the first a.camera = OurCamera1() a.camera = OurCamera2() a.cameraType = 'our1' # We can do this because we set the _NAMES attribute # Increase zoom a.camera.zoom *= 2 # Enter mainloop app = vv.use() app.Run()
#!/usr/bin/env python """ This example illustrates how to create an isocontour from an image and display it over the contour. The contour consists of a pointset in which each 2 subsequent points describe a linepiece. This code relies on scikit-image. For a possibly more useful representation of the contour, see skimage.measure.find_contours. """ import visvis as vv im = vv.imread('imageio:chelsea.png')[:, :, 1] pp = vv.isocontour(im) vv.figure(1) vv.clf() vv.imshow(im) vv.plot(pp, ls='+', lw=2) vv.title('Isocontour') app = vv.use() app.Run()
text : string The text to display. axes : Axes instance Display the image in this axes, or the current axes if not given. """ if axes is None: axes = vv.gca() # seek Title object for child in axes.children: if isinstance(child, vv.Title): ob = child ob.text = text break else: ob = vv.Title(axes, text) # destroy if no text, return object otherwise if not text: ob.Destroy() return None else: return ob if __name__=='__main__': a = vv.gca() vv.title('test title')
volOr.shape[0]), :, :] # pick a z slice in mid volume imTr = volTr[int(0.5 * volOr.shape[0]), :, :] sampling2 = sampling2[1:] # keep y,x origin2 = origin2[1:] vols = [imOr, imTr] if visualize: f = vv.figure(1) vv.clf() f.position = 0.00, 22.00, 1914.00, 1018.00 if reg2d: clim = (-500, 500) a1 = vv.subplot(221) vv.imshow(imOr, clim=clim) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') vv.title('Im1:Original (DataDressed)') a1.daspect = 1, 1, -1 a2 = vv.subplot(222) vv.imshow(imOr, clim=clim) vv.imshow(imTr, clim=clim) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') vv.title('Overlay') a2.daspect = 1, 1, -1 a3 = vv.subplot(223) vv.imshow(imTr, clim=clim) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') vv.title( 'Im2:Original transformed (DataDressedInterpolated u_\magnitude {})' .format(mat2['u_magnitude'][0][0]))
def DoScannning (self, event) : """ Perform scanning of different phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev self.DevSampleSwitcher = self.parent.SampleSwitcher.dev # Save global settings and get the name of log file self.log_filename = SaveSettings(SettingsNotebook=self.parent, title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5") if self.log_filename is None : return ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL : return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL : return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL : raise RuntimeError ("Optimization cannot be started since calibration file was not loaded") # Initiate sample switcher settings = self.parent.SampleSwitcher.GetSettings() if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL : return # Saving the name of channels odd_settings = self.GetSettings() self.channels = sorted(eval( "(%s,)" % odd_settings["channels"] )) if self.DevSampleSwitcher.GetChannelNum()-1 < max(self.channels) : raise ValueError ("Error: Some channels specified are not accessible by sample switcher.") # Check whether the background signal array is present self.CheckBackground() ##################################################################### # Get range of coefficient coeff_range = np.linspace( odd_settings["coeff_min"], odd_settings["coeff_max"], odd_settings["coeff_num"] ) # List all polynomial coefficients N = odd_settings["polynomial_order"] poly_coeffs = np.zeros( (coeff_range.size*N, N+1) ) for n in range(1,N+1) : poly_coeffs[(n-1)*coeff_range.size:n*coeff_range.size, n ] = coeff_range # Chose max amplitude max_ampl = odd_settings["max_ampl"]*np.ones(self.num_pixels) # Arguments of the basis X = np.linspace(-1., 1., self.num_pixels) # Retrieve the basis type polynomial_basis = self.polynomial_bases[ odd_settings["polynomial_basis"] ] # Adjusting button's settings button = event.GetEventObject() button.SetLabel (button._stop_label) button.SetBackgroundColour('red') button.Bind( wx.EVT_BUTTON, button._stop_method) self.need_abort = False ##################################################################### # Start scanning with h5py.File (self.log_filename, 'a') as log_file : for channel in self.channels : # Move to a selected channel self.DevSampleSwitcher.MoveToChannel(channel) # abort, if requested wx.Yield() if self.need_abort : break # Looping over pulse shapes for scan_num, coeff in enumerate(poly_coeffs) : # Calculate new phase phase = polynomial_basis(coeff)(X) # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, phase) # Save phase in radians ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase(max_ampl, phase) if scan_num == 0 : # Initialize the array phases_rad = np.zeros( (len(poly_coeffs), phase.size), dtype=phase.dtype ) amplitudes = np.zeros_like(phases_rad) amplitudes[:] = ampl.min() # Save phase phases_rad[scan_num] = phase amplitudes[scan_num] = ampl # abort, if requested wx.Yield() if self.need_abort : break # Get spectrum spectrum = self.GetSampleSpectrum(channel) # Vertical binning spectrum = ( spectrum.sum(axis=0) if len(spectrum.shape) == 2 else spectrum ) if scan_num == 0 : # Initialize the array spectra = np.zeros( (len(poly_coeffs), spectrum.size), dtype=spectrum.dtype ) spectra[:] = spectrum.min() # Save the spectrum spectra[scan_num] = spectrum # Display the currently acquired data try : spectra_2d_img.SetData(spectra) phases_rad_2d_img.SetData( phases_rad%(2*np.pi) ) #amplitudes_2d_img.SetData( amplitudes ) except NameError : visvis.cla(); visvis.clf() visvis.subplot(121) spectra_2d_img = visvis.imshow(spectra, cm=visvis.CM_JET) visvis.ylabel ('scans'); visvis.xlabel ('wavelegth') visvis.title("spectral scan") visvis.subplot(122) phases_rad_2d_img = visvis.imshow( phases_rad%(2*np.pi), cm=visvis.CM_JET) visvis.title("phase shapes") #visvis.subplot(133) #amplitudes_2d_img = visvis.imshow(amplitudes, cm=visvis.CM_JET) #visvis.title("amplitudes") # Save the data for the given channel try : del log_file[ str(channel) ] except KeyError : pass channel_grp = log_file.create_group( str(channel) ) channel_grp["spectra"] = spectra channel_grp["phases_rad"] = phases_rad channel_grp["amplitudes"] = amplitudes channel_grp["poly_coeffs"] = poly_coeffs # Readjust buttons settings self.StopScannning(event)
""" import visvis as vv class OurCamera1(vv.cameras.TwoDCamera): _NAMES = ('our1', 8) # a string name to be able to set cameraType # an int so it has an index, allowing changing the camera via a shortcut class OurCamera2(vv.cameras.TwoDCamera): _NAMES = ('our2', 9) # Draw an image im = vv.imread('lena.png') vv.imshow(im) vv.title('Press ALT+8 for cam1 and ALT+9 for cam2') # Get axes a = vv.gca() # Add cameras and select the first a.camera = OurCamera1() a.camera = OurCamera2() a.cameraType = 'our1' # We can do this because we set the _NAMES attribute # Increase zoom a.camera.zoom *= 2 # Enter mainloop app = vv.use() app.Run()
t3 = vv.Text(a, 'Look, I\'m at an angle, and red!', 1, 4) t3.textAngle = -20 t3.fontSize = 12 t3.textColor = "r" # Create text labels label1 = vv.Label(a, 'This is a Label') label1.position = 10, 0.9 label1.bgcolor = (0.5, 1, 0.5) ## A quick brown fox jumps over the lazy dog testText = 'A quick brown fox jumps over the lazy dog' # Create figure and figure fig = vv.figure() a = vv.cla() a.cameraType = '2d' vv.title(testText) # Create text labels for i in range(20): offset = 0.1 * i label = vv.Label(a, '| ' + testText + ' - %1.2f pixels offset' % offset) label.bgcolor = None label.position = 10 + 0.1 * i, 10 + i * 15 # Enter main loop app = vv.use() app.Run()
def title(self, value): vv.title(value) @property
def FitSpectralScans(self, scans, voltages, pixels_edges): """ Perform fitting to the pulse shaper's mask transmission coefficient """ def FitIndividualPixel(voltages, pixel, modulation, p0=None): """ Find fit for individual pixel with initial guess for phase function given by `modulation`. `voltages` voltage values for which `pixel` was measured `pixel` measured transmission (to be fitted) `p0` is the initial guess for fitting parametres """ def GetVM(V0, V1, m0, m1): """ Return voltage and phase modulation from parameters """ M = m0 + m1 * modulation V = np.linspace(V0, V1, M.size) return V, M def FittedTransmission(voltages, offset, amplitude, *params): """ Return the transmission function for a shaper """ V, M = GetVM(*params) return amplitude * np.cos(pchip_interpolate( V, M, voltages))**2 + offset # Set fitting parameters to their default values if p0 is None: p0 = [0., 1., voltages.min(), voltages.max(), 0., 1.] # Fitting the transmission try: popt, _ = curve_fit(FittedTransmission, voltages, pixel, p0=p0) except RuntimeError: popt = p0 # Get fitting error fitting_error = np.sum( (FittedTransmission(voltages, *popt) - pixel)**2) return fitting_error, GetVM(*popt[2:]), popt ############################################################################ # Selecting the voltage range V_min = max(voltages_trial.min(), voltages.min()) V_max = min(voltages_trial.max(), voltages.max()) indx = np.nonzero((V_min <= voltages) & (voltages <= V_max)) # Number of calibration points lying within the voltage region num_vol_trial = np.sum((V_min <= voltages_trial) & (voltages_trial <= V_max)) if num_vol_trial < 2: num_vol_trial = 2 # Re-sample modulation provided by CRi so that the voltage is equidistantly spaced resampled_vis_modulation = pchip_interpolate( voltages_trial, vis_modulation, np.linspace(V_min, V_max, min(len(voltages), num_vol_trial))) resampled_nir_modulation = pchip_interpolate( voltages_trial, nir_modulation, np.linspace(V_min, V_max, min(len(voltages), num_vol_trial))) # Normalizing scans scans -= scans.min(axis=0) scans /= scans.max(axis=0) # Bin the spectrum into pixels spectral_slices = map( lambda begin, end: scans[:, begin:end].mean(axis=1), pixels_edges[:-1], pixels_edges[1:]) # List containing calibration data for each pixel calibration = [] # Initial guesses for fitting vis_p0 = None nir_p0 = None # Fit individual pulse shaper pixels them for pixel_num, pixel in enumerate(spectral_slices): # Smoothing and normalizing each pixel #pixel = gaussian_filter(pixel,sigma=1) pixel -= pixel.min() pixel /= pixel.max() # Fit the pixel by using the vis calibration curve as the initial guess vis_err, vis_calibration, vis_p0 = FitIndividualPixel( voltages[indx], pixel[indx], resampled_vis_modulation, vis_p0) # Fit the pixel by using the nir calibration curve as the initial guess nir_err, nir_calibration, nir_p0 = FitIndividualPixel( voltages[indx], pixel[indx], resampled_nir_modulation, nir_p0) # Choose the best fit if nir_err > vis_err: calibation_voltage, calibration_phase = vis_calibration fit_err = vis_err else: calibation_voltage, calibration_phase = nir_calibration fit_err = nir_err ###################### Plot ######################## visvis.clf() # Plot measured data visvis.plot(voltages, pixel, lc='r', ms='*', mc='r') # Plot fitted data plot_voltages = np.linspace(calibation_voltage.min(), calibation_voltage.max(), 500) transmission_fit = np.cos( pchip_interpolate(calibation_voltage, calibration_phase, plot_voltages))**2 visvis.plot(plot_voltages, transmission_fit, lc='b') visvis.title('Calibrating pixel %d / %d' % (pixel_num, len(spectral_slices) - 1)) visvis.legend(['measured', 'fitted']) visvis.xlabel('voltages') visvis.ylabel('Transmission coefficient') self.fig.DrawNow() ############ Save the calibration data ################## calibration.append( (calibation_voltage, calibration_phase, fit_err)) return calibration
if mark == True: ax.plot([0, 0], [0, amax], 'b', ls='-', marker='_') ax.plot([T, T], [0, amax], 'b', ls='-', marker='_') ax.plot([2 * T, 2 * T], [0, amax], 'b', ls='-', marker='_') if __name__ == '__main__': # Show examples import visvis as vv vv.figure(1) vv.clf() a0 = vv.subplot(321) vv.title('default') plot_pattern(*get_motion_pattern()) a1 = vv.subplot(322) vv.title('A=2') plot_pattern(*get_motion_pattern(A=2)) a2 = vv.subplot(323) vv.title('T=0.6') plot_pattern(*get_motion_pattern(T=0.6)) a3 = vv.subplot(324) vv.title('N=10') plot_pattern(*get_motion_pattern(N=10)) a3.axis.showGrid = True
#im2 = im # Create new camera and attach #cam = vv.cameras.TwoDCamera() #a1.camera = cam for i in range(0, use_len): j = uval[i][1] im[:y1i+y0i,i*x1i:(i+1)*x1i] = img_lst[j][:y1i+y0i,:x1i] #x, y = (0, 288-fsz) #text = "Display "+bmarkf+" sub-benchmark for interval, BW" #txt = ("GIPS: %.3f bill instr/sec" % uval[i][0]) #w, h = font.getsize(text) #drawd.rectangle((x, y, x + w + 2*rct_brdr, y + h), fill='black') #drawd.text((x+rct_brdr, y), text, fill='white', font=font) #vv.Text(a1, txt, i*x1i, 20, 0, 'mono', 10) vv.title("hi") #t1 = vv.Text(im2, 'Visvis text', 0.2, 9, 0, 'mono', 30) #vv.Label(im2, '| ' + 'hime'+ ' - %1.2f pixels offset' % offset) # Create figure with two axes ##label1 = vv.Label(a1, 'This is a Label') ##label1.position = 10, 10 ##label1.bgcolor = (0.5, 1, 0.5) #t1 = vv.Text(a1, 'Visvis text', 0.2, 0, 0, 'mono', 20) #t = vv.imshow(im2, axes=a1) t = vv.imshow(im) t.aa = 2 # more anti-aliasing (default=1)
def set_title(self, title): vv.title(title.replace('\n', ' '))
def __init__(self,ptcode,ctcode,allcenterlines,basedir): """ Script to show the stent plus centerline model and select points on centerlines for motion analysis """ import os, time import pirt import visvis as vv import numpy as np import math import itertools import xlsxwriter from datetime import datetime from stentseg.utils.datahandling import select_dir, loadvol, loadmodel from stentseg.utils.new_pointset import PointSet from stentseg.stentdirect.stentgraph import create_mesh from stentseg.motion.vis import create_mesh_with_abs_displacement from stentseg.utils.visualization import show_ctvolume from pirt.utils.deformvis import DeformableTexture3D, DeformableMesh from stentseg.utils import PointSet from stentseg.stentdirect import stentgraph from visvis import Pointset # for meshes from stentseg.stentdirect.stentgraph import create_mesh from visvis.processing import lineToMesh, combineMeshes from visvis import ssdf from stentseg.utils.picker import pick3d try: from PyQt4 import QtCore, QtGui # PyQt5 except ImportError: from PySide import QtCore, QtGui # PySide2 from stentseg.apps.ui_dialog import MyDialog from stentseg.utils.centerline import dist_over_centerline # added for Mirthe import copy cropname = 'prox' exceldir = os.path.join(basedir,ptcode) # Load deformations and avg ct (forward for mesh) # centerlines combined in 1 model m = loadmodel(basedir, ptcode, ctcode, cropname, modelname = 'centerline_total_modelavgreg_deforms') model = m.model # centerlines separated in a model for each centerline # m_sep = loadmodel(basedir, ptcode, ctcode, cropname, modelname = 'centerline_modelavgreg_deforms') s = loadvol(basedir, ptcode, ctcode, cropname, what='avgreg') vol_org = copy.deepcopy(s.vol) s.vol.sampling = [vol_org.sampling[1], vol_org.sampling[1], vol_org.sampling[2]] s.sampling = s.vol.sampling vol = s.vol # Start visualization and GUI fig = vv.figure(30); vv.clf() fig.position = 0.00, 30.00, 944.00, 1002.00 a = vv.gca() a.axis.axisColor = 1,1,1 a.axis.visible = True a.bgcolor = 0,0,0 a.daspect = 1, 1, -1 lim = 2500 t = vv.volshow(vol, clim=(0, lim), renderStyle='mip') pick3d(vv.gca(), vol) b = model.Draw(mc='b', mw = 0, lc='g', alpha = 0.5) vv.xlabel('x (mm)');vv.ylabel('y (mm)');vv.zlabel('z (mm)') vv.title('Model for LSPEAS %s - %s' % (ptcode[7:], ctcode)) # Add clickable nodes t0 = time.time() node_points = [] for i, node in enumerate(sorted(model.nodes())): node_point = vv.solidSphere(translation = (node), scaling = (0.6,0.6,0.6)) node_point.faceColor = 'b' node_point.alpha = 0.5 node_point.visible = True node_point.node = node node_point.nr = i node_points.append(node_point) t1 = time.time() print('Clickable nodes created, which took %1.2f min.' % ((t1-t0)/60)) # list of correctly clicked nodes selected_nodes_sum = set() # 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 t0.bgcolor = None t0.visible = True t1 = vv.Label(a, '\b{Nodepair}: ', fontSize=11, color='w') t1.position = 0.1, 45, 0.5, 20 t1.bgcolor = None t1.visible = True # Initialize output variable to store pulsatility analysis storeOutput = list() def on_key(event): if event.key == vv.KEY_ENTER: # mogenlijkheden aantal nodes # 1 voor relative beweging vanuit avg punt # 2 voor onderlinge beweging tussen twee punten # 3 voor hoek in punt 2 van punt 1 naar punt 3 if len(selected_nodes) == 1: selectn1 = selected_nodes[0].node n1index = selected_nodes[0].nr n1Deforms = model.node[selectn1]['deforms'] output = point_pulsatility(selectn1, n1Deforms) output['NodesIndex'] = [n1index] # Store output with name dialog_output = get_index_name() output['Name'] = dialog_output storeOutput.append(output) # update labels t1.text = '\b{Node}: %i' % (n1index) t1.visible = True print('selection of 1 node stored') if len(selected_nodes) == 2: # get nodes selectn1 = selected_nodes[0].node selectn2 = selected_nodes[1].node # get index of nodes which are in fixed order n1index = selected_nodes[0].nr n2index = selected_nodes[1].nr nindex = [n1index, n2index] # get deforms of nodes n1Deforms = model.node[selectn1]['deforms'] n2Deforms = model.node[selectn2]['deforms'] # get pulsatility cl_merged = append_centerlines(allcenterlines) output = point_to_point_pulsatility(cl_merged, selectn1, n1Deforms, selectn2, n2Deforms, type='euclidian') output['NodesIndex'] = nindex # get distance_centerline #dist_cl = dist_over_centerline(cl_merged, selectn1, selectn2, type='euclidian') # toegevoegd Mirthe #dist_cl = dist_centerline_total(cl_merged, selectn1, # n1Deforms, selectn2, n2Deforms, type='euclidian') # Store output with name dialog_output = get_index_name() output['Name'] = dialog_output storeOutput.append(output) # update labels t1.text = '\b{Node pair}: %i - %i' % (nindex[0], nindex[1]) t1.visible = True print('selection of 2 nodes stored') if len(selected_nodes) == 3: # get nodes selectn1 = selected_nodes[0].node selectn2 = selected_nodes[1].node selectn3 = selected_nodes[2].node # get index of nodes which are in fixed order n1index = selected_nodes[0].nr n2index = selected_nodes[1].nr n3index = selected_nodes[2].nr nindex = [n1index, n2index, n3index] # get deforms of nodes n1Deforms = model.node[selectn1]['deforms'] n2Deforms = model.node[selectn2]['deforms'] n3Deforms = model.node[selectn3]['deforms'] # get angulation output = line_line_angulation(selectn1, n1Deforms, selectn2, n2Deforms, selectn3, n3Deforms) output['NodesIndex'] = nindex # Store output with name dialog_output = get_index_name() output['Name'] = dialog_output storeOutput.append(output) # update labels t1.text = '\b{Nodes}: %i - %i - %i' % (nindex[0], nindex[1], nindex[2]) t1.visible = True print('selection of 3 nodes stored') if len(selected_nodes) > 3: for node in selected_nodes: node.faceColor = 'b' selected_nodes.clear() print('to many nodes selected, select 1,2 or 3 nodes') if len(selected_nodes) < 1: for node in selected_nodes: node.faceColor = 'b' selected_nodes.clear() print('to few nodes selected, select 1,2 or 3 nodes') # Visualize analyzed nodes and deselect for node in selected_nodes: selected_nodes_sum.add(node) for node in selected_nodes_sum: node.faceColor = 'g' # make green when analyzed selected_nodes.clear() if event.key == vv.KEY_ESCAPE: # FINISH MODEL, STORE TO EXCEL # Store to EXCEL storeOutputToExcel(storeOutput, exceldir) vv.close(fig) print('output stored to excel') selected_nodes = list() def select_node(event): """ select and deselect nodes by Double Click """ if event.owner not in selected_nodes: event.owner.faceColor = 'r' selected_nodes.append(event.owner) elif event.owner in selected_nodes: event.owner.faceColor = 'b' selected_nodes.remove(event.owner) def pick_node(event): nodenr = event.owner.nr node = event.owner.node t0.text = '\b{Node nr|location}: %i | x=%1.3f y=%1.3f z=%1.3f' % (nodenr,node[0],node[1],node[2]) def unpick_node(event): t0.text = '\b{Node nr|location}: ' def point_pulsatility(point1, point1Deforms): n1Indices = point1 + point1Deforms pos_combinations = list(itertools.combinations(range(len(point1Deforms)),2)) distances = [] for i in pos_combinations: v = point1Deforms[i[0]] - point1Deforms[i[1]] distances.append(((v[0]**2 + v[1]**2 + v[2]**2)**0.5 )) distances = np.array(distances) # get max distance between phases point_phase_max = distances.max() point_phase_max = [point_phase_max, [x*10 for x in (pos_combinations[list(distances).index(point_phase_max)])]] # get min distance between phases point_phase_min = distances.min() point_phase_min = [point_phase_min, [x*10 for x in (pos_combinations[list(distances).index(point_phase_min)])]] return {'point_phase_min':point_phase_min,'point_phase_max': point_phase_max, 'Node1': [point1, point1Deforms]} def point_to_point_pulsatility(cl, point1, point1Deforms, point2, point2Deforms,type='euclidian'): import numpy as np n1Indices = point1 + point1Deforms n2Indices = point2 + point2Deforms # define vector between nodes v = n1Indices - n2Indices distances = ( (v[:,0]**2 + v[:,1]**2 + v[:,2]**2)**0.5 ).reshape(-1,1) # get min and max distance point_to_pointMax = distances.max() point_to_pointMin = distances.min() # add phase in cardiac cycle where min and max where found (5th = 50%) point_to_pointMax = [point_to_pointMax, (list(distances).index(point_to_pointMax) )*10] point_to_pointMin = [point_to_pointMin, (list(distances).index(point_to_pointMin) )*10] # get median of distances point_to_pointMedian = np.percentile(distances, 50) # Q2 # median of the lower half, Q1 and upper half, Q3 point_to_pointQ1 = np.percentile(distances, 25) point_to_pointQ3 = np.percentile(distances, 75) # Pulsatility min max distance point to point point_to_pointP = point_to_pointMax[0] - point_to_pointMin[0] # add % change to pulsatility point_to_pointP = [point_to_pointP, (point_to_pointP/point_to_pointMin[0])*100 ] # find index of point on cll and calculate length change cll ??? if isinstance(cl, PointSet): cl = np.asarray(cl).reshape((len(cl),3)) indpoint1 = np.where( np.all(cl == point1, axis=-1) )[0] # -1 counts from last to the first axis indpoint2 = np.where( np.all(cl == point2, axis=-1) )[0] # renal point n1Indices = point1 + point1Deforms n2Indices = point2 + point2Deforms clDeforms = [] clpart_deformed = [] vectors = [] clpart = [] d = [] dist_cl = [] clpartDeforms = [] clpart_deformed_test = [] for i in range(len(cl)): clDeforms1 = model.node[cl[i,0], cl[i,1], cl[i,2]]['deforms'] clDeforms.append(clDeforms1) clpart_deformed1 = cl[i] + clDeforms1 clpart_deformed.append(clpart_deformed1) # clpart = cl[min(indpoint1[0], indpoint2[0]):max(indpoint1[0], indpoint2[0])+1] clpart = clpart_deformed[min(indpoint1[0], indpoint2[0]):max(indpoint1[0], indpoint2[0])+1] # for i in range(len(clpart)): # clpartDeforms1 = model.node[clpart[i,0], clpart[i,1], clpart[i,2]]['deforms'] # clpartDeforms.append(clpartDeforms1) # clpart_deformed1_test = cl[i] + clpartDeforms1 # clpart_deformed_test.append(clpart_deformed1_test) # for k in range(len(n1Indices)): # vectors_phases = np.vstack([clpart_deformed_test[i+1][k]-clpart_deformed_test[i][k] for i in range(len(clpart)-1)]) # vectors.append(vectors_phases) for k in range(len(n1Indices)): vectors_phases = np.vstack([clpart[i+1][k]-clpart[i][k] for i in range(len(clpart)-1)]) vectors.append(vectors_phases) for i in range(len(vectors)): if type == 'euclidian': d1 = (vectors[i][:,0]**2 + vectors[i][:,1]**2 + vectors[i][:,2]**2)**0.5 # 3Dvector length in mm d.append(d1) elif type == 'z': d = abs(vectors[i][:,2]) # x,y,z ; 1Dvector length in mm for i in range(len(d)): dist = d[i].sum() dist_cl.append(dist) #if indpoint2 > indpoint1: # stent point proximal to renal on centerline: positive #dist_cl*=-1 cl_min_index1 = np.argmin(dist_cl) cl_min_index = cl_min_index1*10 cl_min = min(dist_cl) cl_max_index1 = np.argmax(dist_cl) cl_max_index = cl_max_index1*10 cl_max = max(dist_cl) print ([dist_cl]) print ([point1, point2]) return {'point_to_pointMin': point_to_pointMin, 'point_to_pointQ1': point_to_pointQ1, 'point_to_pointMedian': point_to_pointMedian, 'point_to_pointQ3': point_to_pointQ3, 'point_to_pointMax': point_to_pointMax, 'point_to_pointP': point_to_pointP, 'Node1': [point1, point1Deforms], 'Node2': [point2, point2Deforms], 'distances': distances, 'dist_cl': dist_cl, 'cl_min_index': cl_min_index, 'cl_max_index': cl_max_index, 'cl_min': cl_min, 'cl_max': cl_max} def line_line_angulation(point1, point1Deforms, point2, point2Deforms, point3, point3Deforms): n1Indices = point1 + point1Deforms n2Indices = point2 + point2Deforms n3Indices = point3 + point3Deforms # get vectors v1 = n1Indices - n2Indices v2 = n3Indices - n2Indices # get angles angles = [] for i in range(len(v1)): angles.append(math.degrees(math.acos((np.dot(v1[i],v2[i]))/ (np.linalg.norm(v1[i])*np.linalg.norm(v2[i]))))) angles = np.array(angles) # get all angle differences of all phases pos_combinations = list(itertools.combinations(range(len(v1)),2)) angle_diff = [] for i in pos_combinations: v = point1Deforms[i[0]] - point1Deforms[i[1]] angle_diff.append(abs(angles[i[0]] - angles[i[1]])) angle_diff = np.array(angle_diff) # get max angle differences point_angle_diff_max = angle_diff.max() point_angle_diff_max = [point_angle_diff_max, [x*10 for x in (pos_combinations[list(angle_diff).index(point_angle_diff_max)])]] # get min angle differences point_angle_diff_min = angle_diff.min() point_angle_diff_min = [point_angle_diff_min, [x*10 for x in (pos_combinations[list(angle_diff).index(point_angle_diff_min)])]] return {'point_angle_diff_min':point_angle_diff_min, 'point_angle_diff_max': point_angle_diff_max, 'angles': angles, 'Node1': [point1, point1Deforms], 'Node2': [point2, point2Deforms], 'Node3': [point3, point1Deforms]} def append_centerlines(allcenterlines): """ Merge seperated PointSet centerlines into one PointSet """ # cl_merged = allcenterlines[0] cl_merged = PointSet(3) for i in range(0,len(allcenterlines)): for point in allcenterlines[i]: cl_merged.append(point) return cl_merged def get_index_name(): # Gui for input name app = QtGui.QApplication([]) m = MyDialog() m.show() m.exec_() dialog_output = m.edit.text() return dialog_output def storeOutputToExcel(storeOutput, exceldir): """Create file and add a worksheet or overwrite existing """ # https://pypi.python.org/pypi/XlsxWriter workbook = xlsxwriter.Workbook(os.path.join(exceldir,'storeOutput.xlsx')) worksheet = workbook.add_worksheet('General') # set column width worksheet.set_column('A:A', 35) worksheet.set_column('B:B', 30) # add a bold format to highlight cells bold = workbook.add_format({'bold': True}) # write title and general tab worksheet.write('A1', 'Output ChEVAS dynamic CT, 10 Phases', bold) analysisID = '%s_%s_%s' % (ptcode, ctcode, cropname) worksheet.write('A2', 'Filename:', bold) worksheet.write('B2', analysisID) worksheet.write('A3', 'Date and Time:', bold) date_time = datetime.now() #strftime("%d-%m-%Y %H:%M") date_format_str = 'dd-mm-yyyy hh:mm' date_format = workbook.add_format({'num_format': date_format_str, 'align': 'left'}) worksheet.write_datetime('B3', date_time, date_format) # write 'storeOutput' sort_index = [] for i in range(len(storeOutput)): type = len(storeOutput[i]['NodesIndex']) sort_index.append([i, type]) sort_index = np.array(sort_index) sort_index = sort_index[sort_index[:,1].argsort()] for i, n in sort_index: worksheet = workbook.add_worksheet(storeOutput[i]['Name']) worksheet.set_column('A:A', 35) worksheet.set_column('B:B', 20) worksheet.write('A1', 'Name:', bold) worksheet.write('B1', storeOutput[i]['Name']) if n == 1: worksheet.write('A2', 'Type:', bold) worksheet.write('B2', '1 Node') worksheet.write('A3', 'Minimum translation (mm, Phases)',bold) worksheet.write('B3', storeOutput[i]['point_phase_min'][0]) worksheet.write_row('C3', list(storeOutput[i]['point_phase_min'][1])) worksheet.write('A4', 'Maximum translation (mm, Phases)',bold) worksheet.write('B4', storeOutput[i]['point_phase_max'][0]) worksheet.write_row('C4', list(storeOutput[i]['point_phase_max'][1])) worksheet.write('A5', 'Avg node position and deformations', bold) worksheet.write('B5', str(list(storeOutput[i]['Node1'][0]))) worksheet.write_row('C5', [str(x)for x in list(storeOutput[i]['Node1'][1])]) worksheet.write('A6', 'Node Index Number', bold) worksheet.write_row('B6', list(storeOutput[i]['NodesIndex'])) elif n == 2: worksheet.write('A2', 'Type:', bold) worksheet.write('B2', '2 Nodes') worksheet.write('A3', 'Minimum distance (mm, Phases)',bold) worksheet.write('B3', storeOutput[i]['point_to_pointMin'][0]) worksheet.write('C3', storeOutput[i]['point_to_pointMin'][1]) worksheet.write('A4', 'Q1 distance (mm)',bold) worksheet.write('B4', storeOutput[i]['point_to_pointQ1']) worksheet.write('A5', 'Median distance (mm)',bold) worksheet.write('B5', storeOutput[i]['point_to_pointMedian']) worksheet.write('A6', 'Q3 distance (mm)',bold) worksheet.write('B6', storeOutput[i]['point_to_pointQ3']) worksheet.write('A7', 'Maximum distance (mm, phases)',bold) worksheet.write('B7', storeOutput[i]['point_to_pointMax'][0]) worksheet.write('C7', storeOutput[i]['point_to_pointMax'][1]) worksheet.write('A8', 'Maximum distance difference (mm)', bold) worksheet.write('B8', storeOutput[i]['point_to_pointP'][0]) worksheet.write('A9', 'Distances for each phase', bold) worksheet.write_row('B9', [str(x) for x in list(storeOutput[i]['distances'])]) worksheet.write('A10', 'Avg node1 position and deformations', bold) worksheet.write('B10', str(list(storeOutput[i]['Node1'][0]))) worksheet.write_row('C10', [str(x) for x in list(storeOutput[i]['Node1'][1])]) worksheet.write('A11', 'Avg node2 position and deformations', bold) worksheet.write('B11', str(list(storeOutput[i]['Node2'][0]))) worksheet.write_row('C11', [str(x) for x in list(storeOutput[i]['Node2'][1])]) worksheet.write('A12', 'Node Index Number', bold) worksheet.write_row('B12', list(storeOutput[i]['NodesIndex'])) worksheet.write('A13', 'Length centerline', bold) worksheet.write('B13', str(list(storeOutput[i]['dist_cl']))) worksheet.write('A14', 'Minimum length centerline', bold) worksheet.write('B14', storeOutput[i]['cl_min']) worksheet.write('C14', storeOutput[i]['cl_min_index']) worksheet.write('A15', 'Maximum length centerline', bold) worksheet.write('B15', storeOutput[i]['cl_max']) worksheet.write('C15', storeOutput[i]['cl_max_index']) elif n == 3: worksheet.write('A2', 'Type:', bold) worksheet.write('B2', '3 Nodes') worksheet.write('A3', 'Minimum angle difference (degrees, Phases)',bold) worksheet.write('B3', storeOutput[i]['point_angle_diff_min'][0]) worksheet.write_row('C3', list(storeOutput[i]['point_angle_diff_min'][1])) worksheet.write('A4', 'Maximum angle difference (degrees, Phases)',bold) worksheet.write('B4', storeOutput[i]['point_angle_diff_max'][0]) worksheet.write_row('C4', list(storeOutput[i]['point_angle_diff_max'][1])) worksheet.write('A5', 'Angles for each phase (degrees)',bold) worksheet.write_row('B5', list(storeOutput[i]['angles'])) worksheet.write('A6', 'Avg node1 position and deformations', bold) worksheet.write('B6', str(list(storeOutput[i]['Node1'][0]))) worksheet.write_row('C6', [str(x) for x in list(storeOutput[i]['Node1'][1])]) worksheet.write('A7', 'Avg node2 position and deformations', bold) worksheet.write('B7', str(list(storeOutput[i]['Node2'][0]))) worksheet.write_row('C7', [str(x) for x in list(storeOutput[i]['Node2'][1])]) worksheet.write('A8', 'Avg node2 position and deformations', bold) worksheet.write('B8', str(list(storeOutput[i]['Node3'][0]))) worksheet.write_row('C8', [str(x) for x in list(storeOutput[i]['Node3'][1])]) worksheet.write('A9', 'Node Index Number', bold) worksheet.write_row('B9', list(storeOutput[i]['NodesIndex'])) workbook.close() # Bind event handlers fig.eventKeyDown.Bind(on_key) for node_point in node_points: node_point.eventDoubleClick.Bind(select_node) node_point.eventEnter.Bind(pick_node) node_point.eventLeave.Bind(unpick_node)
def DoScannning(self, event): """ Perform scanning of different phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev self.DevSampleSwitcher = self.parent.SampleSwitcher.dev # Save global settings and get the name of log file self.log_filename = SaveSettings( SettingsNotebook=self.parent, title="Select file to save phase mask scanning", filename="scanning_phase_mask.hdf5") if self.log_filename is None: return ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL: return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL: return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL: raise RuntimeError( "Optimization cannot be started since calibration file was not loaded" ) # Initiate sample switcher settings = self.parent.SampleSwitcher.GetSettings() if self.DevSampleSwitcher.Initialize(settings) == RETURN_FAIL: return # Saving the name of channels odd_settings = self.GetSettings() self.channels = sorted(eval("(%s,)" % odd_settings["channels"])) if self.DevSampleSwitcher.GetChannelNum() - 1 < max(self.channels): raise ValueError( "Error: Some channels specified are not accessible by sample switcher." ) # Check whether the background signal array is present self.CheckBackground() ##################################################################### # Get range of coefficient coeff_range = np.linspace(odd_settings["coeff_min"], odd_settings["coeff_max"], odd_settings["coeff_num"]) # List all polynomial coefficients N = odd_settings["polynomial_order"] poly_coeffs = np.zeros((coeff_range.size * N, N + 1)) for n in range(1, N + 1): poly_coeffs[(n - 1) * coeff_range.size:n * coeff_range.size, n] = coeff_range # Chose max amplitude max_ampl = odd_settings["max_ampl"] * np.ones(self.num_pixels) # Arguments of the basis X = np.linspace(-1., 1., self.num_pixels) # Retrieve the basis type polynomial_basis = self.polynomial_bases[ odd_settings["polynomial_basis"]] # Adjusting button's settings button = event.GetEventObject() button.SetLabel(button._stop_label) button.SetBackgroundColour('red') button.Bind(wx.EVT_BUTTON, button._stop_method) self.need_abort = False ##################################################################### # Start scanning with h5py.File(self.log_filename, 'a') as log_file: for channel in self.channels: # Move to a selected channel self.DevSampleSwitcher.MoveToChannel(channel) # abort, if requested wx.Yield() if self.need_abort: break # Looping over pulse shapes for scan_num, coeff in enumerate(poly_coeffs): # Calculate new phase phase = polynomial_basis(coeff)(X) # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, phase) # Save phase in radians ampl, phase = self.DevPulseShaper.GetUnwrappedAmplPhase( max_ampl, phase) if scan_num == 0: # Initialize the array phases_rad = np.zeros((len(poly_coeffs), phase.size), dtype=phase.dtype) amplitudes = np.zeros_like(phases_rad) amplitudes[:] = ampl.min() # Save phase phases_rad[scan_num] = phase amplitudes[scan_num] = ampl # abort, if requested wx.Yield() if self.need_abort: break # Get spectrum spectrum = self.GetSampleSpectrum(channel) # Vertical binning spectrum = (spectrum.sum( axis=0) if len(spectrum.shape) == 2 else spectrum) if scan_num == 0: # Initialize the array spectra = np.zeros((len(poly_coeffs), spectrum.size), dtype=spectrum.dtype) spectra[:] = spectrum.min() # Save the spectrum spectra[scan_num] = spectrum # Display the currently acquired data try: spectra_2d_img.SetData(spectra) phases_rad_2d_img.SetData(phases_rad % (2 * np.pi)) #amplitudes_2d_img.SetData( amplitudes ) except NameError: visvis.cla() visvis.clf() visvis.subplot(121) spectra_2d_img = visvis.imshow(spectra, cm=visvis.CM_JET) visvis.ylabel('scans') visvis.xlabel('wavelegth') visvis.title("spectral scan") visvis.subplot(122) phases_rad_2d_img = visvis.imshow(phases_rad % (2 * np.pi), cm=visvis.CM_JET) visvis.title("phase shapes") #visvis.subplot(133) #amplitudes_2d_img = visvis.imshow(amplitudes, cm=visvis.CM_JET) #visvis.title("amplitudes") # Save the data for the given channel try: del log_file[str(channel)] except KeyError: pass channel_grp = log_file.create_group(str(channel)) channel_grp["spectra"] = spectra channel_grp["phases_rad"] = phases_rad channel_grp["amplitudes"] = amplitudes channel_grp["poly_coeffs"] = poly_coeffs # Readjust buttons settings self.StopScannning(event)
#!/usr/bin/env python import visvis as vv from visvis import Aarray app = vv.use() # Let's say we have lena, but only the even pixels in the y dimension. # So each pixel should have twice the size in the y direction. im = vv.imread('astronaut.png') im = im[::2, :, :] # Init a figure with two axes vv.figure() a1 = vv.subplot(121) vv.title('pixel units') a2 = vv.subplot(122) vv.title('real-world units') # Method 1: scale the whole scene # Use this if you want the axis to depict pixel units. t1 = vv.imshow(im, axes=a1) a1.daspect = 1, -2 # daspect works x,y,z, the y-axis is flipped for images # Method 2: use the Aarray class to scale the image # You could use this is you know the physical dimensions of a pixel, # to have the axis depict, for example, mm. im2 = Aarray(im, (2, 1, 1)) # sampling is given in y,x,color order t2 = vv.imshow(im2, axes=a2) app.Run()
def __init__(self, ptcode, ctcode, StartPoints, EndPoints, basedir, modelname='modelavgreg'): """ with start and endpoints provided, calculate centerline and save as ssdf in basedir as model and dynamic model """ #todo: name of dynamic model is now deforms, unclear, should be dynamic #import numpy as np import visvis as vv import numpy as np import os import copy from stentseg.utils import PointSet, _utils_GUI from stentseg.utils.centerline import (find_centerline, points_from_nodes_in_graph, points_from_mesh, smooth_centerline) from stentseg.utils.datahandling import loadmodel, loadvol from stentseg.utils.visualization import show_ctvolume from stentseg.utils.picker import pick3d stentnr = len(StartPoints) cropname = 'prox' what = modelname what_vol = 'avgreg' vismids = True m = loadmodel(basedir, ptcode, ctcode, cropname, what) s = loadvol(basedir, ptcode, ctcode, cropname, what_vol) s.vol.sampling = [s.sampling[1], s.sampling[1], s.sampling[2]] s.sampling = s.vol.sampling start1 = StartPoints.copy() ends = EndPoints.copy() from stentseg.stentdirect import stentgraph ppp = points_from_nodes_in_graph(m.model) allcenterlines = [] # for pp allcenterlines_nosmooth = [] # for pp centerlines = [] # for stentgraph nodes_total = stentgraph.StentGraph() for j in range(stentnr): if j == 0 or not start1[j] == ends[j - 1]: # if first stent or when stent did not continue with this start point nodes = stentgraph.StentGraph() centerline = PointSet(3) # empty # Find main centerline # if j > 3: # for stent with midpoints # centerline1 = find_centerline(ppp, start1[j], ends[j], step= 1, # ndist=10, regfactor=0.5, regsteps=10, verbose=False) #else: centerline1 = find_centerline(ppp, start1[j], ends[j], step=1, ndist=10, regfactor=0.5, regsteps=1, verbose=False) # centerline1 is a PointSet print('Centerline calculation completed') # ========= Maaike ======= smoothfactor = 15 # Mirthe used 2 or 4 # check if cll continued here from last end point if not j == 0 and start1[j] == ends[j - 1]: # yes we continued ppart = centerline1[: -1] # cut last but do not cut first point as this is midpoint else: # do not use first points, as they are influenced by user selected points ppart = centerline1[1:-1] for p in ppart: centerline.append(p) # if last stent or stent does not continue with next start-endpoint if j == stentnr - 1 or not ends[j] == start1[j + 1]: # store non-smoothed for vis allcenterlines_nosmooth.append(centerline) pp = smooth_centerline(centerline, n=smoothfactor) # add pp to list allcenterlines.append(pp) # list with PointSet per centerline self.allcenterlines = allcenterlines # add pp as nodes for i, p in enumerate(pp): p_as_tuple = tuple(p.flat) nodes.add_node(p_as_tuple) nodes_total.add_node(p_as_tuple) # add pp as one edge so that pathpoints are in fixed order pstart = tuple(pp[0].flat) pend = tuple(pp[-1].flat) nodes.add_edge(pstart, pend, path=pp) nodes_total.add_edge(pstart, pend, path=pp) # add final centerline nodes model to list centerlines.append(nodes) # ========= Maaike ======= ## Store segmentation to disk # Build struct s2 = vv.ssdf.new() s2.sampling = s.sampling s2.origin = s.origin s2.stenttype = m.stenttype s2.croprange = m.croprange for key in dir(m): if key.startswith('meta'): suffix = key[4:] s2['meta' + suffix] = m['meta' + suffix] s2.what = what s2.params = s.params #reg s2.paramsseeds = m.params s2.stentType = 'nellix' s2.StartPoints = StartPoints s2.EndPoints = EndPoints # keep centerlines as pp also [Maaike] s2.ppallCenterlines = allcenterlines for k in range(len(allcenterlines)): suffix = str(k) pp = allcenterlines[k] s2['ppCenterline' + suffix] = pp s3 = copy.deepcopy(s2) s3['model'] = nodes_total.pack() # Store model for each centerline for j in range(len(centerlines)): suffix = str(j) model = centerlines[j] s2['model' + suffix] = model.pack() # Save model with seperate centerlines. filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'centerline_' + what) vv.ssdf.save(os.path.join(basedir, ptcode, filename), s2) print('saved to disk as {}.'.format(filename)) # Save model with combined centerlines filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'centerline_total_' + what) vv.ssdf.save(os.path.join(basedir, ptcode, filename), s3) print('saved to disk as {}.'.format(filename)) # remove intermediate centerline points # start1 = map(tuple, start1) # ends = map(tuple, ends) startpoints_clean = copy.deepcopy(start1) endpoints_clean = copy.deepcopy(ends) duplicates = list(set(start1) & set(ends)) for i in range(len(duplicates)): startpoints_clean.remove(duplicates[i]) endpoints_clean.remove(duplicates[i]) #Visualize f = vv.figure(10) vv.clf() a1 = vv.subplot(121) a1.daspect = 1, 1, -1 vv.plot(ppp, ms='.', ls='', alpha=0.6, mw=2) for j in range(len(startpoints_clean)): vv.plot(PointSet(list(startpoints_clean[j])), ms='.', ls='', mc='g', mw=20) # startpoint green vv.plot(PointSet(list(endpoints_clean[j])), ms='.', ls='', mc='r', mw=20) # endpoint red for j in range(len(allcenterlines)): vv.plot(allcenterlines[j], ms='.', ls='', mw=10, mc='y') vv.title('Centerlines and seed points') vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') # for j in range(len(allcenterlines_nosmooth)): # vv.plot(allcenterlines_nosmooth[j], ms='o', ls='', mw=10, mc='c', alpha=0.6) a2 = vv.subplot(122) a2.daspect = 1, 1, -1 vv.plot(ppp, ms='.', ls='', alpha=0.6, mw=2) # vv.volshow(s.vol, clim=clim, renderStyle = 'mip') t = show_ctvolume(s.vol, axis=a2, showVol='ISO', clim=(0, 2500), isoTh=250, removeStent=False, climEditor=True) label = pick3d(vv.gca(), s.vol) for j in range(len(startpoints_clean)): vv.plot(PointSet(list(startpoints_clean[j])), ms='.', ls='', mc='g', mw=20, alpha=0.6) # startpoint green vv.plot(PointSet(list(endpoints_clean[j])), ms='.', ls='', mc='r', mw=20, alpha=0.6) # endpoint red for j in range(len(allcenterlines)): vv.plot(allcenterlines[j], ms='o', ls='', mw=10, mc='y', alpha=0.6) # show midpoints (e.g. duplicates) if vismids: for p in duplicates: vv.plot(p[0], p[1], p[2], mc='m', ms='o', mw=10, alpha=0.6) a2.axis.visible = False vv.title('Centerlines and seed points') a1.camera = a2.camera f.eventKeyDown.Bind( lambda event: _utils_GUI.RotateView(event, [a1, a2])) f.eventKeyDown.Bind( lambda event: _utils_GUI.ViewPresets(event, [a1, a2])) # Pick node for midpoint to redo get_centerline self.pickedCLLpoint = _utils_GUI.Event_pick_graph_point( nodes_total, s.vol, label, nodesOnly=True) # x,y,z # use key p to select point #=============================================================================== vv.figure(11) vv.gca().daspect = 1, 1, -1 t = show_ctvolume(s.vol, showVol='ISO', clim=(0, 2500), isoTh=250, removeStent=False, climEditor=True) label2 = pick3d(vv.gca(), s.vol) for j in range(len(startpoints_clean)): vv.plot(PointSet(list(startpoints_clean[j])), ms='.', ls='', mc='g', mw=20, alpha=0.6) # startpoint green vv.plot(PointSet(list(endpoints_clean[j])), ms='.', ls='', mc='r', mw=20, alpha=0.6) # endpoint red vv.xlabel('x (mm)') vv.ylabel('y (mm)') vv.zlabel('z (mm)') #=============================================================================== ## Make model dynamic (and store/overwrite to disk) import pirt from stentseg.motion.dynamic import incorporate_motion_nodes, incorporate_motion_edges # Load deforms filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'deforms') s1 = vv.ssdf.load(os.path.join(basedir, ptcode, filename)) deformkeys = [] for key in dir(s1): if key.startswith('deform'): deformkeys.append(key) deforms = [s1[key] for key in deformkeys] deforms = [ pirt.DeformationFieldBackward(*fields) for fields in deforms ] for i in range(len(deforms)): deforms[i]._field_sampling = tuple(s1.sampling) paramsreg = s1.params # Load model s2 = loadmodel(basedir, ptcode, ctcode, cropname, 'centerline_' + what) s3 = loadmodel(basedir, ptcode, ctcode, cropname, 'centerline_total_' + what) # Combine ... for key in dir(s2): if key.startswith('model'): incorporate_motion_nodes(s2[key], deforms, s.origin) incorporate_motion_edges(s2[key], deforms, s.origin) model = s2[key] s2[key] = model.pack() # Combine ... for key in dir(s3): if key.startswith('model'): incorporate_motion_nodes(s3[key], deforms, s.origin) incorporate_motion_edges(s3[key], deforms, s.origin) model = s3[key] s3[key] = model.pack() # Save s2.paramsreg = paramsreg filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'centerline_' + what + '_deforms') vv.ssdf.save(os.path.join(basedir, ptcode, filename), s2) print('saved to disk as {}.'.format(filename)) # Save s3.paramsreg = paramsreg filename = '%s_%s_%s_%s.ssdf' % ( ptcode, ctcode, cropname, 'centerline_total_' + what + '_deforms') vv.ssdf.save(os.path.join(basedir, ptcode, filename), s3) print('saved to disk as {}.'.format(filename))
def __init__(self, dicom_basedir, ptcode, ctcode, basedir): import imageio #import easygui from stentseg.utils.datahandling import loadvol from stentseg.utils.datahandling import savecropvols, saveaveraged ## Select base directory for LOADING DICOM data #dicom_basedir = easygui.diropenbox() print('DICOM Path = ', dicom_basedir) #ctcode = '12months' # 'pre', 'post_x', '12months' stenttype = 'nellix' ## Select base directory to SAVE SSDF #basedir = easygui.diropenbox() print('Base Path = ', basedir) # Set which crops to save cropnames = ['prox'] #,'stent'] # ['ring'] or ['ring','stent'] or .. #=============================================================================== ## Step A: read single volumes to get vols: # folder1 = '10%' # folder2 = '60%' # vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom') # vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom') # print( ) # # if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]: # vols4078 = [vol1,vol2] # else: # vols4078 = [vol2,vol1] # # vols = vols4078.copy() # # for vol in vols: # vol.meta.PatientName = ptcode # anonimyze # vol.meta.PatientID = 'anonymous' # print(vol.meta.SeriesDescription,'-', vol.meta.sampling) #=============================================================================== ##Orginele code #=============================================================================== # # folder1 = '40% iDose' # folder2 = '78 iDose' # vol1 = imageio.volread(os.path.join(dicom_basedir, folder1), 'dicom') # vol2 = imageio.volread(os.path.join(dicom_basedir, folder2), 'dicom') # print( ) # # if vol1.meta.SeriesDescription[:2] < vol2.meta.SeriesDescription[:2]: # vols4078 = [vol1,vol2] # else: # vols4078 = [vol2,vol1] # # vols = vols4078.copy() # # for vol in vols: # vol.meta.PatientName = ptcode # anonimyze # vol.meta.PatientID = 'anonymous' # print(vol.meta.SeriesDescription,'-', vol.meta.sampling) #=============================================================================== ## Step A: read 10 volumes to get vols # Deze zoekt alle mappen en dat zijn er dus 10 maar niet in de goede volgorde vols2 = [ vol2 for vol2 in imageio.get_reader(dicom_basedir, 'DICOM', 'V') ] vols = [None] * len(vols2) for i, vol in enumerate(vols2): # print(vol.meta.sampling) print(vol.meta.SeriesDescription) phase = int(vol.meta.SeriesDescription[:1]) # use phase to fix order of phases vols[phase] = vol #vols[phase].meta.ImagePositionPatient = (0.0,0.0,0.0) for i, vol in enumerate( vols): #wat ik heb veranderd is i, en enumerate() print(vol.meta.SeriesDescription) assert vol.shape == vols[0].shape assert str(i * 10) in vol.meta.SeriesDescription # 0% , 10% etc. ## Step B: Crop and Save SSDF # 1 of 2 cropnames opgeven voor opslaan 1 of 2 crpos. # Het eerste volume wordt geladen in MIP, crop met marges van minimaal 30 mm for cropname in cropnames: savecropvols(vols, basedir, ptcode, ctcode, cropname, stenttype) # saveaveraged(basedir, ptcode, ctcode, cropname, range(0,100,10)) ## Visualize result #s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10avgreg') #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what ='10phases') s1 = loadvol(basedir, ptcode, ctcode, cropnames[0], what='phases') #s2 = loadvol(basedir, ptcode, ctcode, cropnames[0], what = 'avg010') #vol1 = s1.vol vol1 = s1.vol40 # Visualize and compare colormap = { 'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)] } import visvis as vv fig = vv.figure(1) vv.clf() fig.position = 0, 22, 1366, 706 a1 = vv.subplot(111) a1.daspect = 1, 1, -1 # t1 = vv.volshow(vol1, clim=(0, 3000), renderStyle='iso') # iso or mip # t1.isoThreshold = 600 # stond op 400 maar je moet hoger zetten als je alleen stent wil # t1.colormap = colormap a1 = vv.volshow2(vol1, clim=(-500, 1500), renderStyle='mip') vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') # vv.title('One volume at %i procent of cardiac cycle' % phase ) vv.title('Vol40')
#!/usr/bin/env python import visvis as vv app = vv.use() f = vv.clf() a = vv.cla() vv.plot([12,34,21,38], lc='b', ls=':',mc='b', mw=7, lw=2, ms='s', mec='r') vv.plot([1,3,4],[33,47,12], lc='r', mc='r', ms='.') vv.plot([20,24,45,21], lc='g', ls='--', mc='g', mw=12, lw=3, ms='') vv.plot([35,14,40,31], lc='k', ls='-.', mc='g', mw=12, lw=3, ms='*') # If the star is not visible, your OpenGl system does not support point sprites a = vv.gca() a.legend = 'line 1', 'line 2', 'line 3' a.axis.showGrid = 1 a.axis.xlabel = 'measurement number' a.axis.ylabel = 'some quantity [unit]' vv.title('An example of \b{plotting}') app.Run()
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 # Create colormap editor in first axes cme = vv.ColormapEditor(vv.gcf(), *tt[3:]) # Run app app.Create() app.Run()
def title(self, value): vv.title(value)
def __open(self, dirname, filename): _info, spectrum, _locs = open_plot(dirname, filename) self.directory = dirname self.__plot(sort_spectrum(spectrum)) vv.title(filename)
def GetDeltaScan(self, event): """ Measure spectra by varying parameter delta in reference phase mask """ # Create pseudonyms of necessary devices self.DevSpectrometer = self.parent.Spectrometer.dev self.DevPulseShaper = self.parent.PulseShaper.dev ####################### Initiate devices ############################# # Initiate spectrometer settings = self.parent.Spectrometer.GetSettings() if self.DevSpectrometer.SetSettings(settings) == RETURN_FAIL: return # Initiate pulse shaper settings = self.parent.PulseShaper.GetSettings() if self.DevPulseShaper.Initialize(settings) == RETURN_FAIL: return # Get number of optimization variables self.num_pixels = self.DevPulseShaper.GetParamNumber() if self.num_pixels == RETURN_FAIL: raise RuntimeError( "Optimization cannot be started since calibration file was not loaded" ) miips_settings = self.GetSettings() ##################################################################### # Get range of coefficient coeff_range = np.linspace(miips_settings["coeff_min"], miips_settings["coeff_max"], miips_settings["coeff_num"]) # Get reference phase based on the corrections already obtained reference_phase, X, polynomial_basis = self.GetReferencePhase( miips_settings) # Get new polynomial new_coeffs = np.zeros(miips_settings["polynomial_order"] + 1) new_coeffs[-1] = 1 current_polynomial = polynomial_basis(new_coeffs)(X) # Chose max amplitude max_ampl = miips_settings["max_ampl"] * np.ones(self.num_pixels) # Adjusting button's settings button = event.GetEventObject() button.SetLabel(button._stop_label) button.SetBackgroundColour('red') button.Bind(wx.EVT_BUTTON, button._stop_method) self.need_abort = False for scan_num, coeff in enumerate(coeff_range): # Get current phase mask current_phase = coeff * current_polynomial current_phase += reference_phase # Check for consistency current_phase %= 1 # Set the pulse shape self.DevPulseShaper.SetAmplPhase(max_ampl, current_phase) wx.Yield() # abort, if requested if self.need_abort: break # Get spectrum spectrum = self.DevSpectrometer.AcquiredData() # Vertical binning spectrum = (spectrum.sum( axis=0) if len(spectrum.shape) == 2 else spectrum) try: spectral_scans except NameError: # Allocate space for spectral scans spectral_scans = np.zeros((coeff_range.size, spectrum.size), dtype=spectrum.dtype) # Save spectrum spectral_scans[scan_num] = spectrum # Display the currently acquired data try: spectral_scan_2d_img.SetData(spectral_scans) except NameError: visvis.cla() visvis.clf() spectral_scan_2d_img = visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel('coefficeints') visvis.xlabel('wavelegth') ####################################################### # Get current wavelength wavelength = self.DevSpectrometer.GetWavelengths() # Adding the scan to log self.scan_log.append({ "spectral_scans": spectral_scans, "reference_phase": reference_phase, "current_polynomial": current_polynomial, "coeff_range": coeff_range, "wavelength": wavelength }) # Plotting fit visvis.cla() visvis.clf() ################ Find the value of coeff such that it maximizes the total intensity of SHG # Method 1: use polynomial filter # Ignored not scanned parameter spectral_sum = spectral_scans.sum(axis=1) indx = np.nonzero(spectral_sum > 0) # Fit the total spectral intensity with chosen polynomials spectral_sum_fit = polynomial_basis.fit(coeff_range[indx], spectral_sum[indx], 10) # Find extrema of the polynomial fit opt_coeff = spectral_sum_fit.deriv().roots() # Find maximum fit_max_sum_val = opt_coeff[np.argmax( spectral_sum_fit(opt_coeff))].real print "\n\nOptimal value of the coefficient (using the polynomial fit) is ", fit_max_sum_val # Method 2: Use Gaussian filter # Smoothing spectral scans filtered_spectral_scans = gaussian_filter(spectral_scans, (2, 0.5)) gauss_max_sum_val = coeff_range[np.argmax( filtered_spectral_scans.sum(axis=1))] print "\nOptimal value of the coefficient (using the Gaussian filter) is ", gauss_max_sum_val # If the difference between methods is great then use the Gaussian filter if abs(gauss_max_sum_val - fit_max_sum_val) / np.abs( [gauss_max_sum_val, fit_max_sum_val]).max() > 0.3: max_sum_val = gauss_max_sum_val else: max_sum_val = fit_max_sum_val self.current_coeff_val.SetValue(max_sum_val) filtered_spectral_scans[np.searchsorted( coeff_range, max_sum_val)][0:-1:2] = spectral_scans.min() ################ Plotting results #################### #spectral_scan_2d_img.SetData(spectral_scans) #spectral_scan_2d_img.SetClim( spectral_scans.min(), spectral_scans.max() ) visvis.subplot(121) visvis.title("Raw spectral scans") visvis.imshow(spectral_scans, cm=visvis.CM_JET) visvis.ylabel('coefficeints') visvis.xlabel('wavelegth') visvis.subplot(122) visvis.title("Finding maximum") visvis.imshow(filtered_spectral_scans, cm=visvis.CM_JET) visvis.ylabel('coefficeints') visvis.xlabel('wavelegth') # Readjust buttons settings self.StopScannning(event)
def dicom2ssdf(dicom_basedir, ptcode, ctcode, basedir, cropnames=['stent'], savedistolicavg=False, visvol=True, visdynamic=False): """ read dicom volumes and store as ssdf format """ #Step A vols2 = [vol2 for vol2 in imageio.get_reader(dicom_basedir, 'DICOM', 'V')] try: for i, vol in enumerate(vols2): print(vol.meta.ImagePositionPatient) for i, vol in enumerate(vols2): print(vol.shape) for i, vol in enumerate(vols2): print(vol.meta.AcquisitionTime) print(vol.meta.sampling) assert vol.shape == vols2[0].shape assert vol.meta.SeriesTime == vols2[0].meta.SeriesTime except AttributeError: print('Some meta information is not available') pass # check order of phases vols = vols2.copy() try: for i, vol in enumerate(vols): print(vol.meta.SeriesDescription) assert str(i * 10) in vol.meta.SeriesDescription # 0% , 10% etc. except AttributeError: # meta info is missing print('vol.meta.SeriesDescription meta information is not available') pass except AssertionError: # not correct order, fix vols = [None] * len(vols2) for i, vol in enumerate(vols2): print(vol.meta.SeriesDescription) phase = int(vol.meta.SeriesDescription[:1]) # use phase to fix order of phases vols[phase] = vol # Step B: Crop and Save SSDF # Load and show first volume: crop with a margin of at least ~25 mm print() print('Crop with margins ~25 mm around ROI for the registration algorithm') stenttype = None # deprecate, not needed for cropname in cropnames: savecropvols(vols, basedir, ptcode, ctcode, cropname, stenttype) # Step C: average diastolic phases if savedistolicavg: phases = 50, 10 # use 7 phases from 50% to 10% saveaveraged(basedir, ptcode, ctcode, cropname, phases) # Visualize 1 phase import visvis as vv if visvol: vol1 = vols[1] colormap = { 'r': [(0.0, 0.0), (0.17727272, 1.0)], 'g': [(0.0, 0.0), (0.27272728, 1.0)], 'b': [(0.0, 0.0), (0.34545454, 1.0)], 'a': [(0.0, 1.0), (1.0, 1.0)] } fig = vv.figure(2) vv.clf() fig.position = 0, 22, 1366, 706 a1 = vv.subplot(111) a1.daspect = 1, 1, -1 renderStyle = 'mip' t1 = vv.volshow(vol1, clim=(0, 3000), renderStyle=renderStyle) # iso or mip if renderStyle == 'iso': t1.isoThreshold = 300 t1.colormap = colormap a1 = vv.volshow2(vol1, clim=(-500, 500), renderStyle=renderStyle) vv.xlabel('x'), vv.ylabel('y'), vv.zlabel('z') vv.title('One volume at 10\% procent of cardiac cycle') if visdynamic: from lspeas.utils.vis import showVolPhases showVol = 'mip' t = showVolPhases(basedir, vols2, showVol=showVol, mipIsocolor=True, isoTh=310, clim=(60, 3000), slider=True) return vols
grid1 = fromField(im[:, :, 0], spacing) grid2 = fromField(im[:, :, 1], spacing) grid3 = fromField(im[:, :, 2], spacing) # Obtain interpolated image imi = np.zeros_like(im) imi[:, :, 0] = grid1.get_field() imi[:, :, 1] = grid2.get_field() imi[:, :, 2] = grid3.get_field() ims.append(imi) imsd.append(abs(imi - im)) diff = abs(ims[0] - ims[1]) # Show vv.figure(1) vv.clf() #vv.subplot(221); vv.imshow(im) for i in range(2): vv.subplot(2, 2, i + 1) vv.imshow(ims[i]) vv.title('Multiscale' if i == 0 else 'Single scale') vv.subplot(2, 2, i + 3) vv.imshow(imsd[i]) for i in range(4): a = vv.subplot(2, 2, i + 1) t = a.FindObjects(vv.Texture2D) t[0].SetClim(0, 255)