Attachment 'LatestMeshMorphing.py'

Download

   1 from lxml import etree as et
   2 from math import sin, cos
   3 import numpy as np
   4 import pygem as pg
   5 import os
   6 import re
   7 from stl import mesh as stl
   8 from string import whitespace
   9 import subprocess
  10 import sys
  11 from tvtk.api import tvtk
  12 from tvtk.api import colors
  13 
  14 sys.path.append('/home/landisb/PycharmProjects/PythonScripts/Project')
  15 
  16 import Utility_tvtk
  17 import ReadSubjectXml		# this only works if sys.path append is right
  18 
  19 
  20 limb = 'Upper_Arm'
  21 
  22 probeWidth = 22.5	# width of ultrasound probe in mm
  23 lengthOutput = False
  24 clickHighlight = False
  25 
  26 def CreateNestedDictionary():
  27 	"""Create a nested dictionary structure for the ultrasound data
  28 		this iterates "nicely" for these purposes as
  29 		for place, slice in nestedDict.items():
  30 			for orient, strata in slice.items():
  31 				for layer, point in strata.items():"""
  32 	from copy import deepcopy
  33 	orient = {	'skin'  : np.zeros(3),
  34 				'fat'   : np.zeros(3),
  35 				'muscle': np.zeros(3),
  36 				'bone'  : np.zeros(3)	}
  37 	place = {	'Anterior' : deepcopy(orient),
  38 				'Posterior': deepcopy(orient),
  39 				'Medial'   : deepcopy(orient),
  40 				'Lateral'  : deepcopy(orient)	}
  41 	nestedDict={'Proximal' : deepcopy(place),
  42 				'Central'  : deepcopy(place),
  43 				'Distal'   : deepcopy(place)	}
  44 	return nestedDict
  45 def dist(p1, p2):
  46 	distance = ( (p1[0]-p2[0])**2 + (p1[1]-p2[1])**2 + (p1[2]-p2[2])** 2 )**0.5
  47 	return distance
  48 def planeFit(points):
  49 	"""
  50 	p, n = planeFit(points)
  51 
  52 	Given an array, points, of shape (d,...)
  53 	representing points in d-dimensional space,
  54 	fit an d-dimensional plane to the points.
  55 	Return a point, p, on the plane (the point-cloud centroid),
  56 	and the normal, n.
  57 	"""
  58 	from numpy.linalg import svd
  59 	points = np.reshape(points, (np.shape(points)[0], -1)) # Collapse trialing dimensions
  60 	assert points.shape[0] <= points.shape[1], "There are only {} points in {} dimensions.".format(points.shape[1], points.shape[0])
  61 	ctr = points.mean(axis=1)
  62 	x = points - ctr[:,np.newaxis]
  63 	M = np.dot(x, x.T) # Could also use np.cov(x) here.
  64 	return ctr, svd(M)[0][:,-1]
  65 def ReadAndApplyUltrasoundThickness(limbSegment, file, probePoints, probeDirections, reverse=False):
  66 	"""Read the xml to find thickness
  67 		assign thickness to probePoints"""
  68 	directory = os.path.dirname(file)
  69 	doc = et.parse(file)
  70 	root = doc.getroot()
  71 	bodyPart = root.find(limbSegment.replace('_', ''))
  72 	for loc in list(bodyPart):
  73 		place, orient = re.findall('[A-Z][a-z]*', loc.tag)  # Split on capitalization
  74 		thicknessFile = loc.get('Anatomical')
  75 		subDoc = et.parse(os.path.join(directory, thicknessFile))
  76 		subRoot = subDoc.getroot()
  77 		subject = subRoot.find("Subject").find("Source")
  78 		Thickness = {}
  79 		for frame in list(subject):
  80 			readings = frame.find('Thickness')
  81 			for value in list(readings):
  82 				try:				Thickness[value.tag].append(float(value.text))
  83 				except KeyError:	Thickness[value.tag] = [float(value.text)]
  84 		for t, v in Thickness.iteritems():
  85 			Thickness[t] = sum(v) / len(v)
  86 		#
  87 		r = probeDirections[place][orient][0]  # roll
  88 		p = probeDirections[place][orient][1]  # pitch
  89 		y = probeDirections[place][orient][2]  # yaw
  90 		transformMatrix = np.array(	[[ cos(p)*cos(y), sin(r)*sin(p)*cos(y)-cos(r)*sin(y), cos(r)*sin(p)*cos(y)+sin(r)*sin(y)],
  91 			 						 [ cos(p)*sin(y), sin(r)*sin(p)*sin(y)+cos(r)*cos(y), cos(r)*sin(p)*sin(y)-sin(r)*cos(y)],
  92 			 						 [-sin(p),		  sin(r)*cos(p),					  cos(r)*cos(p)						]	])
  93 		if reverse:	# uses thickness to move outward from bone
  94 			dirVector = np.dot(transformMatrix, [0,0,-1])	# ultrasound probe points in -Z dir
  95 			probePoints[place][orient]['muscle']= probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'])
  96 			probePoints[place][orient]['fat']   = probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'] + Thickness['Fat'])
  97 			probePoints[place][orient]['skin']  = probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'] + Thickness['Fat'] + Thickness['Skin'])
  98 		else:	# Skin towards bone
  99 			dirVector = np.dot(transformMatrix, [0,0,1])	# ultrasound probe points in +Z dir
 100 			probePoints[place][orient]['fat']   = probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'])
 101 			probePoints[place][orient]['muscle']= probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'] + Thickness['Fat'])
 102 			probePoints[place][orient]['bone']  = probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'] + Thickness['Fat'] + Thickness['Muscle'])
 103 
 104 def NEW_ReadAndApplyUltrasoundThickness(limbSegment, file, probePoints, probeDirections, reverse=False):
 105 	"""Read the xml to find thickness
 106 		assign thickness to probePoints"""
 107 	directory = os.path.dirname(file)
 108 	doc = et.parse(file)
 109 	root = doc.getroot()
 110 	bodyPart = root.find(limbSegment.replace('_', ''))
 111 	for loc in list(bodyPart):
 112 		place, orient = re.findall('[A-Z][a-z]*', loc.tag)  # Split tag on capitalization
 113 		thicknessFile = loc.get('Anatomical')
 114 		subDoc = et.parse(os.path.join(directory, thicknessFile))
 115 		subRoot = subDoc.getroot()
 116 		subject = subRoot.find("Subject").find("Source")
 117 		Thickness = {}
 118 		for frame in list(subject):
 119 			readings = frame.find('Thickness')
 120 			for value in list(readings):
 121 				try:				Thickness[value.tag].append(float(value.text))
 122 				except KeyError:	Thickness[value.tag] = [float(value.text)]
 123 		for t, v in Thickness.iteritems():
 124 			Thickness[t] = sum(v) / len(v)
 125 		#
 126 		r = probeDirections[place][orient][0]  # roll
 127 		p = probeDirections[place][orient][1]  # pitch
 128 		y = probeDirections[place][orient][2]  # yaw
 129 		transformMatrix = np.array(	[[ cos(p)*cos(y), sin(r)*sin(p)*cos(y)-cos(r)*sin(y), cos(r)*sin(p)*cos(y)+sin(r)*sin(y)],
 130 			 					 [ cos(p)*sin(y), sin(r)*sin(p)*sin(y)+cos(r)*cos(y), cos(r)*sin(p)*sin(y)-sin(r)*cos(y)],
 131 			 					 [-sin(p),		  sin(r)*cos(p),					  cos(r)*cos(p)						]	])
 132 		if reverse:	# uses thickness to move outward from bone
 133 			dirVector = np.dot(transformMatrix, [0,0,-1])	# ultrasound probe points in -Z dir
 134 			probePoints[place][orient]['muscle']= probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'])
 135 			probePoints[place][orient]['fat']   = probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'] + Thickness['Fat'])
 136 			probePoints[place][orient]['skin']  = probePoints[place][orient]['bone'] + dirVector*(Thickness['Muscle'] + Thickness['Fat'] + Thickness['Skin'])
 137 		else:	# Skin towards bone
 138 			dirVector = np.dot(transformMatrix, [0,0,1])	# ultrasound probe points in +Z dir
 139 			probePoints[place][orient]['fat']   = probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'])
 140 			probePoints[place][orient]['muscle']= probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'] + Thickness['Fat'])
 141 			probePoints[place][orient]['bone']  = probePoints[place][orient]['skin'] + dirVector*(Thickness['Skin'] + Thickness['Fat'] + Thickness['Muscle'])
 142 
 143 def ReadInVitroPositions(limbSegment, file):
 144 	"""Read the xml to find the in vitro ultrasound positions"""
 145 	basePoints = CreateNestedDictionary()
 146 	baseDirections = CreateNestedDictionary()
 147 	doc = et.parse(file)
 148 	root = doc.getroot()
 149 	bodyPart = root.find(limbSegment.replace('_',''))
 150 	for loc in list(bodyPart):
 151 		place = loc.tag
 152 		place, orient = re.findall('[A-Z][a-z]*', place)	# Split on capitalization
 153 		pos = loc.find("Anatomical").find("USPosition")
 154 		x = float( pos.find("x").get('value') ) * 1000
 155 		y = float( pos.find("y").get('value') ) * 1000
 156 		z = float( pos.find("z").get('value') ) * 1000
 157 		roll = float( pos.find("roll" ).get('value') )
 158 		pitch= float( pos.find("pitch").get('value') )
 159 		yaw  = float( pos.find("yaw"  ).get('value') )
 160 		basePoints[place][orient]['skin'] = [x, y, z]
 161 		baseDirections[place][orient] = [roll, pitch, yaw]
 162 	return basePoints, baseDirections
 163 def WritePygemParameterFile(pygemParamFile, controlPoints, adjustedPoints):
 164 	rbfTemplate = """[Radial Basis Functions]
 165 basis function: thin_plate_spline
 166 radius: 10
 167 [Control points]
 168 original control points:{}
 169 deformed control points:{}"""
 170 	original = str(controlPoints).replace('[', '').replace(']', '').replace(whitespace, '\t')
 171 	morphed = str(adjustedPoints).replace('[', '').replace(']', '').replace(whitespace, '\t')
 172 	#
 173 	pygemParams = open(pygemParamFile, 'w')
 174 	pygemParams.write(rbfTemplate.format(original, morphed))
 175 	pygemParams.close()
 176 
 177 # Locations of all the files that will be used
 178 if   'Leg' in limb:
 179 	meshes = {	'bone'  : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/Segmentation/bone.stl',
 180 				'fat'   : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/Segmentation/fat.stl',
 181 				'muscle': '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/Segmentation/muscle.stl',
 182 				'skin'  : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/Segmentation/skin.stl'}
 183 	#
 184 	inVitroPositionsFile = '/home/landisb/PycharmProjects/Data/Morphing/FALSE_CADAVER_DATA/FALSE_CADAVER_UL_US_CT.xml'
 185 	# inVitroPositionsFile = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/CMULTIS002-2_UL_US_CT.xml'
 186 	#
 187 	cadaverFile = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/Configuration/CMULTIS002-2.xml'
 188 	subjectFile = '/home/landisb/PycharmProjects/Data/Morphing/MULTIS008-1/Configuration/MULTIS008-1.xml'
 189 	#
 190 	cadaverUltrasound = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-2/CMULTIS002-2_TA_inclusion.xml'
 191 	# cadaverUltrasound = '/home/landisb/PycharmProjects/Data/Morphing/FALSE_CADAVER_DATA/FALSE_TA_inclusion.xml'
 192 	subjectUltrasound = '/home/landisb/PycharmProjects/Data/Morphing/MULTIS008-1/MULTIS008-1_TA_inclusion.xml'
 193 elif 'Arm' in limb:
 194 	meshes = {	'bone'  : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/Segmentation/bone.stl',
 195 				'fat'   : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/Segmentation/fat.stl',
 196 				'muscle': '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/Segmentation/muscle.stl',
 197 				'skin'  : '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/Segmentation/skin.stl'}
 198 	#
 199 	inVitroPositionsFile = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/CMULTIS002-3_UA_US_CT.xml'
 200 	#
 201 	cadaverFile = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/Configuration/CMULTIS002-3.xml'
 202 	subjectFile = '/home/landisb/PycharmProjects/Data/Morphing/MULTIS008-1/Configuration/MULTIS008-1.xml'
 203 	#
 204 	cadaverUltrasound = '/home/landisb/PycharmProjects/Data/Morphing/CMULTIS002-3/TissueThickness/UltrasoundManual/CMULTIS002-3_TA_inclusion.xml'
 205 	subjectUltrasound = '/home/landisb/PycharmProjects/Data/Morphing/MULTIS008-1/MULTIS008-1_TA_inclusion.xml'
 206 else:	print 'limb value {} is unexpected.'.format(limb)
 207 
 208 # First get probe positions from inVitro, ie cadaver test, model is based off this
 209 probePoints, probeDirections = ReadInVitroPositions(limb, inVitroPositionsFile)
 210 
 211 # Read ultrasound thicknesses and apply them to the probePositions
 212 NEW_ReadAndApplyUltrasoundThickness(limb, cadaverUltrasound, probePoints, probeDirections)
 213 
 214 # Read subject file xml to find experimentally measured sizes
 215 cadaverMeasurements = ReadSubjectXml.GetNewData(cadaverFile)
 216 subjectMeasurements = ReadSubjectXml.GetData(subjectFile)
 217 
 218 
 219 # Find limb normal
 220 normals = {}
 221 for place, slice in probePoints.items():
 222 	pointArray = np.array(  [point for strata in slice.values() for point in strata.values()]  )
 223 	center, normal = planeFit(pointArray.T)				# First calculate the origin and normal
 224 	normals[place] = normal
 225 norm = sum( normals.values() )/len(normals)
 226 
 227 # Assign projected probe BONE positions
 228 projectedPoints = CreateNestedDictionary()	# probe points in morphed positions
 229 for place, slice in probePoints.items():
 230 	landmark = 'landmarkto{}Circumference'.format(place)
 231 	central = 'landmarktoCentralCircumference'
 232 	morphedLength  = subjectMeasurements[limb][landmark] - subjectMeasurements[limb][central]
 233 	originalLength = cadaverMeasurements[limb][landmark] - cadaverMeasurements[limb][central]
 234 	diff = (morphedLength-originalLength)*10		# to put it in mm not cm
 235 	for orient, strata in slice.items():
 236 		for layer, point in strata.items():
 237 			if layer is 'bone':
 238 				projectedPoints[place][orient][layer] = point + norm*diff
 239 
 240 # Read subject ultrasound thicknesses and apply them outward from the bone to projectedPositions
 241 ReadAndApplyUltrasoundThickness(limb, subjectUltrasound, projectedPoints, probeDirections, reverse=True)
 242 
 243 # Turn dictionaries of points in numpy arrays for use with pygem
 244 controlArray = np.array( [point for slice in probePoints.values()     for strata in slice.values() for point in strata.values()] )
 245 morphedArray = np.array( [point for slice in projectedPoints.values() for strata in slice.values() for point in strata.values()] )
 246 
 247 # # Morph meses with subprocees to speed things up.
 248 # print 'Morphing...',
 249 # WritePygemParameterFile('morphing.dat', controlArray,morphedArray)
 250 # processes = [subprocess.Popen(['python', 'RunPygem.py', mesh, 'morphing.dat']) for layer, mesh in meshes.items()]
 251 # print 'this takes a while...',
 252 # for proc in processes:	proc.wait()
 253 # print 'finished.'
 254 
 255 # Draw it all to the screen
 256 # Some containers to make drawing easier
 257 planeColors = 	{'Proximal':colors.pink, 'Central':colors.green_pale, 'Distal':colors.cyan}
 258 inVivo_Colors = {'Proximal':colors.red, 'Central':colors.green_dark, 'Distal':colors.blue}
 259 legColors = {'skin':colors.sandy_brown, 'fat':colors.lemon_chiffon, 'muscle':colors.salmon, 'bone':colors.blanched_almond}
 260 stlActors = []
 261 pointActors = []
 262 cutActors = []
 263 planeActors = []
 264 arrowActors = []
 265 
 266 
 267 # Create graphics stuff
 268 ren = tvtk.Renderer(background=colors.white)
 269 renWin = tvtk.RenderWindow(size=(800,800))
 270 renWin.add_renderer(ren)
 271 if clickHighlight:
 272 		style = Utility_tvtk.MouseHighLightActor(ren)
 273 		iren = tvtk.RenderWindowInteractor(render_window=renWin, interactor_style=style.style)
 274 else:	iren = tvtk.RenderWindowInteractor(render_window=renWin)
 275 
 276 # Get actors for stls
 277 for layer, mesh in meshes.iteritems():
 278 	if   layer is 'fat':	op = 0
 279 	elif layer is 'skin':	op = 0.0
 280 	elif layer is 'bone':	op = 0.8
 281 	elif layer is 'muscle':	op = 0.0
 282 	stlActors.append(Utility_tvtk.MakeStl(mesh, legColors[layer], opacity=op))
 283 	# stlActors.append(  Utility_tvtk.MakeStl(mesh, colors.cyan, opacity=op)  )
 284 	# newMesh = mesh.replace('.', '_morphed.')
 285 	# stlActors.append(  Utility_tvtk.MakeStl(newMesh, colors.sandy_brown, opacity=op)  )
 286 
 287 
 288 # Get actors for probePoints
 289 print 'In Vitro (light colors):'
 290 for place, slice in probePoints.iteritems():
 291 	post = slice.pop('Posterior')		# remove posterior points
 292 	pointArray = np.array([point for strata in slice.values() for point in strata.values()])
 293 	pointActor = Utility_tvtk.MakePoints(pointArray, planeColors[place], size=5)
 294 	pointActors.append(pointActor)
 295 	slice['Posterior'] = post			# re-add posterior points
 296 	#
 297 	for orient, strata in slice.items():	arrowActors.append(  Utility_tvtk.MakeArrow(probePoints[place][orient]['skin'], probePoints[place][orient]['bone'], planeColors[place], opacity=0.5)  )
 298 	#
 299 	center, normal = planeFit(pointArray.T)					# First calculate the origin and normal
 300 	# size = 5 * dist(center, pointArray[0])
 301 	# planeActors.append(Utility_tvtk.DrawPlane(center, normal, size, planeColors[place]))
 302 	if 'Leg' in limb:
 303 		if   place is 'Proximal':	centerAdjustment = center - probeWidth * normal
 304 		elif place is 'Central':	centerAdjustment = center  # no adjustment
 305 		elif place is 'Distal':		centerAdjustment = center + probeWidth * normal
 306 	elif 'Arm' in limb:
 307 		if   place is 'Proximal':	centerAdjustment = center+probeWidth*normal
 308 		elif place is 'Central':	centerAdjustment = center		# no adjustment
 309 		elif place is 'Distal':		centerAdjustment = center-probeWidth*normal
 310 	else:	centerAdjustment = center
 311 	centerAdjustment = center
 312 	plane = tvtk.Plane(origin=centerAdjustment,normal=normal)  # Create the plane as a function, that will be used to cut the stl.
 313 	#
 314 	cut, circum = Utility_tvtk.MakeStlCut(meshes['skin'], plane, planeColors[place])
 315 	cutActors.append(cut)
 316 	# showCut, dontcare = Utility_tvtk.MakeStlCut(meshes['fat'], plane, colors.lemon_chiffon)
 317 	# cutActors.append(showCut)
 318 	# showCut, dontcare = Utility_tvtk.MakeStlCut(meshes['muscle'], plane, colors.pink)
 319 	# cutActors.append(showCut)
 320 	showCut, dontcare = Utility_tvtk.MakeStlCut(meshes['bone'], plane, colors.yellow)
 321 	cutActors.append(showCut)
 322 	measured = cadaverMeasurements[limb][place+'Circumference']*10
 323 	percent = (measured-circum)/measured*100
 324 	print '	{:8s} circumference (mm)	measured {:3.0f} calculated {:6.3f}	error {: 4.2f}.'.format(place, measured, circum, percent)
 325 	#
 326 	# Find hip and knee mesh locations
 327 	if lengthOutput and place is 'Proximal':
 328 		# Points at the hip and knee
 329 		landmark = 'landmarktoCentralCircumference'
 330 		# hip = probePoints['Central']['Lateral']['skin'] - normals['Proximal']*cadaverMeasurements[limb][landmark]*10
 331 		knee= probePoints['Central']['Lateral']['skin'] + normals['Distal']*(cadaverMeasurements[limb]['Length']-cadaverMeasurements[limb][landmark])*10
 332 		hip = probePoints['Central']['Lateral']['skin'] - norm*cadaverMeasurements[limb][landmark]*10
 333 		# knee= probePoints['Central']['Lateral']['skin'] + norm*(cadaverMeasurements[limb]['Length']-cadaverMeasurements[limb][landmark])*10
 334 		#
 335 		stlMesh = stl.Mesh.from_file(meshes['skin'])  # read stl file
 336 		stlPoints = stlMesh.vectors.reshape(-1,3)
 337 		#
 338 		distArray = np.linalg.norm(stlPoints-hip, axis=1)
 339 		hipIndex = np.argmin(distArray)
 340 		#
 341 		distArray = np.linalg.norm(stlPoints-knee, axis=1)
 342 		kneeIndex = np.argmin(distArray)
 343 		#
 344 		length = dist(stlPoints[hipIndex], stlPoints[kneeIndex])
 345 		measured = cadaverMeasurements[limb]['Length']*10
 346 		estimated = dist(hip, knee)
 347 		percent = (measured-length)/measured*100
 348 		print '	Length (mm)	 				measured {:3.0f} calculated {:6.3f}	error {: 4.2f}'.format(measured, length, percent)
 349 		#
 350 		# Highlight hip and knee points
 351 		pointActor = Utility_tvtk.MakePoints(stlPoints[hipIndex].reshape(1, 3), planeColors['Proximal'], size=10)
 352 		pointActors.append(pointActor)
 353 		pointActor = Utility_tvtk.MakePoints(stlPoints[kneeIndex].reshape(1, 3), planeColors['Distal'], size=10)
 354 		pointActors.append(pointActor)
 355 
 356 # # Get actors for projectedPoints
 357 # print 'In Vivo (dark colors):'
 358 # for place, slice in projectedPoints.iteritems():
 359 # 	pointArray = np.array([point for strata in slice.values() for point in strata.values()])
 360 # 	pointActor = Utility_tvtk.MakePoints(pointArray, inVivo_Colors[place], size=5)
 361 # 	pointActors.append(pointActor)
 362 # 	#
 363 # 	center, normal = planeFit(pointArray.T)
 364 # 	if 'Leg' in limb:
 365 # 		if place is 'Proximal':		centerAdjustment = center - probeWidth * normal
 366 # 		elif place is 'Central':	centerAdjustment = center  # no adjustment
 367 # 		elif place is 'Distal':		centerAdjustment = center + probeWidth * normal
 368 # 	elif 'Arm' in limb:
 369 # 		if   place is 'Proximal':	centerAdjustment = center+probeWidth*normal
 370 # 		elif place is 'Central':	centerAdjustment = center		# no adjustment
 371 # 		elif place is 'Distal':		centerAdjustment = center-probeWidth*normal
 372 # 	else:	centerAdjustment = center
 373 # 	centerAdjustment = center
 374 # 	plane = tvtk.Plane(origin=centerAdjustment,normal=normal)  # Create the plane as a function, that will be used to cut the stl.
 375 # 	#
 376 # 	newMesh = meshes['skin'].replace('.', '_morphed.')
 377 # 	cut,  circum = Utility_tvtk.MakeStlCut(newMesh, plane, inVivo_Colors[place])
 378 # 	cutActors.append(cut)
 379 # 	measured = subjectMeasurements[limb][place+'Circumference']*10
 380 # 	percent = (measured-circum)/measured*100
 381 # 	print '	{:8s} circumference (mm)	measured {:3.0f} calculated {:6.3f}	error {: 4.2f}.'.format(place, measured, circum, percent)
 382 # 	#
 383 # 	# Find morphed hip and knee mesh locations
 384 # 	if lengthOutput and place is 'Proximal':		# proximal so it prints after all 3 circumferences
 385 # 		newMesh = meshes['skin'].replace('.', '_morphed.')
 386 # 		stlMesh = stl.Mesh.from_file(newMesh)  # read stl file
 387 # 		newPoints = stlMesh.vectors.reshape(-1,3)
 388 # 		#
 389 # 		length = dist(newPoints[hipIndex], newPoints[kneeIndex])
 390 # 		measured = subjectMeasurements[limb]['Length']*10
 391 # 		percent = (measured-length)/measured*100
 392 # 		print '	Length (mm)	 				measured {:3.0f} calculated {:6.3f}	error {: 4.2f}'.format(measured, length, percent)
 393 # 		#
 394 # 		# Highlight morphed hip and knee
 395 # 		pointActor = Utility_tvtk.MakePoints(newPoints[hipIndex].reshape(1,3), inVivo_Colors['Proximal'], size=10)
 396 # 		pointActors.append(pointActor)
 397 # 		pointActor = Utility_tvtk.MakePoints(newPoints[kneeIndex].reshape(1,3), inVivo_Colors['Distal'], size=10)
 398 # 		pointActors.append(pointActor)
 399 
 400 # Add all the actors that have been made
 401 for stl in stlActors:		ren.add_actor(stl)
 402 for point in pointActors:	ren.add_actor(point)
 403 for plane in planeActors:	ren.add_actor(plane)
 404 for arrow in arrowActors:	ren.add_actor(arrow)
 405 for cut in cutActors:		ren.add_actor(cut)
 406 
 407 # Reset camera and viewing area
 408 ren.reset_camera()
 409 cam = ren.active_camera
 410 cam.azimuth(30)
 411 cam.elevation(30)
 412 cam.dolly(1.5)
 413 ren.reset_camera_clipping_range()
 414 
 415 iren.initialize()
 416 renWin.render()
 417 renWin.window_name=os.path.basename(__file__).replace('.py', '')
 418 iren.start()
 419 
 420 #
 421 # #
 422 # # #	print TVTK_Object.class_editable_traits()
 423 # #
 424 #

Attached Files

To refer to attachments on a page, use attachment:filename, as shown below in the list of files. Do NOT use the URL of the [get] link, since this is subject to change and can break easily.
  • [get | view] (2016-09-16 15:12:44, 34.1 KB) [[attachment:Femur_Adjusted_Points.png]]
  • [get | view] (2016-09-16 15:12:04, 32.9 KB) [[attachment:Femur_Guide_Points.png]]
  • [get | view] (2017-04-11 20:32:58, 20.4 KB) [[attachment:LatestMeshMorphing.py]]
  • [get | view] (2016-09-16 15:13:03, 45.3 KB) [[attachment:Morphed_Femur.png]]
  • [get | view] (2017-06-05 14:43:15, 351.5 KB) [[attachment:Morphed_Leg.png]]
  • [get | view] (2020-02-21 22:17:48, 17.4 KB) [[attachment:MultisMeshMorphing.py]]
 All files | Selected Files: delete move to page copy to page

You are not allowed to attach a file to this page.