def _gen_outfilename(self): out_file = self.inputs.out_file if isdefined(out_file) and isdefined(self.inputs.t1): _, _, ext = split_filename(self.inputs.t1) out_file = self.inputs.out_file+ext if not isdefined(out_file) and isdefined(self.inputs.t1): pth, _, ext = split_filename(self.inputs.t1) print(pth, ext) out_file = os.path.join(pth, 'segmentation'+ext) return os.path.abspath(out_file)
def create_tensors(self, image, patch_size=(96, 96)): "Function to create the 2D tensor from the 3D images" image_tensor = [] im_base, im_name, ext = split_filename(image) im_path = os.path.join(im_base, im_name) if ext == '.nrrd': image, _ = nrrd.read(image) elif ext == '.nii.gz' or ext == '.nii': image = nib.load(image).get_fdata() im_size = image.shape[:2] for n_slice in range(image.shape[2]): im_array, info_dict = load_data_2D('', '', array=image[:, :, n_slice], img_size=im_size, patch_size=patch_size, binarize=False, normalization=True, mb=[], prediction=True) for j in range(im_array.shape[0]): image_tensor.append(im_array[j, :]) if info_dict is not None: im_name = im_path + ext self.image_info[im_name]['slices'] = n_slice + 1 for k in info_dict[0].keys(): self.image_info[im_name][k] = info_dict[0][k] if image_tensor: self.image_tensor = (np.asarray(image_tensor).reshape( -1, im_array.shape[1], im_array.shape[2], 1)) else: self.image_tensor = np.zeros()
def __init__(self, toConvert, clean=False, bin_path=''): print('Started image format conversion...') self.basedir, self.filename, _ = split_filename(toConvert) self.filename = self.filename.split('.')[0] self.toConvert = toConvert self.clean = clean self.bin_path = bin_path
def resize_image(self, image, order=0, new_spacing=(0.1, 0.1, 0.1), save2file=True, outdir=None): if outdir is None: outdir, fname, ext = split_filename(image) else: _, fname, ext = split_filename(image) outname = os.path.join(outdir, fname + '_resampled' + ext) if ext == '.nrrd': image, hd = nrrd.read(image) space_x = np.abs(hd['space directions'][0, 0]) space_y = np.abs(hd['space directions'][1, 1]) space_z = np.abs(hd['space directions'][2, 2]) elif ext == '.nii.gz' or ext == '.nii': hd = nib.load(image).header affine = nib.load(image).affine image = nib.load(image).get_data() space_x, space_y, space_z = hd.get_zooms() resampling_factor = (new_spacing[0] / space_x, new_spacing[1] / space_y, new_spacing[2] / space_z) new_shape = (image.shape[0] // resampling_factor[0], image.shape[1] // resampling_factor[1], image.shape[2] // resampling_factor[2]) new_image = resize(image.astype(np.float64), new_shape, order=order, mode='edge', cval=0, anti_aliasing=False) if save2file: if ext == '.nrrd': hd['sizes'] = np.array(new_image.shape) hd['space directions'][0, 0] = new_spacing[0] hd['space directions'][1, 1] = new_spacing[1] hd['space directions'][2, 2] = new_spacing[2] nrrd.write(outname, new_image, header=hd) elif ext == '.nii.gz' or ext == '.nii': im2save = nib.Nifti1Image(new_image, affine=affine) nib.save(im2save, outname) return new_image, tuple(map(int, new_shape)), outname, image.shape
def _run_interface(self, runtime): images = self.inputs.images if images: new_dir = os.path.abspath('data_prepared') os.mkdir(os.path.abspath('data_prepared')) for i, image in enumerate(images): _, _, ext = split_filename(image) shutil.copy2(image, os.path.join( new_dir,'subject1_{}'.format(str(i).zfill(4))+ext)) else: raise Exception('No images provided!Please check.') return runtime
def _gen_outfilename(self, name): if name == 'out_file': out_file = self.inputs.out_file if isdefined(out_file) and isdefined(self.inputs.input_file): _, _, ext = split_filename(self.inputs.input_file) out_file = self.inputs.out_file+ext if not isdefined(out_file) and isdefined(self.inputs.input_file): pth, fname, ext = split_filename(self.inputs.input_file) print(pth, fname, ext) out_file = os.path.join(pth, fname+'_bet'+ext) elif name == 'out_mask': out_file = self.inputs.out_file if isdefined(out_file) and isdefined(self.inputs.input_file): _, _, ext = split_filename(self.inputs.input_file) out_file = self.inputs.out_file+'_mask'+ext # if isdefined(out_file): # pth, fname, ext = split_filename(out_file) # out_file = os.path.join(pth, fname+'_bet_mask'+ext) elif not isdefined(out_file) and isdefined(self.inputs.input_file): pth, fname, ext = split_filename(self.inputs.input_file) print(pth, fname, ext) out_file = os.path.join(pth, fname+'_bet_mask'+ext) return os.path.abspath(out_file)
def save_inference(self, outdir, binarize=True): "Function to save the segmented masks" prediction = self.prediction z0 = 0 for i, image in enumerate(self.image_info): try: _, basename, ext = split_filename(image) patches = self.image_info[image]['patches'] slices = self.image_info[image]['slices'] resampled_image_dim = self.image_info[image]['image_dim'] indexes = self.image_info[image]['indexes'] deltas = self.image_info[image]['deltas'] original_image_dim = self.image_info[image]['orig_size'] im = prediction[z0:z0 + (slices * patches), :, :, 0] final_prediction = self.inference_reshaping( im, patches, slices, resampled_image_dim, indexes, deltas, original_image_dim, binarize=binarize) outname = os.path.join( outdir, basename.split('_resampled')[0] + '_lung_segmented{}'.format(ext)) reference = self.image_info[image]['orig_image'] if ext == '.nrrd': _, hd = nrrd.read(reference) nrrd.write(outname, final_prediction, header=hd) elif ext == '.nii.gz' or ext == '.nii': ref = nib.load(reference) im2save = nib.Nifti1Image(final_prediction, affine=ref.affine) nib.save(im2save, outname) z0 = z0 + (slices * patches) except: continue return outname
def database(self): base_dir = self.input_dir sub_id = self.sub_id dict_sequences = {} dict_sequences['MR-RT'] = {} dict_sequences['RT'] = {} dict_sequences['OT'] = {} mr_rt_session = [ x for x in os.listdir(os.path.join(base_dir, sub_id)) if 'MR-RT' in x and os.path.isdir(os.path.join(base_dir, sub_id, x)) ] try: self.extention = self.workflow_inputspecs()['format'] except: self.extention = '.nii.gz' if mr_rt_session: mrs = mr_rt_session[0] dict_sequences['MR-RT'][mrs] = {} ot = list( set([ split_filename(x)[1].split('_')[0] for x in os.listdir(os.path.join(base_dir, sub_id, mrs)) ])) if ot: dict_sequences['MR-RT'][mrs]['scans'] = ot else: dict_sequences['MR-RT'][mrs]['scans'] = None ot_sessions = [ x for x in os.listdir(os.path.join(base_dir, sub_id)) if 'MR-RT' not in x and '_RT' not in x and os.path.isdir(os.path.join(base_dir, sub_id, x)) ] if ot_sessions: for session in ot_sessions: dict_sequences['OT'][session] = {} ot = list( set([ split_filename(x)[1].split('_')[0] for x in os.listdir( os.path.join(base_dir, sub_id, session)) if x != 'CT' ])) if ot: dict_sequences['OT'][session]['scans'] = ot else: dict_sequences['OT'][session]['scans'] = None rt_sessions = sorted([ x for x in os.listdir(os.path.join(base_dir, sub_id)) if '_RT' in x and os.path.isdir(os.path.join(base_dir, sub_id, x)) ]) if rt_sessions: for session in rt_sessions: dict_sequences['RT'][session] = {} dict_sequences['RT'][session]['phy_dose'] = None dict_sequences['RT'][session]['rbe_dose'] = None dict_sequences['RT'][session]['ot_dose'] = None dict_sequences['RT'][session]['rtct'] = None dict_sequences['RT'][session]['rtstruct'] = None try: physical = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session, 'RTDOSE')) if '1-PHY' in x ] except FileNotFoundError: physical = [] pass if physical: dcms = [ x for y in physical for x in glob.glob( os.path.join(base_dir, sub_id, session, 'RTDOSE', y, '*.dcm')) ] right_dcm = check_dcm_dose(dcms) if right_dcm: dict_sequences['RT'][session][ 'phy_dose'] = 'RTDOSE/1-PHY*' elif not physical and self.extention: physical = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session)) if '1-PHY' in x ] if physical: dict_sequences['RT'][session]['phy_dose'] = physical[0] try: rbe = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session, 'RTDOSE')) if '1-RBE' in x ] except FileNotFoundError: rbe = [] pass if rbe: dcms = [ x for y in rbe for x in glob.glob( os.path.join(base_dir, sub_id, session, 'RTDOSE', y, '*.dcm')) ] right_dcm = check_dcm_dose(dcms) if right_dcm: dict_sequences['RT'][session][ 'rbe_dose'] = 'RTDOSE/1-RBE*' elif not rbe and self.extention: rbe = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session)) if '1-RBE' in x ] if rbe: dict_sequences['RT'][session]['rbe_dose'] = rbe[0] try: ot_dose = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session, 'RTDOSE')) if '1-RBE' not in x and '1-PHY' not in x ] except FileNotFoundError: ot_dose = [] pass if ot_dose: dcms = [ x for y in ot_dose for x in glob.glob( os.path.join(base_dir, sub_id, session, 'RTDOSE', y, '*.dcm')) ] right_dcm = check_dcm_dose(dcms) if right_dcm: dict_sequences['RT'][session]['ot_dose'] = [ 'RTDOSE/' + x for x in ot_dose ] elif not ot_dose and self.extention: ot_dose = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session)) if '1-RBE' not in x and '1-PHY' not in x and 'DOSE' in x ] if ot_dose: dict_sequences['RT'][session]['ot_dose'] = ot_dose if os.path.isdir( os.path.join(base_dir, sub_id, session, 'RTSTRUCT')): rtstruct = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session, 'RTSTRUCT')) if '1-' in x ] if rtstruct: dict_sequences['RT'][session][ 'rtstruct'] = 'RTSTRUCT/1-*' else: if os.path.isdir( os.path.join(base_dir, sub_id, session, 'RTSTRUCT_used')): dict_sequences['RT'][session][ 'rtstruct'] = 'RTSTRUCT_used/*.dcm' if os.path.isdir( os.path.join(base_dir, sub_id, session, 'RTCT')): rtct = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session, 'RTCT')) if '1-' in x ] if rtct: dict_sequences['RT'][session]['rtct'] = 'RTCT/1-*' elif self.extention: rtct = [ x for x in os.listdir( os.path.join(base_dir, sub_id, session)) if 'RTCT.nii.gz' in x ] if rtct: dict_sequences['RT'][session]['rtct'] = rtct[0] self.dict_sequences = dict_sequences
def _run_interface(self, runtime): images = self.inputs.ct base_output_dir = os.path.abspath(self.inputs.out_folder) for image in images: sub_name, session, _, im_name = image.split('/')[-4:] base_outname = im_name.split('-')[0] output_dir = os.path.join(base_output_dir, sub_name, session) if not os.path.isdir(output_dir): os.makedirs(output_dir) _, _, extention = split_filename(image) if extention == '.nii.gz' or extention == '.nii': ref = nib.load(image) ref = nib.as_closest_canonical(ref) image_hd = ref.header space_x, space_y, space_z = image_hd.get_zooms() im = ref.get_fdata() elif extention == '.nrrd': im, image_hd = nrrd.read(image) space_x = np.abs(image_hd['space directions'][0, 0]) space_y = np.abs(image_hd['space directions'][1, 1]) space_z = np.abs(image_hd['space directions'][2, 2]) process = True out = [] min_size_x = int(17 / space_x) if min_size_x > im.shape[0]: min_size_x = im.shape[0] min_size_y = int(30 / space_y) if min_size_y > im.shape[1]: min_size_y = im.shape[1] min_size_z = int(60 / space_z) if min_size_z > im.shape[2]: min_size_z = im.shape[2] _, _, dimZ = im.shape mean_Z = int(np.ceil((dimZ) / 2)) n_mice_detected = [] not_correct = True angle = 0 counter = 0 while not_correct: im[im < np.min(im) + 824] = np.min(im) im[im == 0] = np.min(im) for offset in [20, 10, 0, -10, -20]: _, y1 = np.where(im[:, :, mean_Z + offset] != np.min(im)) im[:, np.min(y1) + min_size_y + 10:, mean_Z + offset] = 0 img2, _, _ = self.find_cluster(im[:, :, mean_Z + offset], space_x) labels = label(img2) regions = regionprops(labels) if regions: n_mice_detected.append(len(regions)) if offset == 0: xx = [ x for y in [[x.bbox[0], x.bbox[2]] for x in regions] for x in y ] yy = [ x for y in [[x.bbox[1], x.bbox[3]] for x in regions] for x in y ] else: n_mice_detected.append(0) if len(set(n_mice_detected)) == 1 or ( len(set(n_mice_detected)) == 2 and 0 in set(n_mice_detected)): not_correct = False elif counter < 8: angle = angle - 2 print( 'Different number of mice have been detected going from down-up ' 'in the image. This might be due to an oblique orientation ' 'of the mouse trail. The CT image will be rotated about the z ' 'direction of %f degrees', np.abs(angle)) n_mice_detected = [] if extention == '.nii.gz' or extention == '.nii': im = nib.load(image) im = nib.as_closest_canonical(im) im = im.get_fdata() elif extention == '.nrrd': im, _ = nrrd.read(image) im = rotate(im, angle, (0, 2), reshape=False, order=0) counter += 1 if counter % 2 == 0: mean_Z = mean_Z - 10 else: print( 'CT image has been rotated of 14° but the number of mice detected ' 'is still not the same going from down to up. This CT cannot be ' 'cropped properly and will be excluded.') process = False not_correct = False if process: if extention == '.nii.gz' or extention == '.nii': im = nib.load(image) im = nib.as_closest_canonical(im) im = im.get_fdata() elif extention == '.nrrd': im, _ = nrrd.read(image) if angle != 0: im = rotate(im, angle, (0, 2), reshape=False, order=0) im[im == 0] = np.min(im) im[im < np.min(im) + 824] = np.min(im) im[im == 0] = np.min(im) im = im[xx[0]:xx[1], yy[0]:yy[1], :] hole_size = np.zeros(im.shape[2]) offset_z = int((im.shape[2] - min_size_z) / 2) for z in range(offset_z, im.shape[2] - offset_z): _, _, zeros = self.find_cluster(im[:, :, z], space_x) hole_size[z] = zeros mean_Z = np.where(hole_size == np.max(hole_size))[0][0] if extention == '.nii.gz' or extention == '.nii': im = nib.load(image) im = nib.as_closest_canonical(im) im = im.get_fdata() elif extention == '.nrrd': im, _ = nrrd.read(image) if angle != 0: im = rotate(im, angle, (0, 2), reshape=False, order=0) im[im == 0] = np.min(im) im[im < np.min(im) + 824] = np.min(im) im[im == 0] = np.min(im) _, y1 = np.where(im[:, :, mean_Z] != np.min(im)) im[:, np.min(y1) + min_size_y + 10:, mean_Z] = 0 img2, _, _ = self.find_cluster(im[:, :, mean_Z], space_x) labels = label(img2) regions = regionprops(labels) xx = [ x for y in [[x.bbox[0], x.bbox[2]] for x in regions] for x in y ] yy = [ x for y in [[x.bbox[1], x.bbox[3]] for x in regions] for x in y ] if extention == '.nii.gz' or extention == '.nii': im = nib.load(image) im = nib.as_closest_canonical(im) im = im.get_fdata() elif extention == '.nrrd': im, _ = nrrd.read(image) if angle != 0: im = rotate(im, angle, (0, 2), reshape=False, order=0) im[im == 0] = np.min(im) average_mouse_size = int( np.round( np.mean([ xx[i + 1] - xx[i] for i in range(0, len(xx), 2) ]))) average_hole_size = average_mouse_size // 2 image_names = [ 'mouse-0{}'.format(x + 1) for x in range(int(len(xx) // 2)) ] offset_box = average_hole_size // 3 y_min = np.min(yy) - offset_box y_max = np.max(yy) + offset_box for n_mice, i in enumerate(range(0, len(xx), 2)): croppedImage = im[xx[i] - offset_box:xx[i + 1] + offset_box, y_min:y_max, mean_Z - int(min_size_z / 2):mean_Z + int(min_size_z / 2)] outname = os.path.join( output_dir, base_outname + '-{}{}'.format(image_names[n_mice], extention)) if extention == '.nii.gz' or extention == '.nii': im2save = nib.Nifti1Image(croppedImage, affine=ref.affine) nib.save(im2save, outname) elif extention == '.nrrd': nrrd.write(outname, croppedImage, header=image_hd) out.append(outname) self.cropped_images = out return runtime