def do_segmentation(self,src_path,dst_path):
    """
    
    This function is used to segment the input image into a segmented image based on grey matter, white matter and csf. These are the features used to
    detect the stage of AD 

    Variables & its function:
    nclass => value is initialized as 3 inorder to divide to 3 classes-GM,WM,CSF
    beta => The smoothness factor of segmentation
    t0 => Stores the time before segmentation
    hmrf => Create an instance of class TissueClassifierHMRF
    t1 => Store the time after segmentation
    total_time => Calculate the total time taken for segmentation
    brain => Reconstructing the segmented brain image as a 3D file which is then saved to the destination

    """
    #To get only the image data array
    t1 = load_nifti_data(src_path)
    print('t1.shape (%d, %d, %d)' % t1.shape)
    #To load the entire nifti file
    t2 = nib.load(src_path)
    nclass = 3
    beta = 0.1
    t0 = time.time()
    hmrf = TissueClassifierHMRF()
    #Perform segmentation
    initial_segmentation, final_segmentation, PVE = hmrf.classify(t1, nclass, beta)
    t1 = time.time()
    total_time = t1-t0
    print('Total time:' + str(total_time))
    print(final_segmentation.shape)
    brain = nib.Nifti1Image(final_segmentation,t2.affine)
    print('Segmentation performed successfully')
    nib.save(brain, os.path.join(dst_path))
Ejemplo n.º 2
0
 def applyHMRF(self, img):
     hmrf = TissueClassifierHMRF(verbose=False)
     _, _, PVE = hmrf.classify(img, nclasses=3, beta=0.1)
     PVE = np.squeeze(PVE)
     white_matter = PVE[:, :, 2:3]
     csf = PVE[:, :, 0:1]
     return img * white_matter
     #return img*white_matter# + img*csf
     """
Ejemplo n.º 3
0
def segmentation(brain, affine_brain, diff, affine_diff):
    # Segmentation of brain into three principal tissue components: white matter, gray matter, cerebrospinal fluid

    t1 = registration(diff, affine_diff, brain, affine_brain)
    nclass = 3
    beta = 0.1
    hmrf = TissueClassifierHMRF()
    _, final_segmentation = hmrf.classify(t1, nclass, beta)

    nib.save(nib.Nifti1Image(final_segmentation, affine_diff),
             'segmentation.nii.gz')
    return final_segmentation
Ejemplo n.º 4
0
def segmentation(t1_path):
    t1, affine = preproccesing(t1_path, save=False)
    print('t1.shape (%d, %d, %d)' % t1.shape)
    nclass, beta = 3, 0.1
    t0 = time.time()
    print('--> Computing segmentation')
    hmrf = TissueClassifierHMRF()
    initial_segmentation, final_segmentation, PVE = hmrf.classify(
        t1, nclass, beta)
    t1 = time.time()
    total_time = t1 - t0
    print('Total time:' + str(total_time))
    return PVE
Ejemplo n.º 5
0
Archivo: utils.py Proyecto: dPys/PyNets
def segment_t1w(t1w, basename, nclass=3, beta=0.1, max_iter=100):
    """
    A function to use FSL's FAST to segment an anatomical
    image into GM, WM, and CSF prob maps.

    Parameters
    ----------
    t1w : str
        File path to an anatomical T1-weighted image.
    basename : str
        A basename to use for output files.

    Returns
    -------
    out : str
        File path to the probability map Nifti1Image consisting of GM, WM,
        and CSF in the 4th dimension.

    """
    from dipy.segment.tissue import TissueClassifierHMRF
    from nilearn.image import new_img_like

    print("Segmenting T1w...")

    t1w_img = nib.load(t1w)
    hmrf = TissueClassifierHMRF()
    PVE = hmrf.classify(t1w_img.get_fdata(), nclass, beta,
                        max_iter=max_iter)[2]

    new_img_like(t1w_img, PVE[..., 2]).to_filename(
        f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_{'pve_0.nii.gz'}")

    new_img_like(t1w_img, PVE[..., 1]).to_filename(
        f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_{'pve_1.nii.gz'}")

    new_img_like(t1w_img, PVE[..., 0]).to_filename(
        f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_{'pve_2.nii.gz'}")

    out = {}  # the outputs
    out["wm_prob"] = f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_" \
                     f"pve_0.nii.gz"
    out["gm_prob"] = f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_" \
                     f"pve_1.nii.gz"
    out["csf_prob"] = f"{os.path.dirname(os.path.abspath(t1w))}/{basename}_" \
                      f"pve_2.nii.gz"

    del PVE
    t1w_img.uncache()
    gc.collect()

    return out
Ejemplo n.º 6
0
def get_tissue_sums_CN_smooth(list_data):
    global white_CN_smooth
    global gray_CN_smooth
    global csf_CN_smooth
    global white_sum_CN_smooth
    global gray_sum_CN_smooth
    global csf_sum_CN_smooth
    
    i=0
    for o in list_data:
        try:
            hmrf = TissueClassifierHMRF()
            initial_segmentation, final_segmentation, PVE = hmrf.classify(o, nclass, beta)

            img_ax = np.rot90(final_segmentation[..., 89])
            img_cor = np.rot90(final_segmentation[:, 128, :])

            img_ax = np.rot90(PVE[..., 89, 0])
            #CSF
            csf_CN_smooth.append(img_ax)
            csf_sum_CN_smooth.append(sum(img_ax))

            img_cor = np.rot90(PVE[:, :, 89, 1])
            #GRAY
            gray_CN_smooth.append(img_cor)
            gray_sum_CN_smooth.append(sum(img_cor))

            img_cor = np.rot90(PVE[:, :, 89, 2])
            #WHITE
            white_CN_smooth.append(img_cor)
            white_sum_CN_smooth.append(sum(img_cor))
            i=i+1
        except ValueError as error:
            i=i+1
            print error
            print i
Ejemplo n.º 7
0
def test_classify():

    imgseg = TissueClassifierHMRF()

    beta = 0.1
    tolerance = 0.0001
    max_iter = 10

    npt.assert_(image.max() == 1.0)
    npt.assert_(image.min() == 0.0)

    # First we test without setting iterations and tolerance
    seg_init, seg_final, PVE = imgseg.classify(image, nclasses, beta)

    npt.assert_(seg_final.max() == nclasses)
    npt.assert_(seg_final.min() == 0.0)

    # Second we test it with just changing the tolerance
    seg_init, seg_final, PVE = imgseg.classify(image, nclasses, beta,
                                               tolerance)

    npt.assert_(seg_final.max() == nclasses)
    npt.assert_(seg_final.min() == 0.0)

    # Third we test it with just the iterations
    seg_init, seg_final, PVE = imgseg.classify(image, nclasses, beta, max_iter)

    npt.assert_(seg_final.max() == nclasses)
    npt.assert_(seg_final.min() == 0.0)

    # Next we test saving the history of accumulated energies from ICM
    imgseg = TissueClassifierHMRF(save_history=True)

    seg_init, seg_final, PVE = imgseg.classify(200 * image, nclasses,
                                               beta, tolerance)

    npt.assert_(seg_final.max() == nclasses)
    npt.assert_(seg_final.min() == 0.0)

    npt.assert_(imgseg.energies_sum[0] > imgseg.energies_sum[-1])
Ejemplo n.º 8
0
"""

beta = 0.1

"""
We could also set the number of iterations. By default this parameter is set to
100 iterations, but most of the time the ICM (Iterated Conditional Modes)
loop will converge before reaching the 100th iteration.
After setting the necessary parameters we can now call an instance of the class
"TissueClassifierHMRF" and its method called "classify" and input the
parameters defined above to perform the segmentation task.
"""

t0 = time.time()

hmrf = TissueClassifierHMRF()
initial_segmentation, final_segmentation, PVE = hmrf.classify(t1, nclass, beta)

t1 = time.time()
total_time = t1-t0
print('Total time:' + str(total_time))

fig = plt.figure()
a = fig.add_subplot(1, 2, 1)
img_ax = np.rot90(final_segmentation[..., 89])
imgplot = plt.imshow(img_ax)
a.axis('off')
a.set_title('Axial')
a = fig.add_subplot(1, 2, 2)
img_cor = np.rot90(final_segmentation[:, 128, :])
imgplot = plt.imshow(img_cor)
Ejemplo n.º 9
0
import nibabel as nib
import experiments.segmentation.evaluation as eval
import time
from dipy.segment.tissue import TissueClassifierHMRF
# Get the file names from command line
img_fname = sys.argv[1]
out_fname = sys.argv[2]
with open('beta.txt','r') as f:
    beta = float(f.readline())

# Load the data
img_nib = nib.load(img_fname)
t1 = img_nib.get_data().squeeze().astype(np.float64)

# Execute the segmentation
nclass = 3
#beta = 0.1
tolerance = 0.00001

t0 = time.time()
hmrf = TissueClassifierHMRF()
initial_segmentation, final_segmentation, PVE = hmrf.classify(t1, nclass, beta, tolerance)
final_segmentation = np.array(final_segmentation)
t1 = time.time()
total_time = t1-t0
print('Total time:' + str(total_time))

# Convert numpy array to Nifti image and save
out_nib = nib.Nifti1Image(final_segmentation, img_nib.get_affine())
out_nib.to_filename(out_fname)