def applyTransformations(data): for d in data: success, transform = slicer.util.loadTransform(d['transform'], returnNode=True) success, preopLandmarks = slicer.util.loadMarkupsFiducialList( d['landmarks'], returnNode=True) ModuleLogicMixin.applyTransform(transform, preopLandmarks) print "saving to : %s" % os.path.dirname(d['landmarks']) ModuleLogicMixin.saveNodeData( preopLandmarks, os.path.dirname(d['landmarks']), FileExtension.FCSV, name="{}-PreopLandmarks-transformed".format(d['case']))
def runRegistrations(data, destination): caseNumber = data["caseNumber"] success, intraopVolume = slicer.util.loadVolume(data["Intraop"]["volume"], returnNode=True) intraopVolume.SetName("{}: IntraopVolume".format(caseNumber)) for segmentationType in ["Manual", "Automatic"]: success, preopVolume = slicer.util.loadVolume(data["Preop"]["volume"], returnNode=True) preopVolume.SetName("{}: PreopVolume".format(caseNumber)) success, preopLabel = slicer.util.loadLabelVolume( data["Preop"]["labels"][segmentationType], returnNode=True) preopLabel.SetName("{}: PreopManual-label".format(caseNumber)) success, intraopLabel = slicer.util.loadLabelVolume( data["Intraop"]["labels"][segmentationType], returnNode=True) intraopLabel.SetName("{}: IntraopManual-label".format(caseNumber)) if data["Preop"]["used_endorectal_coil"] is True: preopVolume = applyBiasCorrection(preopVolume, preopLabel) result = runRegistration(intraopVolume, intraopLabel, preopVolume, preopLabel) if result: for regType, transform in result.transforms.asDict().iteritems(): ModuleLogicMixin.saveNodeData(transform, destination, FileExtension.H5, name="{}-TRANSFORM-{}-{}".format( caseNumber, regType, segmentationType)) for regType, volume in result.volumes.asDict().iteritems(): if not regType in ['rigid', 'affine', 'bSpline']: continue ModuleLogicMixin.saveNodeData(volume, destination, FileExtension.NRRD, name="{}-VOLUME-{}-{}".format( caseNumber, regType, segmentationType))
def createSegmentations(data, outputDir): caseNumber = data["caseNumber"] for imageType in ["Preop", "Intraop"]: automaticLabelPath = data[imageType]["labels"]["Automatic"] if not os.path.exists(automaticLabelPath): logic = AutomaticSegmentationLogic() endorectalCoilUsed = "BWH_WITHOUT_ERC" if data[imageType][ "used_endorectal_coil"] is False else "BWH_WITH_ERC" success, volume = slicer.util.loadVolume(data[imageType]["volume"], returnNode=True) automaticLabel = logic.run(volume, domain=endorectalCoilUsed) labelName = "{}-{}Automatic-label".format(caseNumber, imageType) ModuleLogicMixin.saveNodeData(automaticLabel, outputDir, FileExtension.NRRD, name=labelName) else: print "Not running {} segmentation for case {} because label already exists".format( imageType, caseNumber)
def main(argv): try: parser = argparse.ArgumentParser( description="Slicetracker Transform Applicator") parser.add_argument( "-ld", "--landmark-root-directory", dest="landmarkRootDir", metavar="PATH", default="-", required=True, help= "Root directory that lists all cases holding information for landmarks" ) parser.add_argument( "-st", "--segmentation-type", dest="segmentationType", metavar="NAME", default="-", choices=['Manual', 'Automatic'], required=True, help="Expected transform name will be " "{casenumber}-TRANSFORM-{transformType}-{segmentationType}.h5") parser.add_argument( "-tt", "--transform-type", dest="transformType", metavar="NAME", default="-", choices=['rigid', 'affine', 'bSpline'], required=True, help= "%(choices). expected transform name: {casenumber}-TRANSFORM-{transformType}-{segmentationType}.h5" ) parser.add_argument( "-ft", "--fiducial-type", dest="fiducialType", metavar="NAME", default="-", choices=['Targets', 'Landmarks'], required=True, help='list servers, storage, or both (default: %(default)s)') args = parser.parse_args(argv) segmentationType = args.segmentationType transformType = args.transformType fiducialType = args.fiducialType for root, dirs, _ in os.walk(args.landmarkRootDir): for case in dirs: landmarks = os.path.join( root, case, "{}-Preop{}.fcsv".format(case, fiducialType)) transform = os.path.join( root, case, "{}-TRANSFORM-{}-{}.h5".format(case, transformType, segmentationType)) # check if exists and if is identity volume = os.path.join( root, case, "{}-VOLUME-{}-{}.nrrd".format(case, transformType, segmentationType)) if not os.path.exists(volume): logging.info( "Case {}: No valid {} transform found.Falling back to affine" .format(case, transformType)) # volume = os.path.join(root, case, "{}-VOLUME-affine-{}.nrrd".format(case, segmentationType)) transform = os.path.join( root, case, "{}-TRANSFORM-affine-{}.h5".format( case, segmentationType)) if all(os.path.exists(f) for f in [landmarks, transform]): success, landmarksNode = slicer.util.loadMarkupsFiducialList( landmarks, returnNode=True) success, transformNode = slicer.util.loadTransform( transform, returnNode=True) ModuleLogicMixin.applyTransform(transformNode, landmarksNode) fileName = "{}-Preop{}-transformed-{}-{}".format( case, fiducialType, transformType, segmentationType) print "saving to : {}/{}{}".format( os.path.dirname(landmarks), fileName, FileExtension.FCSV) ModuleLogicMixin.saveNodeData(landmarksNode, os.path.dirname(landmarks), FileExtension.FCSV, name=fileName) else: logging.warn( "Did not find landmarks/transforms for case %s" % case) except Exception, e: print e
def copyData(data, outputDir): logic = DeepInfer.DeepInferLogic() parameters = DeepInfer.ModelParameters() segmenter_json_file = os.path.join(DeepInfer.JSON_LOCAL_DIR, "ProstateNeedleFinder.json") with open(segmenter_json_file, "r") as fp: j = json.load(fp, object_pairs_hook=OrderedDict) iodict = parameters.create_iodict(j) dockerName, modelName, dataPath = parameters.create_model_info(j) csvData = [[ 'Case', 'SeriesNumber', 'TargetName', 'Pos', 'NeedleDistance', 'ErrorVector', 'Comment' ]] for case, caseData in data.iteritems(): if not caseData: continue outputCaseDir = os.path.join(outputDir, case) if not os.path.exists(outputCaseDir): ModuleLogicMixin.createDirectory(outputCaseDir) print "processing data of case %s" % case for data in caseData: seriesNumber = data["seriesNumber"] inputs = dict() temp = os.path.join(outputCaseDir, "{}-label.nrrd".format(seriesNumber)) if not os.path.exists(temp): copy(os.path.join(data["path"], data["label"]), temp) # success, inputs['InputProstateMask'] = slicer.util.loadLabelVolume(temp, returnNode=True) temp = os.path.join(outputCaseDir, "{}-volume.nrrd".format(seriesNumber)) if not os.path.exists(temp): copy(os.path.join(data["path"], data["volume"]), temp) # success, inputs['InputVolume'] = slicer.util.loadVolume(temp, returnNode=True) temp = os.path.join(outputCaseDir, "{}-targets.fcsv".format(seriesNumber)) if not os.path.exists(temp): copy(os.path.join(data["path"], data["targets"]), temp) success, targetNode = slicer.util.loadMarkupsFiducialList( temp, returnNode=True) temp = os.path.join(outputCaseDir, "{}-needle-label.nrrd".format(seriesNumber)) if not os.path.exists(temp): outputs = dict() outputs['OutputLabel'] = slicer.mrmlScene.AddNewNodeByClass( "vtkMRMLLabelMapVolumeNode") outputs[ 'OutputFiducialList'] = slicer.mrmlScene.AddNewNodeByClass( "vtkMRMLMarkupsFiducialNode") params = dict() params['InferenceType'] = 'Ensemble' logic.executeDocker(dockerName, modelName, dataPath, iodict, inputs, params) logic.updateOutput(iodict, outputs) ModuleLogicMixin.saveNodeData( outputs['OutputLabel'], outputCaseDir, FileExtension.NRRD, name="{}-needle-label".format(seriesNumber)) ModuleLogicMixin.saveNodeData( outputs['OutputFiducialList'], outputCaseDir, FileExtension.FCSV, name="{}-needle-tip".format(seriesNumber)) temp = os.path.join( outputCaseDir, "{}-needle-centerline.fcsv".format(seriesNumber)) if not os.path.exists(temp): centerLine = CenterLinePoints( os.path.join(outputCaseDir, "{}-needle-label.nrrd".format(seriesNumber))) points_ijk = centerLine.get_needle_points_ijk() points_ras = centerLine.convert_points_ijk_to_ras(points_ijk) centerLineNode = slicer.mrmlScene.AddNewNodeByClass( "vtkMRMLMarkupsFiducialNode") for point in points_ras: centerLineNode.AddFiducialFromArray(point) centerLineNode.SetLocked(True) ModuleLogicMixin.saveNodeData( centerLineNode, outputCaseDir, FileExtension.FCSV, name="{}-needle-centerline".format(seriesNumber)) success, centerLineNode = slicer.util.loadMarkupsFiducialList( temp, returnNode=True) if not centerLineNode.GetNumberOfFiducials(): csvData.append([ case, seriesNumber, "", "", "", "", "No centerline was found" ]) else: cmLogic = CurveMaker.CurveMakerLogic() cmLogic.DestinationNode = slicer.mrmlScene.CreateNodeByClass( "vtkMRMLModelNode") cmLogic.SourceNode = centerLineNode cmLogic.updateCurve() cmLogic.CurvePoly = vtk.vtkPolyData() cmLogic.enableAutomaticUpdate(1) for idx in range(targetNode.GetNumberOfFiducials()): targetName = targetNode.GetNthFiducialLabel(idx) if targetName.lower() in ["right", "left"]: continue pos = ModuleLogicMixin.getTargetPosition(targetNode, idx) (distance, minErrorVec) = cmLogic.distanceToPoint(pos, True) # print "{}: {} ({})".format(targetName, distance, minErrorVec) csvData.append([ case, seriesNumber, targetName, pos, distance, minErrorVec, "" ]) def cleanup(): slicer.mrmlScene.RemoveNode(cmLogic.DestinationNode) cleanup() return csvData