Example #1
0
def generate_solid_cones(scales, m=1):
    cones = np.zeros(mni_aseg.shape)
    for i, (r_min, r_max) in enumerate(scales):
        print('Creating sphere: {} - {} ...'.format((i + 1), (r_min, r_max)))
        sc = solid_cone(radius=(r_min, r_max), center=centroid, m=m)
        cones[np.where(sc)] = i + 1
    return cones
    # Calculate the inner and outer radius
    # for all the spheres: scales
    n_spheres = max_radius // (tk - overlap)
    scales = [(i * (tk - overlap), ((i + 1) * tk) - (i * overlap))
              for i in range(n_spheres)]
    print('Number of scales: {} | Scales: {}'.format(len(scales), scales))

    # Get centroid of MNI152
    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,
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)
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))
Example #5
0
def process_image(folder):
    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)

        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(0, 180, 8)):
                ti = time()
                rot_a = rotate(mask_sub, angle=z_angle, axes=(0,2), reshape=False)
                for j, x_angle in enumerate(range(-270, 90, 8)):
                    solid_ang_mask = rotate(rot_a, angle=x_angle, axes=(0,1), reshape=False)
                    img_masked = np.multiply(vol_sub, solid_ang_mask)
                    grad_masked = np.multiply(grad_sub, solid_ang_mask)
                    # img_masked = vol_sub * solid_ang_mask
                    # grad_masked = 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[j, i] = np.nan_to_num(img_masked.sum() / n)
                    img_grad_2d[j, i] = np.nan_to_num(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), j, i, img_2d[j, i], 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))
    
    exit()
Example #6
0
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))
Example #7
0
import time
from numpy import pi
import nibabel as nb
from scipy.ndimage.interpolation import rotate
from scipy.ndimage import affine_transform

import matplotlib.pyplot as plt

from lib.masks import solid_cone
from lib.visualization import show_mri

# Define the root folder
root = os.path.dirname(os.path.dirname(os.getcwd()))

if __name__ == '__main__':
    a = solid_cone(radius=(33, 66))
    print(a.shape)

    cos_gamma = np.cos(pi / 8)
    sin_gamma = np.sin(pi / 8)
    rot_affine = np.array([[1, 0, 0, 0], [0, cos_gamma, -sin_gamma, 0],
                           [0, sin_gamma, cos_gamma, 0], [0, 0, 0, 1]])

    rot_affine_3 = np.array([[cos_gamma, 0, sin_gamma, 0], [0, 1, 0, 0],
                             [-sin_gamma, 0, cos_gamma, 0], [0, 0, 0, 1]])

    rot_affine_0 = np.array([[cos_gamma, 0, sin_gamma], [0, 1, 0],
                             [-sin_gamma, 0, cos_gamma]])

    rot_affine_2 = np.array([[1, 0, 0, 0], [0, cos_gamma, -sin_gamma, 0],
                             [0, sin_gamma, cos_gamma, 0], [0, 0, 0, 1]])