Skip to content

Commit

Permalink
Conflict resolved for 2.0 releaase merge
Browse files Browse the repository at this point in the history
  • Loading branch information
VictorVeraFrazao committed Jan 22, 2024
1 parent 3fc0533 commit 99dd17a
Show file tree
Hide file tree
Showing 48 changed files with 4,088 additions and 972 deletions.
2 changes: 2 additions & 0 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -85,3 +85,5 @@ RUN cp bin/3.2_DTIConnectivity/dsi_main.py dsi_main
COPY lib/ lib/
COPY test/ test/
RUN echo "/aida/bin/dsi_studio_ubuntu_1804/dsi-studio/dsi_studio" > bin/3.2_DTIConnectivity/dsi_studioPath.txt
COPY test/ test/

20 changes: 9 additions & 11 deletions bin/2.1_T2PreProcessing/applyMICO.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,13 +26,15 @@
import sys,os
import MICO
import progressbar
from tqdm import tqdm


def run_MICO(IMGdata,outputPath):
data = nii.load(IMGdata)
v = 8

vol = data.get_data()
# get UNSCALED img data
vol = data.get_fdata()
biasCorrectedVol = np.zeros(vol.shape[0:3])
ImgMe = np.mean(vol)
if ImgMe > 10000:
Expand All @@ -42,11 +44,8 @@ def run_MICO(IMGdata,outputPath):
else:
nCvalue = 1

bar = progressbar.ProgressBar()
for idx in bar(range(vol.shape[2])):
#ImgMe = np.mean(vol,3)
#Img = ImgMe[:,:,idx]/10

progressbar = tqdm(total=vol.shape[2], desc='Biasfieldcorrection')
for idx in range(vol.shape[2]):
if np.size(vol.shape) == 4:
Img = vol[:, :, idx, 0] / nCvalue
else:
Expand Down Expand Up @@ -107,23 +106,22 @@ def run_MICO(IMGdata,outputPath):
# smV = img_bc > 1200
# img_bc[smV] = 0




M, C = sortMemC(M, C)
seg = np.zeros([nrow,ncol])
for k in range(N_region):
seg = seg + k * M[:,:, k] # label the k-th region

biasCorrectedVol[:,:,idx]=img_bc

progressbar.update(1)

progressbar.close()

unscaledNiiData = nii.Nifti1Image(biasCorrectedVol, data.affine)
hdrOut = unscaledNiiData.header
hdrOut.set_xyzt_units('mm')

#outputData = os.path.join(os.path.dirname(IMGdata),os.path.basename(IMGdata).split('.')[0]+'BiasMico.nii.gz')
outputData = os.path.join(outputPath,os.path.basename(IMGdata).split('.')[0]+'Bias.nii.gz')
# hdrOut['sform_code'] = 1
nii.save(unscaledNiiData,outputData)

return outputData
Expand Down
98 changes: 83 additions & 15 deletions bin/2.1_T2PreProcessing/preProcessing_T2.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,36 @@
import nibabel as nii
import numpy as np
import applyMICO
import subprocess
import shutil
import logging


def reset_orientation(input_file):

brkraw_dir = os.path.join(os.path.dirname(input_file), "brkraw")
if os.path.exists(brkraw_dir):
return

os.mkdir(brkraw_dir)
dst_path = os.path.join(brkraw_dir, os.path.basename(input_file))

shutil.copyfile(input_file, dst_path)

data = nii.load(input_file)
raw_img = data.dataobj.get_unscaled()

raw_nii = nii.Nifti1Image(raw_img, data.affine)
nii.save(raw_nii, input_file)

delete_orient_command = f"fslorient -deleteorient {input_file}"
subprocess.run(delete_orient_command, shell=True)

# Befehl zum Festlegen der radiologischen Orientierung
forceradiological_command = f"fslorient -forceradiological {input_file}"
subprocess.run(forceradiological_command, shell=True)



#%% Functions

Expand All @@ -24,7 +54,7 @@ def applyBET(input_file, frac, radius, vertical_gradient):
"""
# scale Nifti data by factor 10
data = nii.load(input_file)
imgTemp = data.get_data()
imgTemp = data.get_fdata()
scale = np.eye(4)* 10
scale[3][3] = 1

Expand All @@ -37,23 +67,21 @@ def applyBET(input_file, frac, radius, vertical_gradient):
hdrIn = scaledNiiData.header
hdrIn.set_xyzt_units('mm')
scaledNiiData = nii.as_closest_canonical(scaledNiiData)
print('Orientation:' + str(nii.aff2axcodes(scaledNiiData.affine)))

fslPath = os.path.join(os.getcwd(),'fslScaleTemp.nii.gz')
fslPath = os.path.join(os.path.dirname(input_file),'fslScaleTemp.nii.gz')
nii.save(scaledNiiData, fslPath)

# extract brain
output_file = os.path.join(os.path.dirname(input_file),os.path.basename(input_file).split('.')[0] + 'Bet.nii.gz')

myBet = fsl.BET(in_file=fslPath, out_file=output_file,frac=frac,radius=radius,
vertical_gradient=vertical_gradient,robust=True, mask = True)
print(myBet.cmdline)
myBet.run()
os.remove(fslPath)

# unscale result data by factor 10ˆ(-1)
dataOut = nii.load(output_file)
imgOut = dataOut.get_data()
imgOut = dataOut.get_fdata()
scale = np.eye(4)/ 10
scale[3][3] = 1

Expand All @@ -72,7 +100,7 @@ def applyBET(input_file, frac, radius, vertical_gradient):
parser = argparse.ArgumentParser(description='Preprocessing of T2 Data')

requiredNamed = parser.add_argument_group('Required named arguments')
requiredNamed.add_argument('-i','--inputFile', help='path to input file',required=True)
requiredNamed.add_argument('-i','--input_file', help='path to input file',required=True)

parser.add_argument(
'-f',
Expand Down Expand Up @@ -110,20 +138,24 @@ def applyBET(input_file, frac, radius, vertical_gradient):
args = parser.parse_args()

# set Parameters
inputFile = None
if args.inputFile is not None and args.inputFile is not None:
inputFile = args.inputFile
if not os.path.exists(inputFile):
sys.exit("Error: '%s' is not an existing directory or file %s is not in directory." % (inputFile, args.file,))
input_file = None
if args.input_file is not None and args.input_file is not None:
input_file = args.input_file
if not os.path.exists(input_file):
sys.exit("Error: '%s' is not an existing directory or file %s is not in directory." % (input_file, args.file,))

#Konfiguriere das Logging-Modul
log_file_path = os.path.join(os.path.dirname(input_file), "preprocess.txt")
logging.basicConfig(filename=log_file_path, level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')

frac = args.frac
radius = args.radius
vertical_gradient = args.vertical_gradient
bias_skip = args.bias_skip

# 1) Process MRI
print("T2 Preprocessing \33[5m...\33[0m (wait!)", end="\r")
logging.info(f"Frac: {frac} Radius: {radius} Gradient {vertical_gradient}")

<<<<<<< HEAD
# generate log - file
sys.stdout = open(os.path.join(os.path.dirname(inputFile), 'preprocessing.log'), 'w')
sys.stderr = open(os.path.join(os.path.dirname(inputFile), 'preprocessing_err.log'), 'w')
Expand All @@ -132,15 +164,51 @@ def applyBET(input_file, frac, radius, vertical_gradient):
print("Frac: %s" % frac)
print("Radius: %s" % radius)
print("Gradient: %s" %vertical_gradient)
=======
reset_orientation(input_file)
logging.info("Orientation resetted to RAS")
>>>>>>> production

#intensity correction using non parametric bias field correction algorithm
logging.info("Starting Biasfieldcorrection:")
if bias_skip == 0:
outputMICO = applyMICO.run_MICO(inputFile,os.path.dirname(inputFile))
try:
outputMICO = applyMICO.run_MICO(input_file,os.path.dirname(input_file))
logging.info("Biasfieldcorrecttion was successful")
except Exception as e:
logging.error(f'Fehler in der Biasfieldcorrecttion\nFehlermeldung: {str(e)}')
raise
else:
<<<<<<< HEAD
outputMICO = inputFile
# get rid of your skull
outputBET = applyBET(input_file=outputMICO,frac=frac,radius=radius,vertical_gradient=vertical_gradient)

sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__
print('T2 Preprocessing \033[0;30;42m COMPLETED \33[0m')
print('T2 Preprocessing \033[0;30;42m COMPLETED \33[0m')
=======
outputMICO = input_file

# brain extraction
logging.info("Starting brain extraction")
try:
outputBET = applyBET(input_file=outputMICO,frac=frac,radius=radius,vertical_gradient=vertical_gradient)
logging.info("Brain extraction was successful")
except Exception as e:
logging.error(f'Error in brain extraction\nFehlermeldung: {str(e)}')
raise

logging.info("Preprocessing completed")











>>>>>>> production
Loading

0 comments on commit 99dd17a

Please sign in to comment.