mni_aseg = nb.load(mni_file) centroid = tuple(get_centroid(mni_aseg.get_data() > 0)) print('Centroid of MNI152: {}'.format(centroid)) spheres = np.zeros(mni_aseg.shape) for i, (r_min, r_max) in enumerate(scales): print('Creating sphere: {} ...'.format(i + 1)) sc = solid_cone(radius=(r_min, r_max), center=centroid) spheres[np.where(sc)] = i + 1 # ==== INDEX CALCULATION ==== indexes = pd.DataFrame(columns=['scale', 'theta', 'phi', 'indexes']) for i, z_angle in enumerate(range(-180, 180, ns)): for j, x_angle in enumerate(range(0, 180, ns)): print('Processing angles: ({}, {})'.format(z_angle, x_angle)) solid_ang_mask = rotate_vol(spheres, angles=(x_angle, 0, z_angle)) # ROI for i, (r_min, r_max) in enumerate(scales): scale = '{}_{}'.format(r_min, r_max) ix = np.where(solid_ang_mask == i + 1) data = { 'scale': scale, 'theta': z_angle, 'phi': x_angle, 'indexes': ix } indexes = indexes.append([data]) # Plot for (180, 0) degrees if z_angle == -180 and x_angle == 0: nii_a = nb.Nifti1Image(solid_ang_mask, mni_aseg.affine) nb.save(nii_a, '/tmp/cones.nii')
def process_image(folders): # Scale definition smin, smax, step = (0, 100, 5) # Work directories dataset_registered_folder = '/home/jullygh/sssilvar/Documents/workdir/' results_folder = '/home/jullygh/sssilvar/Documents/results_radial_vid_optimized' mni_dir = os.path.join(root, 'lib', 'templates', 'MNI152', 'aseg.mgz') # Get template centroid mni_aseg = nb.load(mni_dir).get_data() centroid = tuple(get_centroid(mni_aseg > 0)) print('[ OK ] Centroid = {}'.format(centroid)) # Define scales (radial analysis) scales = [] for i in range(smin, smax): if i <= smax - step: scales.append((i, i + step)) print('Scales to be analysed (%d scales):' % len(scales)) print(scales) # Start processing the whole dataset for folder in [folders]: # Set of folders important in the processing pipeline # aseg_file = os.path.join(subject_dir, 'aseg.mgz') # Segmentation volume per subject subject_dir = os.path.join(dataset_registered_folder, folder) brainmask_file = os.path.join(subject_dir, 'brainmask_reg.mgz') subject_output_dir = os.path.join(results_folder, folder) # Print info message print('[ INFO ] Processing subject %s located in %s' % (folder, subject_dir)) # Try creating a folder for each subject try: os.mkdir(subject_output_dir) os.mkdir(os.path.join(subject_output_dir, 'png')) os.mkdir(os.path.join(subject_output_dir, 'raw')) print('[ OK ] Folder created at: ' + subject_output_dir) except OSError: print('[ WARNING ] Folder already exists.') # Load MRI image and aseg file mgz = nb.load(brainmask_file) img = mgz.get_data().astype(np.float32) # Calculate the gradient: img_grad gx, gy, gz = np.gradient(img) img_grad = np.sqrt(gx ** 2 + gy ** 2 + gz ** 2) # # Load aseg.mgz file: aseg, and centroid calculation: centroid # mgz = nb.load(aseg_file) # aseg = mgz.get_data() # centroid = tuple(get_centroid(aseg > 0)) for n_scale, scale in enumerate(scales): # Crete a solid angle from a scale: sa r_min, r_max = scale sa = solid_cone(radius=(r_min, r_max), center=centroid) # Start go over the whole sphere (x_angle: [0, pi] and z_angle [-pi, pi]) img_2d = np.zeros([360, 180]) img_grad_2d = np.zeros_like(img_2d) mask_sub, center = extract_sub_volume(sa, radius=(r_min, r_max), centroid=centroid) vol_sub, _ = extract_sub_volume(img, radius=(r_min, r_max), centroid=centroid) grad_sub, _ = extract_sub_volume(img_grad, radius=(r_min, r_max), centroid=centroid) for i, z_angle in enumerate(range(-180, 180)): for j, x_angle in enumerate(range(0, 180)): # Create cone solid_ang_mask = rotate_vol(mask_sub, angles=(x_angle, 0, z_angle)) # Get indexes where mask is 1 ix = np.where(solid_ang_mask == 1) # Mask images img_masked = vol_sub[ix] grad_masked = grad_sub[ix] # Number of voxels analyzed n = np.sum(solid_ang_mask[ix]) # Set pixel in plane as the mean of the voxels analyzed img_2d[i, j] = np.nan_to_num(img_masked.sum() / n) img_grad_2d[i, j] = np.nan_to_num(grad_masked.sum() / n) # print('[ SA ] Scale: %d of %d %s Ang: %s | Point (%d, %d) of (360/180) | Value: %f' % # (n_scale + 1, len(scales), scale, (x_angle, z_angle), i, j, img_2d[i, j])) print('Scale %d of %d' % (n_scale, len(scales))) # Create results: # 2 png files / 2 raw files # Output filenames for intensity and gradients png_intensity_fn = os.path.join(subject_output_dir, 'png', 'intensity_%03d_to_%03d_solid_angle_to_sphere.png' % (r_min, r_max)) raw_intensity_fn = os.path.join(subject_output_dir, 'raw', 'intensity_%03d_to_%03d_solid_angle_to_sphere.raw' % (r_min, r_max)) png_gradient_fn = os.path.join(subject_output_dir, 'png', 'gradient_%03d_to_%03d_solid_angle_to_sphere.png' % (r_min, r_max)) raw_gradient_fn = os.path.join(subject_output_dir, 'raw', 'gradient_%03d_to_%03d_solid_angle_to_sphere.raw' % (r_min, r_max)) # Save results (Intensity and gradients) plt.imsave(png_intensity_fn, img_2d, cmap='gray') img_2d.tofile(raw_intensity_fn) # RAW output for gradients plt.imsave(png_gradient_fn, img_grad_2d, cmap='gray') img_grad_2d.tofile(raw_gradient_fn)
scales = [(0, 25), (25, 50), (50, 75), (75, 100)] centroid = tuple(get_centroid(aseg > 0)) print('[ OK ] Centroid = {}'.format(centroid)) for radius in scales: # Create a binary mask (cone between scales) mask = sphere(radius=radius, center=centroid) # Subsample the whole volume and the mask vol_sub, center = extract_sub_volume(vol, radius=radius, centroid=centroid) mask_sub, _ = extract_sub_volume(mask, radius=radius, centroid=centroid) mask_sub = rotate_vol(mask_sub, angles=(45, 0, 0)) solid_ang_mask = rotate_vol(mask_sub, angles=(0, 0, -180)) # Mask sub-sampled volume vol_masked_sub = vol_sub * solid_ang_mask mean_int = np.nan_to_num(vol_masked_sub.sum() / solid_ang_mask.sum()) print(mean_int) image_out_filename = os.path.join( root, 'output', 'intensity_%d_to_%d_three_views.png' % radius) show_mri(vol_masked_sub, slice_xyz=center) plt.savefig(image_out_filename, cmap='gray', bbox_inches='tight') # plt.show()
img_grad_2d = np.zeros_like(img_2d) img_sobel_2d = np.zeros_like(img_2d) pix_count = 0 # Compute Solid cone and extract sub-volume: sc, sub_mask sc = solid_cone(radius=(r_min, r_max), center=centroid) mask_sub, center = extract_sub_volume(sc, radius=(r_min, r_max), centroid=centroid) print('Radius range: ({} to {})'.format(r_min, r_max)) # Iterate over angles (theta, phi) for i, z_angle in enumerate(range(-180, 180, ns)): for j, x_angle in enumerate(range(0, 180, ns)): solid_ang_mask = rotate_vol(mask_sub, angles=(x_angle, 0, z_angle)) # ROI pix_count += 1 # Iterate over subjects for subject in subjects.index: # Load subject and process it nii_file = join(data_folder, subject, subj_file) nii_orig = nb.load(nii_file) img = nii_orig.get_data().astype(np.float32) vol_sub, _ = extract_sub_volume(img, radius=(r_min, r_max), centroid=centroid) roi_mean = np.nan_to_num( vol_sub[np.where(solid_ang_mask)].mean())
def process_image(folders): # dataset_registered_folder = '/home/jullygh/sssilvar/Documents/workdir/' # results_folder = '/home/jullygh/sssilvar/Documents/results_same_centroid' # mni_file = join(root, 'param', 'FSL_MNI152_FreeSurferConformed_1mm.nii') # Start processing the whole dataset for folder in [folders]: # Set of folders important in the processing pipeline # aseg_file = join(subject_dir, 'aseg.mgz') # Segmentation volume per subject subject_dir = join(dataset_registered_folder, folder) brainmask_file = join(subject_dir, 'brainmask_reg.nii.gz') subject_output_dir = join(results_folder, folder) # Execute if file exists if isfile(brainmask_file): # Print info message print('[ INFO ] Processing subject %s located in %s' % (folder, subject_dir)) # Try creating a folder for each subject try: os.mkdir(subject_output_dir) print('[ OK ] Folder created at: ' + subject_output_dir) except OSError: print('[ WARNING ] Folder already exists.') # Load MRI image and aseg file mgz = nb.load(brainmask_file) img = mgz.get_data().astype(np.float) # Calculate the gradient: img_grad gx, gy, gz = np.gradient(img) img_grad = np.sqrt(gx**2 + gy**2 + gz**2) # # Load aseg.mgz file: aseg, and centroid calculation: centroid # mgz = nb.load(aseg_file) # aseg = mgz.get_data() # centroid = tuple(get_centroid(aseg > 0)) scales = [ (0, 25), (25, 50), (50, 75), (75, 100), ] for n_scale, scale in enumerate(scales): # Crete a solid angle from a scale: sa r_min, r_max = scale sa = solid_cone(radius=(r_min, r_max), center=centroid) # Start go over the whole sphere (x_angle: [0, pi] and z_angle [-pi, pi]) img_2d = np.zeros([360, 180]) img_grad_2d = np.zeros_like(img_2d) mask_sub, center = extract_sub_volume(sa, radius=(r_min, r_max), centroid=centroid) vol_sub, _ = extract_sub_volume(img, radius=(r_min, r_max), centroid=centroid) grad_sub, _ = extract_sub_volume(img_grad, radius=(r_min, r_max), centroid=centroid) for i, z_angle in enumerate(range(-180, 180, 4)): ti = time() for j, x_angle in enumerate(range(0, 180, 4)): solid_ang_mask = rotate_vol(mask_sub, angles=(x_angle, 0, z_angle)) img_masked = np.multiply(vol_sub, solid_ang_mask) grad_masked = np.multiply(grad_sub, solid_ang_mask) # Number of voxels analyzed n = solid_ang_mask.sum() # Set pixel in plane as the mean of the voxels analyzed img_2d[i, j] = img_masked.sum() / n img_grad_2d[i, j] = grad_masked.sum() / n elapsed = time() - ti print( '[ SA ] Scale: %d %s Ang: %s | Point (%d, %d) of (360/180) | Value: %f | Time: %.2f' % (n_scale + 1, scale, (x_angle, z_angle), i, j, img_2d[i, j], elapsed)) # Create results: # 2 png files / 2 raw files # PNG output for intensities img_filename = join( subject_output_dir, 'intensity_%d_to_%d_solid_angle_to_sphere' % (r_min, r_max)) plt.imsave(img_filename + '.png', img_2d, cmap='gray') img_2d.tofile(img_filename + '.raw') # RAW output for gradients grad_filename = join( subject_output_dir, 'gradient_%d_to_%d_solid_angle_to_sphere' % (r_min, r_max)) plt.imsave(grad_filename + '.png', img_grad_2d, cmap='gray') img_grad_2d.tofile(grad_filename + '.raw') else: print('[ ERROR ] File {} was not found'.format(brainmask_file))
def process_image(folder, n_scale, scale): # Set of folders important in the processing pipeline subject_dir = join(dataset_registered_folder, folder) brainmask_file = join(subject_dir, 'brainmask_reg.nii.gz') subject_output_dir = join(results_folder, folder) # Get radius range from scale r_min, r_max = scale # Declare image output filenames intensities_file = join(subject_output_dir, 'intensity_%d_to_%d_solid_angle_to_sphere' % (r_min, r_max)) gradients_file = join(subject_output_dir, 'gradient_%d_to_%d_solid_angle_to_sphere' % (r_min, r_max)) sobel_file = join(subject_output_dir, 'sobel_%d_to_%d_solid_angle_to_sphere' % (r_min, r_max)) # Create a condition checking if mappings exist images_missed = any([not isfile(f + '.raw') for f in [intensities_file, gradients_file]]) print('[ INFO ] Is any image missed?: {}'.format('Yes' if images_missed else 'No')) # Execute if file exists if isfile(brainmask_file) and images_missed: # Print info message print('[ INFO ] Processing subject %s located in %s' % (folder, subject_dir)) # Try creating a folder for each subject try: os.mkdir(subject_output_dir) print('[ OK ] Folder created at: ' + subject_output_dir) except OSError: print('[ WARNING ] Folder {} already exists.'.format(subject_output_dir)) # Load MRI image and aseg file mgz = nb.load(brainmask_file) img = mgz.get_data().astype(np.float) # Calculate the gradient: img_grad gx, gy, gz = np.gradient(img) img_grad = np.sqrt(gx ** 2 + gy ** 2 + gz ** 2) # Extract edges with sobel sobel_mode = 'reflect' sobel_x = ndi.sobel(img, axis=0, mode=sobel_mode) sobel_y = ndi.sobel(img, axis=1, mode=sobel_mode) sobel_z = ndi.sobel(img, axis=2, mode=sobel_mode) img_sobel = np.sqrt(sobel_x ** 2 + sobel_y ** 2 + sobel_z ** 2) # Crete a solid angle from a scale: sa sa = solid_cone(radius=(r_min, r_max), center=centroid) # Start go over the whole sphere (x_angle: [0, pi] and z_angle [-pi, pi]) ns = 2 # TODO: Check if it's necessary to change it img_2d = np.zeros([360 // ns, 180 // ns]) img_grad_2d = np.zeros_like(img_2d) img_sobel_2d = np.zeros_like(img_2d) # Extract only relevant volume mask_sub, center = extract_sub_volume(sa, radius=(r_min, r_max), centroid=centroid) vol_sub, _ = extract_sub_volume(img, radius=(r_min, r_max), centroid=centroid) grad_sub, _ = extract_sub_volume(img_grad, radius=(r_min, r_max), centroid=centroid) sobel_sub, _ = extract_sub_volume(img_sobel, radius=(r_min, r_max), centroid=centroid) for i, z_angle in enumerate(range(-180, 180, ns)): ti = time() for j, x_angle in enumerate(range(0, 180, ns)): solid_ang_mask = rotate_vol(mask_sub, angles=(x_angle, 0, z_angle)) img_masked = np.multiply(vol_sub, solid_ang_mask) grad_masked = np.multiply(grad_sub, solid_ang_mask) sobel_masked = np.multiply(sobel_sub, solid_ang_mask) # Number of voxels analyzed n = solid_ang_mask.sum() # Set pixel in plane as the mean of the voxels analyzed img_2d[i, j] = img_masked.sum() / n img_grad_2d[i, j] = grad_masked.sum() / n img_sobel_2d[i, j] = sobel_masked.sum() / n elapsed = time() - ti print('[ SA ] Scale: %d %s Ang: %s | Point (%d, %d) of (360/180) | Value: %f | Time: %.2f' % (n_scale + 1, scale, (x_angle, z_angle), i, j, img_2d[i, j], elapsed)) # Create results: # 2 png files / 2 raw files # Image output for intensities plt.imsave(intensities_file + '.png', img_2d, cmap='gray') img_2d.tofile(intensities_file + '.raw') # Image output for gradients plt.imsave(gradients_file + '.png', img_grad_2d, cmap='gray') img_grad_2d.tofile(gradients_file + '.raw') # Image output for sobel plt.imsave(sobel_file + '.png', img_sobel_2d, cmap='gray') img_sobel_2d.tofile(sobel_file + '.raw') else: print('[ ERROR ] File {} was not found'.format(brainmask_file))