anonymizeImagesNIfTI.py 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. import os
  2. import json
  3. import re
  4. import subprocess
  5. import nibabel
  6. import shutil
  7. import sys
  8. shome=os.path.expanduser('~nixUser')
  9. sys.path.insert(1,shome+'/software/src/labkeyInterface')
  10. import labkeyInterface
  11. import labkeyDatabaseBrowser
  12. sys.path.insert(1,shome+'/software/src/orthancInterface')
  13. import orthancInterface
  14. import orthancFileBrowser
  15. sys.path.insert(1,shome+'/software/src/IPNUMM/dicomUtils')
  16. import loadDicom
  17. fhome=os.path.expanduser('~')
  18. fconfig=os.path.join(fhome,'.labkey','network.json')
  19. net=labkeyInterface.labkeyInterface()
  20. net.init(fconfig)
  21. db=labkeyDatabaseBrowser.labkeyDB(net)
  22. onet=orthancInterface.orthancInterface()
  23. onet.init(fconfig)
  24. ofb=orthancFileBrowser.orthancFileBrowser(onet)
  25. hi=0
  26. project='iPNUMMretro/Study'
  27. #project='Orthanc/Database'
  28. tempBase=os.path.join(fhome,'temp')
  29. #all images from database
  30. ds=db.selectRows(project,'study','Imaging',[])
  31. imageSelector=["CT","PETWB"];
  32. niftiBase='/data/nifti'
  33. labkeyBase='/data/labkey'
  34. projectNIfTIBase=os.path.join(labkeyBase,'files',project,'@files/nifti')
  35. i=0
  36. for row in ds["rows"]:
  37. for im in imageSelector:
  38. linkField=im+"1"
  39. print("Checking row[{}]={}".format(linkField,row[linkField]))
  40. if row[linkField]=="[NIFTI]":
  41. print("Skipping {}".format(im))
  42. continue
  43. seriesId=row[im];
  44. if seriesId=="0":
  45. continue
  46. print("{}: {}".format(im,seriesId))
  47. fname=os.path.join(tempBase,seriesId+".zip");
  48. ofb.getZip('series',seriesId,fname)
  49. unzipDir=os.path.join(tempBase,seriesId)
  50. try:
  51. os.mkdir(unzipDir)
  52. except FileExistsError:
  53. shutil.rmtree(unzipDir)
  54. try:
  55. outTxt=subprocess.check_output(["unzip","-d",unzipDir,"-xj",fname])
  56. except subprocess.CalledProcessError:
  57. print("unzip failed for {}".format(fname))
  58. continue
  59. slices=loadDicom.load(unzipDir)
  60. img=loadDicom.convertToNIfTI(slices)
  61. outNIfTI=os.path.join(niftiBase,seriesId+'.nii.gz')
  62. nibabel.save(img,outNIfTI)
  63. shutil.rmtree(unzipDir)
  64. os.remove(fname)
  65. labkeyNIfTI=os.path.join(projectNIfTIBase,seriesId+'.nii.gz')
  66. try:
  67. os.symlink(outNIfTI,labkeyNIfTI)
  68. except FileExistsError:
  69. pass
  70. row[linkField]="[NIFTI]"
  71. db.modifyRows("update",project,"study","Imaging",[row])
  72. if i==-1:
  73. break
  74. i=i+1
  75. print("Done")