Exemple #1
0
def skull_strip(img):
    """
    Removes non-brain voxels from a scan
    

    Parameters
    ----------
    img : numpy array
        3d np array representing the scan

    Returns
    -------
    A tuple containing the skull-stripped image followed by the binary mask
    used to strip the original image

    """
    ext = Extractor()

    # `prob` will be a 3d numpy image containing probability
    # of being brain tissue for each of the voxels in `img`
    prob = ext.run(img)
    # mask can be obtained as:
    mask = prob > 0.5

    stripped_img = img * mask

    return stripped_img, mask
def skull_stripper(image):
    ext = Extractor()
    prob = ext.run(image)
    mask = prob < 0.7
    img_filtered = np.ma.masked_array(image, mask=mask)
    img_filtered = img_filtered.filled(0)
    return img_filtered
Exemple #3
0
def get_data_with_skull_scraping(path, PROB=0.5):
    arr = nib.load(path).get_data()
    ext = Extractor()
    prob = ext.run(arr)
    mask = prob > PROB
    arr = arr * mask
    return arr
Exemple #4
0
def skullStrip(imgFp, saveDir):
    img = utils.readImg(imgFp)
    ext = Extractor()
    prob = ext.run(img)
    mask = (prob > 0.5)
    mask = mask.astype(dtype="uint16")
    utils.saveImg(mask, saveDir + "/skull-strip.nii")
    return mask
Exemple #5
0
def skull_stripper(image):
    ext = Extractor()
    prob = ext.run(image)
    # set the threshold for extractor to extract the brain
    mask = prob < 0.7
    img_filtered = np.ma.masked_array(image, mask=mask)
    # fill the background to 0
    img_filtered = img_filtered.filled(0)

    return img_filtered
def skull_removal_get_mask(nib_T1_obj):
    volume = nib_T1_obj.get_fdata()
    ext = Extractor()

    # `prob` will be a 3d numpy image containing probability
    # of being brain tissue for each of the voxels in `img`
    prob = ext.run(volume)

    # mask can be obtained as:
    mask = prob > 0.5

    return mask
Exemple #7
0
def skull_strip(image):
    img = image.get_fdata()
    ext = Extractor()

    prob = ext.run(img)  # 3d numpy array with prob that the pixel comtains brain tissue
    mask = prob > 0.5  # mask of the mri-brain tissue
    img = np.array(img)
    mask = np.array(mask)

    result = img * mask
    
    return result
def stripping(path, spath):
    print("here is the path" + path)
    rawimg, image_header = load(path)
    t = rawimg
    # print(rawimg.shape)
    plt.imshow(t[:, :, 80], cmap=plt.get_cmap('gray'))
    for i in range(193):
        scipy.misc.imsave('static/uploads1/' + str(i) + 'ws' + '.jpg',
                          rawimg[:, :, i])

    ext = Extractor()
    prob = ext.run(t)
    mask = (prob > 0.5)
    print(mask.shape)
    br = rawimg[:]
    br[~mask] = 0
    ws = []
    wos = []

    for i in range(193):
        scipy.misc.imsave('static/uploads1/' + str(i) + 'wos' + '.jpg',
                          br[:, :, i])

    for o in range(193):
        ws.append(
            Image.open('static/uploads1/' + str(o) + 'ws' +
                       '.jpg').convert('P'))
        wos.append(
            Image.open('static/uploads1/' + str(o) + 'wos' +
                       '.jpg').convert('P'))

    # ws[0].save('static/uploads1/withskull.gif', save_all=True,  C:\Users\DELL\Desktop\React Work\yfp v3\demoProject\demosite\public\img\back
    save_path = 'C:/Users/DELL/Desktop/React Work/yfp v3/demoProject/demosite/public/img/' + spath + '/'
    if not os.path.exists(save_path):
        os.makedirs(save_path)
    ws[0].save(save_path + '/withskull.gif',
               save_all=True,
               append_images=ws[1:],
               optimize=False,
               duration=60,
               loop=0)
    wos[0].save(save_path + '/withoutskull.gif',
                save_all=True,
                append_images=wos[1:],
                optimize=False,
                duration=60,
                loop=0)

    plt.imshow(rawimg[:, :, 80], cmap=plt.get_cmap('gray'))
def skull_strip(image):
    img = image.get_fdata()
    ext = Extractor()

    prob = ext.run(
        img)  # 3d numpy array with prob that the pixel comtains brain tissue
    mask = prob > 0.5  # mask of the mri-brain tissue
    img = np.array(img)
    mask = np.array(mask)

    result = img * mask
    cut = result[92, :, :]  #result[:, :, 92]
    #resized = cv.resize(cut, (160, 256), interpolation=cv.INTER_NEAREST)
    resized = np.pad(cut, ((0, 0), (16, 16), (0, 0)), mode='constant')

    return resized
Exemple #10
0
def prep_data(filename_path, nii_dir_path):

    print("Extracting brain from NII file.")
    # Brain extraction stuff happens here.
    p = 0.5
    img = nib.load(filename_path)

    affine = img.affine
    img = img.get_fdata()

    extractor = Extractor()

    prob = extractor.run(img)
    mask = prob > p

    brain = img[:]
    brain[~mask] = 0
    brain = nib.Nifti1Image(brain, affine)
    nib.save(brain, os.path.join(nii_dir_path, "brain.nii"))

    # Split the extracted brain NII into individual JPGs.
    jpg_dir_path = nii_dir_path + '/jpg/'

    # Create the necessary output directories
    if not os.path.exists(jpg_dir_path):
        os.makedirs(jpg_dir_path)

    # Split the NII into JPGs
    med2image.med2image_nii(
        inputFile=nii_dir_path + "/brain.nii",
        outputDir=jpg_dir_path,
        outputFileStem='NII-file',
        outputFileType="jpg").run()

    processed_img_dir = nii_dir_path + "/proc_img/"

    if not os.path.exists(processed_img_dir):
        os.makedirs(processed_img_dir)

    # Get the entropy values of each image...
    image_entropies = get_image_entropies(jpg_dir_path)
    # ...and save the 10 images with the highest entropy
    crop_and_save_image(image_entropies, jpg_dir_path, processed_img_dir)
Exemple #11
0
def deep_skull_strip(t1w_data, t1w_brain_mask, img):
    import tensorflow as tf
    if tf.__version__ > "2.0.0":
        import tensorflow.compat.v1 as tf
    from deepbrain import Extractor
    import logging

    print('Attempting deepbrain skull-stripping...')
    logger = tf.get_logger()
    logger.setLevel(logging.ERROR)
    os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
    ext = Extractor()
    prob = ext.run(t1w_data)
    mask = prob > 0.5
    nib.save(
        nib.Nifti1Image(mask, affine=img.affine, header=img.header),
        t1w_brain_mask,
    )
    img.uncache()
    return t1w_brain_mask
Exemple #12
0
def get_brain_mask(t1):
    """
        Provides an alternative for ANTs
        used to extract brain mask given raw image
        Does the task of skull stripping

        t1: T1 MRI volume: height x width x depth

        returns: boolean mask
    """
    from deepbrain import Extractor
    with Extractor() as ext:
        probs = ext.run(t1)
    return probs > 0.5
Exemple #13
0
def prep_data(filename_path):

    nii_output_dir = os.getenv('TMP_DIR_PATH',
                               "/Users/pmartyn/PycharmProjects/Thesis/tmp/")

    if not os.path.exists(nii_output_dir):
        os.makedirs(nii_output_dir)

    p = 0.5
    img = nib.load(filename_path)

    affine = img.affine
    img = img.get_fdata()

    prob = Extractor().run(img)
    mask = prob > p

    brain = img[:]
    brain[~mask] = 0
    image_array = nib.Nifti1Image(brain, affine).get_fdata()

    total_slices = image_array.shape[2]

    image_entropies = []

    for current_slice in range(0, total_slices):
        image_data = np.rot90(
            np.rot90(np.rot90(image_array[:, :, current_slice])))
        gray_image_data = color.rgb2gray(image_data)

        ent = measure.shannon_entropy(gray_image_data)
        dictionary = {
            "filename": current_slice,
            "entropy-value": ent,
            "image-data": gray_image_data
        }

        image_entropies.append(dictionary)

    image_entropies.sort(key=itemgetter('entropy-value'), reverse=True)

    for dictionary in image_entropies[:6]:
        filename = dictionary["filename"]
        image_data = dictionary["image-data"]
        img_to_crop = Image.fromarray(image_data)
        # The crop rectangle, as a (left, upper, right, lower)-tuple.
        cropped = img_to_crop.crop((25, 20, 250, 275))
        cropped = np.array(cropped)
        io.imsave(nii_output_dir + str(filename) + ".jpeg", cropped)
 def strip_the_skull(self,src_path,dst_path):
   """
   
   The function is to strip the skull from the input MRI brain image.
   
   Variables & its function:
     img => Loads the data from 3D input file which is then later converted to numpy array using get_fdata()
     affine => Stores the affine data of the input file
     ext => Creates an instance of class extractor
     prob => Set of probabilities are calculated and stored
     mask => The region of brain is identified using threshold 0.5
     brain => Unwanted pixels are made to 0 and is converted back to a nifti image using NiftiImage function. It is then saved as 3D using nibabel library
   
   """
   img = nib.load(src_path)
   affine = img.affine
   img = img.get_fdata()
   ext = Extractor()
   prob = ext.run(img)
   mask = prob > 0.5
   brain = img[:]
   brain[~mask] = 0
   brain = nib.Nifti1Image(brain, affine)
   nib.save(brain, dst_path)
    def __getitem__(self, idx):
        #         Returns a tuple of the image and its group/label
        imgsize = 224

        if torch.is_tensor(idx):
            idx = idx.tolist()

        imagepath = self.imagepaths[idx]
        label = get_label(imagepath, csvpath)

        #         create imgbatch with three different perspectives
        imgbatch = []

        imgdata = nib.load(imagepath).get_fdata()
        prob = Extractor().run(imgdata)
        mask = prob > 0.5
        imgdata[~mask] = 0

        imgdata1 = cv2.resize(imgdata[96, :, :], (imgsize, imgsize))
        imgdata1 = torch.from_numpy(imgdata1)
        imgdata1 = torch.stack([imgdata1, imgdata1, imgdata1], 0)
        imgbatch.append(imgdata1.reshape(3, imgsize, imgsize))

        imgdata2 = cv2.resize(imgdata[:, imgdata.shape[1] // 2, :],
                              (imgsize, imgsize))
        imgdata2 = torch.from_numpy(imgdata2)
        imgdata2 = torch.stack([imgdata2, imgdata2, imgdata2], 0)
        imgbatch.append(imgdata2.reshape(3, imgsize, imgsize))

        imgdata3 = cv2.resize(imgdata[:, :, imgdata.shape[2] // 2],
                              (imgsize, imgsize))
        imgdata3 = torch.from_numpy(imgdata3)
        imgdata3 = torch.stack([imgdata3, imgdata3, imgdata3], 0)
        imgbatch.append(imgdata3.reshape(3, imgsize, imgsize))

        sample = (imgbatch, torch.tensor(label))
        return sample
Exemple #16
0
import nibabel as nb
from deepbrain import Extractor
import numpy as np
import matplotlib.pyplot as plt

# Load a nifti as 3d numpy image [H, W, D]

img_path = 'F:\\MPI dataset\\Duc_dataset\\brain_extraction_MRA_dim_same
img = nib.load(img_path).get_fdata()

ext = Extractor()

# `prob` will be a 3d numpy image containing probability
# of being brain tissue for each of the voxels in `img`
prob = ext.run(img)

# mask can be obtained as:
mask = prob > 0.5

npy_file_train = 'F:\\Datasets\\CTdata\\img_train11860.npy'
npy_file_label = 'F:\\Datasets\\CTdata\\img_label11860.npy'


npy_file_train = 'F:\\Datasets\\CTBlood vessels data\\img_train11860.npy'
npy_file_label = 'F:\\Datasets\\CTBlood vessels data\\img_label11860.npy'

np_train=np.load(npy_file_train)
np_label=np.load(npy_file_label)

print('np_label.shape : ', np_label.shape)
print('np_train.shape : ', np_train.shape)
def main():

    args = parse_args()
    logging.basicConfig(level=logging.getLevelName(args.debug_level.upper()))

    pybids_cache_path = os.path.join(args.bids_path, PYBIDS_CACHE_PATH)

    layout = bids.BIDSLayout(
        args.bids_path,
        database_path=pybids_cache_path,
        reset_database=args.force_reindex,
        index_metadata=False,
        validate=False,
    )

    if args.datalad:
        annex_repo = AnnexRepo(args.bids_path)

    subject_list = (
        args.participant_label if args.participant_label else bids.layout.Query.ANY
    )
    session_list = args.session_label if args.session_label else bids.layout.Query.ANY
    filters = dict(
        subject=subject_list,
        session=session_list,
        **args.ref_bids_filters,
        extension=['nii','nii.gz'])
    deface_ref_images = layout.get(**filters)

    if not len(deface_ref_images):
        logging.info(f"no reference image found with condition {filters}")
        return

    new_files, modified_files = [], []

    script_dir = os.path.dirname(__file__)

    mni_path = os.path.abspath(os.path.join(script_dir, MNI_PATH))
    mni_mask_path = os.path.abspath(os.path.join(script_dir, MNI_MASK_PATH))
    # if the MNI template image is not available locally
    if not os.path.exists(os.path.realpath(mni_path)):
        datalad.api.get(mni_path, dataset=datalad.api.Dataset(script_dir + "/../../"))
    tmpl_image = nb.load(mni_path)
    tmpl_image_mask = nb.load(mni_mask_path)
    tmpl_defacemask = generate_deface_ear_mask(tmpl_image)
    brain_xtractor = Extractor()

    for ref_image in deface_ref_images:
        subject = ref_image.entities["subject"]
        session = ref_image.entities["session"]

        datalad.api.get(ref_image.path)
        ref_image_nb = ref_image.get_image()

        matrix_path = ref_image.path.replace(
            "_%s.%s" % (ref_image.entities["suffix"], ref_image.entities["extension"]),
            "_mod-%s_defacemaskreg.mat" % ref_image.entities["suffix"],
        )

        if os.path.exists(matrix_path):
            logging.info("reusing existing registration matrix")
            ref2tpl_affine = AffineMap(np.loadtxt(matrix_path))
        else:
            logging.info(f"running registration of reference serie: {ref_image.path}")
            brain_mask = (brain_xtractor.run(ref_image_nb.get_fdata()) > 0.99).astype(
                np.uint8
            )
            brain_mask[:] = scipy.ndimage.morphology.binary_dilation(
                brain_mask, iterations=4
            )
            brain_mask_nb = nb.Nifti1Image(brain_mask, ref_image_nb.affine)
            ref2tpl_affine = registration(
                tmpl_image, ref_image_nb, tmpl_image_mask, brain_mask_nb
            )
            np.savetxt(matrix_path, ref2tpl_affine.affine)
            new_files.append(matrix_path)

        if args.debug_images:
            output_debug_images(tmpl_image, ref_image, ref2tpl_affine)

        series_to_deface = []
        for filters in args.other_bids_filters:
            series_to_deface.extend(
                layout.get(
                    extension=["nii", "nii.gz"],
                    subject=subject,
                    session=session,
                    **filters,
                )
            )

        # unlock before making any change to avoid unwanted save
        if args.datalad:
            annex_repo.unlock([serie.path for serie in series_to_deface])

        for serie in series_to_deface:
            if args.datalad:
                if (
                    next(annex_repo.get_metadata(serie.path))[1].get(
                        "distribution-restrictions"
                    )
                    is None
                ):
                    logging.info(
                        f"skip {serie.path} as there are no distribution restrictions metadata set."
                    )
                    continue
            logging.info(f"defacing {serie.path}")

            datalad.api.get(serie.path)
            serie_nb = serie.get_image()
            warped_mask = warp_mask(tmpl_defacemask, serie_nb, ref2tpl_affine)
            if args.save_all_masks or serie == ref_image:
                warped_mask_path = serie.path.replace(
                    "_%s" % serie.entities["suffix"],
                    "_mod-%s_defacemask" % serie.entities["suffix"],
                )
                if os.path.exists(warped_mask_path):
                    logging.warning(
                        f"{warped_mask_path} already exists : will not overwrite, clean before rerun"
                    )
                else:
                    warped_mask.to_filename(warped_mask_path)
                    new_files.append(warped_mask_path)

            masked_serie = nb.Nifti1Image(
                np.asanyarray(serie_nb.dataobj) * np.asanyarray(warped_mask.dataobj),
                serie_nb.affine,
                serie_nb.header,
            )
            masked_serie.to_filename(serie.path)
            modified_files.append(serie.path)

    if args.datalad and len(modified_files):
        logging.info("saving files and metadata changes in datalad")
        annex_repo.set_metadata(
            modified_files, remove={"distribution-restrictions": "sensitive"}
        )
        datalad.api.save(
            modified_files + new_files,
            message="deface %d series/images and update distribution-restrictions"
            % len(modified_files),
        )
Exemple #18
0
    sys.exit()
try:
    parameters = sys.argv[1]
    for i in range(3, 9):
        print(params[i - 3])
        try:
            params_val_default[i - 3] = parameters[i]
        except IndexError:
            print(params_val_default[i - 3])
except IndexError:
    print("Some or all of parameters are in defualt")
t1Image = sitk.ReadImage(os.path.join('input', inputDir[0]))
t1Array = sitk.GetArrayFromImage(t1Image)
#define extractor for brain extraction
print('1-Brain extraction is started using Deep Brain extractor...')
ext = Extractor()
prob = ext.run(t1Array)
# mask can be obtained as: where the best parameters was found for 0.125
prob[prob < params_val_default[0]] = 0
prob[prob >= params_val_default[0]] = 1
mask = prob
brain = np.multiply(t1Array, mask)
brain = np.absolute(brain)
MaxIn = brain.max()
MinIn = brain.min()
brain = (brain * 255.0) / MaxIn
MaxIn = brain.max()
MinIn = brain.min()
brain = np.ceil(brain)
print('2-Image labeling is started using Tsallis entropy...')
q = params_val_default[1]
Exemple #19
0
 def _skull_strip_func(self) -> np.ndarray:
     ext = Extractor()
     prob = ext.run(self.sample_data)
     return prob
Exemple #20
0
def preprocess(path, fixed_size=127):

    sub, sub_raw = load_nii(path)

    ext = Extractor()

    prob = ext.run(sub)

    mask = prob < 0.5
    sub[mask] = 0

    sub = cut_on_edges(sub)

    for i in range(sub.shape[0]):
        sub[i, :, :] = cv2.medianBlur(sub[i, :, :], 3).astype('uint8')

    for i in range(sub.shape[1]):
        sub[:, i, :] = cv2.medianBlur(sub[:, i, :], 3).astype('uint8')

    for i in range(sub.shape[2]):
        sub[:, :, i] = cv2.medianBlur(sub[:, :, i], 3).astype('uint8')

    hist = myhist(sub)
    hist = hist[1:]
    hist = medfilt(hist, 7)

    peaks, _ = find_peaks(hist, height=500000)

    if len(peaks) < 2:
        raise Exception(
            "Não foram encontrados picos suficiente para a segmentação")

    sub_white = np.copy(sub)
    sub_gray = np.copy(sub)
    sub_csf = np.copy(sub)

    margin = 10

    threshold = peaks[-1]
    sub_white[sub_white < threshold - margin] = 0
    sub_white[sub_white > 0] = 255

    threshold = peaks[0]
    sub_gray[sub_gray > threshold + margin] = 0
    sub_gray[sub_gray < threshold - margin] = 0
    sub_gray[sub_gray > 0] = 255

    sub_csf[sub_csf > threshold - margin] = 0
    sub_csf[sub_csf > 0] = 255

    common = sub_csf * sub_white * sub_gray

    sub_gray = sub_gray - common
    sub_gray[sub_gray < 0] = 0

    sub_white = sub_white - common
    sub_white[sub_white < 0] = 0

    sub_csf = sub_csf - common
    sub_csf[sub_csf < 0] = 0

    return sub_raw, sub, sub_white, sub_gray, sub_csf, margin
Exemple #21
0
filelist = os.listdir(img_dir + img_file)

for i in range(len(filelist)):

    # get subject id's
    name = filelist[i][0:9]  # [5:9] for id

    # skullstrip images
    img_path = img_dir + img_file + '\\' + filelist[i]

    img = nib.load(img_path).get_fdata()
    img_length, img_width, img_height = img.shape[0], img.shape[1], img.shape[
        2]
    img_array = np.array(img)

    ext = Extractor()
    brain = ext.run(img)
    mask = brain > 0.5

    mask_array = np.array(mask, dtype=int)
    mask_array = mask_array.reshape([img_length, img_width, img_height])
    img_array = img_array.reshape([img_length, img_width, img_height])

    skull_array = mask_array * img_array
    new_img = nib.Nifti1Image(skull_array, None)

    new_file = '\\skullstripped_files\\PD'
    location = img_dir + new_file
    output = os.path.join(location, ('%s_skullstripped.nii' % name))
    nib.save(new_img, output)
import nibabel as nib
from deepbrain import Extractor
from pathlib import Path
import matplotlib.pyplot as plt
import numpy as np
import SimpleITK as sitk
import random
import torch.nn.functional as f
import torch
import pandas
import re

ext = Extractor()  #


def trim(arr, mask):
    #
    bounding_box = tuple(
        slice(np.min(i),
              np.max(i) + 1) for i in np.where(mask))
    return arr[bounding_box]


def image_resample(image: sitk.Image):
    '''
    image = sitk.ReadImage(image_path)
    使用 SimpleITK 自带函数重新缩放图像
    '''
    origin_spacing = image.GetSpacing()  #  获取源分辨率
    origin_size = image.GetSize()
Exemple #23
0
def gen_mask(t1w_head, t1w_brain, mask):
    import os.path as op
    from nilearn.image import math_img

    t1w_brain_mask = f"{op.dirname(t1w_head)}/t1w_brain_mask.nii.gz"

    if mask is not None:
        from nilearn.image import resample_to_img

        print(f"Using {mask}...")
        nib.save(resample_to_img(nib.load(mask), nib.load(t1w_head)),
                 t1w_brain_mask)
    else:
        # Check if already skull-stripped. If not, strip it.
        img = nib.load(t1w_head)
        t1w_data = img.get_fdata()
        perc_zero = np.count_nonzero(
            np.nan_to_num(
                np.array(t1w_data == 0).astype('int'))) / np.count_nonzero(
                    np.nan_to_num(t1w_data.astype('bool').astype('int')))
        # TODO find a better heuristic for determining whether a t1w image has
        # already been skull-stripped
        if perc_zero < 0.25:
            try:
                import tensorflow as tf
                if tf.__version__ > "2.0.0":
                    import tensorflow.compat.v1 as tf
                import logging
                from deepbrain import Extractor

                logger = tf.get_logger()
                logger.setLevel(logging.ERROR)
                os.environ["TF_CPP_MIN_LOG_LEVEL"] = "2"
                ext = Extractor()
                prob = ext.run(t1w_data)
                mask = prob > 0.5
                nib.save(
                    nib.Nifti1Image(mask, affine=img.affine,
                                    header=img.header),
                    t1w_brain_mask,
                )
                img.uncache()
            except:
                # Fallback to FSL's BET
                import time

                t1w_brain = f"{op.dirname(t1w_head)}/t1w_brain_bet.nii.gz"
                t1w_brain_mask = f"{op.dirname(t1w_head)}/t1w_brain_bet_mask.nii.gz"
                # Get mean B0 brain mask
                cmd = f"bet {t1w_head} {t1w_brain} -m -f 0.2"
                os.system(cmd)
                time.sleep(1)
        else:
            # Fallback to FSL's BET
            import time

            t1w_brain = f"{op.dirname(t1w_head)}/t1w_brain_bet.nii.gz"
            t1w_brain_mask = f"{op.dirname(t1w_head)}/t1w_brain_bet_mask.nii.gz"
            # Get mean B0 brain mask
            cmd = f"bet {t1w_head} {t1w_brain} -m -f 0.2"
            os.system(cmd)
            time.sleep(1)

    # Threshold T1w brain to binary in anat space
    t_img = nib.load(t1w_brain_mask)
    img = math_img("img > 0.0", img=t_img)
    img.to_filename(t1w_brain_mask)
    t_img.uncache()

    os.system(
        f"fslmaths {t1w_head} -mas {t1w_brain_mask} {t1w_brain} 2>/dev/null")

    assert op.isfile(t1w_brain)
    assert op.isfile(t1w_brain_mask)

    return t1w_brain, t1w_brain_mask
Exemple #24
0
def get_brain_mask(t1):
    from deepbrain import Extractor
    with Extractor() as ext:
        probs = ext.run(t1)
    return probs > 0.5