Parcourir la source

Making run segmentation for non-divided files

Andrej Studen/Merlin il y a 3 ans
Parent
commit
cc26fefd7c
1 fichiers modifiés avec 10 ajouts et 111 suppressions
  1. 10 111
      pythonScripts/runSegmentation.py

+ 10 - 111
pythonScripts/runSegmentation.py

@@ -45,11 +45,6 @@ def valueSubstitution(pars,val):
 
     return path
 
-def getCroppedImagePath(tempFile,crop):
-    p=pathlib.Path(tempFile)
-    sfx=''.join(p.suffixes)
-    return re.sub(sfx,crop+sfx,str(p))
-
 def getSuffix(tempFile):
     p=pathlib.Path(tempFile)
     return ''.join(p.suffixes)
@@ -78,28 +73,6 @@ def normalizeCT(ctFile,maskFile):
     im1.SetDirection(im.GetDirection())
     SimpleITK.WriteImage(im1,ctFile)
 
-def cropImage(tempFile,crop, cropData):
-
-    im=SimpleITK.ReadImage(tempFile)
-    sz=im.GetSize()
-    ax=int(cropData['axis'])
-    rng=[float(v) for v in cropData['range']]
-    #update cropData['n']
-    if cropData['n']=="NONE":
-        cropData['n']=sz[ax]
-    if not sz[ax]==cropData['n']:
-        print('Size mismatch {}:{}'.format(sz[ax],cropData['n']))
-    n=sz[ax]
-    ii=[int(x*n) for x in rng]
-    slc=[slice(None) for v in sz]
-    slc[ax]=slice(ii[0],ii[1])
-    im1=im[slc]
-    #im1=im.take(indices=range(i1,i2),axis=cropData['axis'])
-    SimpleITK.WriteImage(im1,getCroppedImagePath(tempFile,crop))
-    print("Written {}".format(getCroppedImagePath(tempFile,crop)))
-
-
-
 def runDeepMedic(setup,pars):
     args=[]
     args.append(os.path.join(setup['paths']['deepMedicVE'],'bin','python'))
@@ -113,37 +86,15 @@ def runDeepMedic(setup,pars):
     print(args) 
     print(subprocess.run(args,check=True,stdout=subprocess.PIPE).stdout)
 
-def getSegmentationFile(pars,crop):
+def getSegmentationFile(pars):
     #this is how deep medic stores files
     return getSegmImagePath(\
-            getCroppedImagePath(\
             os.path.join(pars['tempBase'],'output','predictions','currentSession','predictions',\
-                pars['images']['images']['segmentations']['tempFile']),crop)
+            pars['images']['images']['segmentations']['tempFile'])
             )
 
-def getWeight(x,w):
-    for r in w:
-        fw=[float(v) for v in r['range']]
-        if x>fw[1]:
-            continue
-        if x<fw[0]:
-            continue
-        n=float(r['n'])
-        if not 'k' in r:
-            return n 
-
-        k=float(r['k'])
-        return k*x+n
-    return 0
-
 def runSegmentation(fb,row,pars,setup):
     
-    if False:
-        images=pars['images']['images']
-        outImg=mergeSegmentations(pars)
-        segFile=os.path.join(pars['tempBase'],images['segmentations']['tempFile'])
-        SimpleITK.WriteImage(outImg,segFile)
-        return segFile
      
     #download to temp file (could be a fixed name)
     project=pars['project']
@@ -152,77 +103,25 @@ def runSegmentation(fb,row,pars,setup):
     baseDir=fb.formatPathURL(project,pars['imageDir']+'/'+\
         getPatientLabel(row,participantField)+'/'+\
         getVisitLabel(row))
-    cropData=pars['images']['crop']
-    #reset n
-    for crop in cropData:
-        cropData[crop]['n']="NONE"
     
     #download 
     for im in images:
         tmpFile=images[im]['tempFile']
         if 'queryField' in images[im]:
             fb.readFileToFile(baseDir+'/'+row[images[im]['queryField']],tmpFile)
+   
     #normalize 
     normalizeCT(images['CT']['tempFile'],images['patientmask']['tempFile'])
 
-    #crop and store file names
-    for im in images:
-        tmpFile=images[im]['tempFile']
-            
-        with open(images[im]['fileList'],'w') as f:
-            for crop in cropData:
-                print('n={}'.format(cropData[crop]['n']))
-                if os.path.isfile(tmpFile):
-                    cropImage(tmpFile,crop,cropData[crop])
-                print('n={}'.format(cropData[crop]['n']))
-                f.write(getCroppedImagePath(tmpFile,crop)+'\n')
-
-    #normalize crops
-    for crop in cropData:
-        normalizeCT(getCroppedImagePath(images['CT']['tempFile'],crop),
-                getCroppedImagePath(images['patientmask']['tempFile'],crop))
-    
-    #run deep medic
-    runDeepMedic(setup,pars)
+    #update templates to know which files to process
 
-    #merge segmentations
-    outImg=mergeSegmentations(pars)
-    segFile=os.path.join(pars['tempBase'],images['segmentations']['tempFile'])
-    SimpleITK.WriteImage(outImg,segFile)
-    return segFile
-        #
 
-def mergeSegmentations(pars):
+    #run deep medic
+    #runDeepMedic(setup,pars)
     
-    cropData=pars['images']['crop']
-    start=True
-    for c in cropData:
-        segFile=getSegmentationFile(pars,c)
-        si=SimpleITK.ReadImage(segFile)
-        rng=[float(v) for v in cropData[c]['range']]
-        n=cropData[c]['n']
-        print(n)
-        img=SimpleITK.ConstantPad(si,[0,0,int(rng[0]*n)],[0,0,n-int(rng[1]*n)],-1)
-        print(img.GetSize())
-        ni=SimpleITK.GetArrayFromImage(img)
-        print(ni.shape)
-        w1=numpy.zeros(ni.shape)
-        aw=[getWeight((x+0.5)/n,cropData[c]['w']) for x in numpy.arange(n)]
-        for k in numpy.arange(len(aw)):
-            w1[k,:,:]=aw[k]
-        if start:
-            w0=w1
-            imgTmpl=img
-            nout=ni
-            start=False
-            continue
-        nout[w1>w0]=ni[w1>w0]
-        w0[w1>w0]=w1[w1>w0]
-    iout=SimpleITK.GetImageFromArray(nout)
-    iout.SetDirection(img.GetDirection())
-    iout.SetOrigin(img.GetOrigin())
-    iout.SetSpacing(img.GetSpacing())
-    return iout
+    #segFile=os.path.join(pars['tempBase'],images['segmentations']['tempFile'])
+    #SimpleITK.WriteImage(outImg,segFile)
+    return segFile
 
         
 def main(parameterFile):
@@ -301,7 +200,7 @@ def main(parameterFile):
             #copy file to file
             #normally I would update the targetQuery, but it contains previously set images
             #copy to labkey
-            fb.writeFileToFile(segFile,outFile)
+            #fb.writeFileToFile(segFile,outFile)