def loadmodel(basedir, ptcode, ctcode, cropname, modelname='modelavgreg'): """ Load stent model. An ssdf struct is returned. """ # Load fname = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, modelname) try: s = ssdf.load(os.path.join(basedir, ptcode, fname)) except FileNotFoundError: s = ssdf.load(os.path.join(basedir, fname)) # Turn into graph model from stentseg.stentdirect import stentgraph for key in dir(s): if key.startswith('model'): model = stentgraph.StentGraph() model.unpack(s[key]) s[key] = model # also unpack seeds if exist #-mind that also seeds need to be packed before save is possible again- elif key.startswith('seeds'): seeds = stentgraph.StentGraph() seeds.unpack(s[key]) s[key] = seeds elif key.startswith('landmark'): # landmark validation landmarks = stentgraph.StentGraph() landmarks.unpack(s[key]) s[key] = landmarks return s
def loadvol(basedir, ptcode=None, ctcode=None, cropname=None, what='phases', fname=None): """ Load volume data. An ssdf struct is returned. The volumes are made into Aarray's with their sampling and origin set. """ if fname is None: fname = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, what) try: s = ssdf.load(os.path.join(basedir, ptcode, fname)) except FileNotFoundError: s = ssdf.load(os.path.join(basedir, fname)) for key in dir(s): if key.startswith('vol'): s[key] = vv.Aarray(s[key], s.sampling, s.origin) elif key.startswith('deform'): fields = s[key] s[key] = [ vv.Aarray(field, s.sampling, s.origin) for field in fields ] # origin of volume is added as meta-data #[vv.Aarray(field, s.sampling, [0,0,0]) for field in fields] would use wrong deform-data when deforming return s
def __init__(self): # load font data path = getResourceDir() self.s = ssdf.load(os.path.join(path, 'fonts.ssdf')) # list of fonts self.fonts = {}
def __init__(self, fname=None): # Store filename self._fname = fname # Load if fname and os.path.exists(fname): self._db = ssdf.load(fname) else: self._db = ssdf.new() # Key of last added entry self._lastkey = ''
def load_volume(patnr): """ Gives back volume (pixels) and volume properties (sampling and origin) """ # tmp = r'C:\Users\Michel\Documents\BMT\Bacheloropdracht\data\croppedAvg7_pat%02i.ssdf' tmp = r'C:\almar\data\dicom\cropped\croppedReg_pat%02i_gravity.bsdf' s = ssdf.load(tmp % patnr) vol = Aarray(s.vol.astype(np.float32), s.sampling, s.origin) #Save sampling sampling = s.sampling origin = s.origin return vol, sampling, origin
def test_pack1(self): # Custom stent g = StentGraph(summary='dit is een stent!', lala=3) g.add_node((10, 20), foo=3) g.add_node((30, 40), foo=5) g.add_edge((1, 1), (2, 2), bar=10) g.add_edge((10, 20), (1, 1), bar=20) fname = '/home/almar/test.ssdf' ssdf.save(fname, g.pack()) g2 = StentGraph() g2.unpack(ssdf.load(fname)) #print(nx.is_isomorphic(g, g2)) assert nx.is_isomorphic(g, g2)
def makeLandmarkModelDynamic(basedir, ptcode, ctcode, cropname, what='landmarksavgreg', savedir=None): """ Make model dynamic with deforms from registration (and store/overwrite to disk) """ #todo: change in default and merge with branch landmarks? import pirt from stentseg.motion.dynamic import (incorporate_motion_nodes, incorporate_motion_edges) from visvis import ssdf import os if savedir is None: savedir = basedir # Load deforms s = loadvol(basedir, ptcode, ctcode, cropname, 'deforms') deformkeys = [] for key in dir(s): if key.startswith('deform'): deformkeys.append(key) deforms = [s[key] for key in deformkeys] deforms = [pirt.DeformationFieldBackward(*fields) for fields in deforms] paramsreg = s.params # Load model where landmarks were stored # s2 = loadmodel(savedir, ptcode, ctcode, cropname, what) fname = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, what) s2 = ssdf.load(os.path.join(savedir, fname)) # Turn into graph model model = stentgraph.StentGraph() model.unpack(s2[what]) # Combine ... incorporate_motion_nodes(model, deforms, s2.origin) incorporate_motion_edges(model, deforms, s2.origin) # Save back filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, what) s2.model = model.pack() s2.paramsreg = paramsreg ssdf.save(os.path.join(savedir, filename), s2) print('saved to disk to {}.'.format(os.path.join(savedir, filename)))
def test_pack2(self): # Auto generate import random n = 500 p = dict( (i, (random.gauss(0, 2), random.gauss(0, 2))) for i in range(n)) g_ = nx.random_geometric_graph(n, 0.1, dim=3, pos=p) g = StentGraph(summary='dit is een stent!', lala=3) g.add_nodes_from(g_.nodes_iter()) g.add_edges_from(g_.edges_iter()) fname = '/home/almar/test.ssdf' ssdf.save(fname, g.pack()) g2 = StentGraph() g2.unpack(ssdf.load(fname)) #print(nx.is_isomorphic(g, g2)) assert nx.is_isomorphic(g, g2)
def __init__(self): # Define settings file name self._fname = os.path.join(appdata_dir('visvis'), 'config.ssdf') # Init settings self._s = ssdf.new() # Load settings if we can if os.path.exists(self._fname): try: self._s = ssdf.load(self._fname) except Exception: pass # Update any missing settings to their defaults for key in dir(self): if key.startswith('_'): continue self._s[key] = getattr(self, key) # Save now so the config file contains all settings self._Save()
def saveaveraged(basedir, ptcode, ctcode, cropname, phases): """ Step C: Save average of a number of volumes (phases in cardiac cycle) Load ssdf containing all phases and save averaged volume as new ssdf """ filename = '%s_%s_%s_phases.ssdf' % (ptcode, ctcode, cropname) file_in = os.path.join(basedir, ptcode, filename) if not os.path.exists(file_in): raise RuntimeError('Could not find ssdf for given input %s' % ptcode, ctcode, cropname) s = ssdf.load(file_in) s_avg = ssdf.new() averaged = np.zeros(s.vol0.shape, np.float64) if phases[1] < phases[0]: phaserange = list(range(0, 100, 10)) for i in range(phases[1] + 10, phases[0], 10): phaserange.remove(i) else: phaserange = range(phases[0], phases[1] + 10, 10) for phase in phaserange: averaged += s['vol%i' % phase] s_avg['meta%i' % phase] = s['meta%i' % phase] averaged *= 1.0 / len(phaserange) averaged = averaged.astype('float32') s_avg.vol = averaged s_avg.sampling = s.sampling # z, y, x voxel size in mm s_avg.origin = s.origin s_avg.stenttype = s.stenttype s_avg.croprange = s.croprange s_avg.ctcode = s.ctcode s_avg.ptcode = s.ptcode avg = 'avg' + str(phases[0]) + str(phases[1]) filename = '%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, avg) file_out = os.path.join(basedir, ptcode, filename) ssdf.save(file_out, s_avg)
# Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import numpy as np import visvis as vv import sys import zlib import base64 # todo: parameterize; allow custum Gaussian blobs at specified positions. if False: # Get data (exported from Matlab) from visvis import ssdf db = ssdf.load('d:/almar/projects/peaks.ssdf') data = db.z.astype(np.float32) # Dump data = data.tostring() data = zlib.compress(data) text = base64.encodebytes(data) print(text) def peaks(): """ peaks() Returs a 2D map of z-values that represent an example landscape with Gaussian blobs.
# Copyright (C) 2012, Almar Klein # # Visvis is distributed under the terms of the (new) BSD License. # The full license can be found in 'license.txt'. import numpy as np import visvis as vv import zlib, base64 # todo: parameterize; allow custum Gaussian blobs at specified positions. if False: # Get data (exported from Matlab) from visvis import ssdf db = ssdf.load('d:/almar/projects/peaks.ssdf') data = db.z.astype(np.float32) # Dump data = data.tostring() data = zlib.compress(data) text = base64.encodestring(data) print(text) def peaks(): """ peaks() Returs a 2D map of z-values that represent an example landscape with Gaussian blobs. """
# Create volume (smooth a bit) if True: vol0 = vv.aVolume() vol = vol0.copy() * 0.5 vol[1:, :, :] += 0.3 * vol0[:-1, :, :] vol[:-1, :, :] += 0.3 * vol0[1:, :, :] vol[:, 1:, :] += 0.3 * vol0[:, :-1, :] vol[:, :-1, :] += 0.3 * vol0[:, 1:, :] vol[:, :, 1:] += 0.3 * vol0[:, :, :-1] vol[:, :, :-1] += 0.3 * vol0[:, :, 1:] else: # My personal test from visvis import ssdf 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
clim0 = (0,2500) isoTh = 250 targetdir2 = os.path.join(targetdir1, ptcode) s = loadvol(basedir2, ptcode, ctcode, cropname, what) nrs = [1,2,4,5,7,8,10,11,13,14,16,17,19,20,22,23,25,26] FIG1 = False ## Load all rings of the limb for i in nrs: ring = 'ringR%s' %(i) filename = '%s_%s_%s_%s_%s.ssdf' % (ptcode, ctcode, cropname, 'model'+what,ring) s["ringR" + str(i)] = ssdf.load(os.path.join(basedir1, filename)) ## Visualize centerlines rings s2 = loadmodel(targetdir2, ptcode, ctcode, cropname, modelname='stentseedsavgreg') pmodel = points_from_nodes_in_graph(s2.model) if FIG1 == True: f = vv.figure(1); vv.clf() f.position = 709.00, 30.00, 1203.00, 1008.00 a1 = vv.subplot(121) show_ctvolume(s.vol, None, showVol=showVol, clim=clim0, isoTh=isoTh, removeStent=False) label = pick3d(vv.gca(), s.vol) a1.axis.visible = showAxis a1.daspect = 1,1,-1 a2 = vv.subplot(122)
# Create volume (smooth a bit) if True: vol0 = vv.aVolume() vol = vol0.copy()*0.5 vol[1:,:,:] += 0.3 * vol0[:-1,:,:] vol[:-1,:,:] += 0.3 * vol0[1:,:,:] vol[:,1:,:] += 0.3 * vol0[:,:-1,:] vol[:,:-1,:] += 0.3 * vol0[:,1:,:] vol[:,:,1:] += 0.3 * vol0[:,:,:-1] vol[:,:,:-1] += 0.3 * vol0[:,:,1:] else: # My personal test from visvis import ssdf 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]