Пример #1
0
def draw_mrseq_with_mask(lesion_id, target_dir, save_dir, mod='mrbl'):
    importlib.reload(masks)
    P = lm.get_paths_dict(lesion_id, target_dir)

    out_img = []
    art, C = masks.crop_img_to_mask_vicinity(P[mod]['art'],
                                             P[mod]['tumor'],
                                             .5,
                                             return_crops=True)
    pre = masks.crop_img_to_mask_vicinity(P[mod]['pre'], P[mod]['tumor'], .5)
    equ = masks.crop_img_to_mask_vicinity(P[mod]['equ'], P[mod]['tumor'], .5)
    sub = art - pre

    sl = art.shape[-1] // 2

    I, D = hf.nii_load(P[mod]['art'])
    if exists(P[mod]['enh'] + ".off"):
        mask = masks.get_mask(P[mod]['enh'], D, I.shape)
        mask = hf.crop_nonzero(mask, C)[0]
    else:
        mask = np.zeros(art.shape)

    tumor_mask = masks.get_mask(P[mod]['tumor'], D, I.shape)
    tumor_mask = hf.crop_nonzero(tumor_mask, C)[0]

    sub_w_mask = vis.create_contour_img(sub, [tumor_mask, mask])

    vis.display_sequence([
        pre[..., sl], art[..., sl], equ[..., sl], sub[..., sl], sub_w_mask,
        mask[..., sl]
    ], 2, 3, join(save_dir, "%s_%s.png" % (lesion_id, mod)))
Пример #2
0
def vascular_to_deposition_ball(lesion_id,
                                target_dir,
                                liplvls,
                                exclude_small=True):
    P = lm.get_paths_dict(lesion_id, target_dir)
    L = liplvls + [10000]

    mrbl_enh = masks.get_mask(P['ball']['mrbl']['enh'])
    ball = masks.get_mask(ball_mask_path)
    mrbl_nec = ball - mrbl_enh
    mrbl_nec[mrbl_nec < 0] = 0

    ct24 = hf.nii_load(P['ball']['ct24']['img'])[0]
    ct24[ct24 <= 0] = 1
    enh_ct = ct24 * mrbl_enh
    nec_ct = ct24 * mrbl_nec
    lips_enh = []
    lips_nec = []
    for i in range(len(L) - 1):
        den = np.sum(mrbl_enh)
        if den == 0 or (exclude_small and den <= 50):  #den / V <= .05
            lips_enh.append(np.nan)
        else:
            lips_enh.append(np.nansum([(enh_ct > L[i])]) /
                            den)  # & (enh_ct <= L[i+1])

        den = np.sum(mrbl_nec)
        if den == 0 or (exclude_small and den <= 50):  #den / V <= .05
            lips_nec.append(np.nan)
        else:
            lips_nec.append(np.nansum([(nec_ct > L[i])]) /
                            den)  # & (nec_ct <= L[i+1])

    return lips_nec + lips_enh
Пример #3
0
def lip_to_response(lesion_id, target_dir, liplvls, exclude_small=True):
    P = lm.get_paths_dict(lesion_id, target_dir)
    L = liplvls + [10000]

    M = masks.get_mask(P['ct24Tx']['crop']['tumor'])
    if exists(P['ct24Tx']['mrbl']['enh'] + ".off"):
        mrbl_enh = masks.get_mask(P['ct24Tx']['mrbl']['enh'])
        enh_bl, D = masks.get_mask(P['mrbl']['enh'],
                                   img_path=P['mrbl']['art'],
                                   return_dims=True)
        enh_bl = enh_bl.sum() * np.product(D)
    else:
        return [np.nan] * (len(liplvls) + 1)

    if exists(P['ct24Tx']['mr30']['enh'] + ".off"):
        mr30d_enh = masks.get_mask(P['ct24Tx']['mr30']['enh'])
        mr30d_nec = M * (1 - mr30d_enh)

        enh_30, D = masks.get_mask(P['mr30']['enh'],
                                   img_path=P['mr30']['art'],
                                   return_dims=True)
        enh_30 = enh_30.sum() * np.product(D)
    else:
        mr30d_enh = np.zeros(M.shape)
        mr30d_nec = M
        enh_30 = 0

    ct24, D = hf.nii_load(P['ct24Tx']['crop']['img'])
    ct24[ct24 < 0] = 1

    enh_ct = ct24 * mrbl_enh
    #V = np.sum(enh_ct != 0)
    #resp = mrbl_enh * mr30d_nec
    #resp_ct = ct24 * resp

    lips = []
    #z=np.zeros((3,3))
    #z[1,1]=1
    #B2 = np.stack([z,np.ones((3,3)),z],-1)
    #B2 = np.ones((3,3,1))
    cross = np.zeros((3, 3))
    cross[1, :] = 1
    cross[:, 1] = 1
    cross = np.expand_dims(cross, -1)
    for i in range(len(L) - 1):
        lip_segment = (enh_ct > L[i]) & (enh_ct <= L[i + 1])
        #lip_segment = binary_closing(binary_opening(lip_segment, cross))

        den = lip_segment.sum()
        if den == 0 or (exclude_small
                        and den <= 25):  #(den / V <= .05 or den <= 50)):
            lips.append(np.nan)
        else:
            lips.append(np.sum(mr30d_nec * lip_segment / den))

    return lips + [
        enh_30 / enh_bl - 1
    ]  #(mrbl_enh*mr30d_nec).sum()/mrbl_enh.sum() #np.product(D)*(mr30d_enh.sum()-mrbl_enh.sum())
Пример #4
0
def seg_target_lipiodol(P, thresholds=[75, 160, 215], num_tumors=1):
    raise ValueError("Not ready")
    ct_img, D = hf.nii_load(P["ct24"]["img"])
    mask, _ = masks.get_mask(seg, D, ct_img.shape)

    img = (mask > 0) * ct_img
    #save_folder =
    info[dirname(seg)] = (ct_img, D, mask)

    if P["ct24"]["tumor"] is None:
        tumor_mask = img > thresholds[1]
        tumor_mask = binary_closing(tumor_mask)
    else:
        tumor_mask = masks.get_mask(P["ct24"]["tumor"], D, ct_img.shape)

    mask1 = copy.deepcopy(img)
    mask1 = mask1 > thresholds[1]
    B2 = ball(2)
    B2 = B2[:, :, [0, 2, 4]]
    mask1 = binary_dilation(mask1, np.ones((3, 3, 1)))

    if num_tumors == 1:
        tumor_labels, num_labels = label(mask1, return_num=True)
        label_sizes = [
            np.sum(tumor_labels == label_id)
            for label_id in range(1, num_labels + 1)
        ]
        biggest_label = label_sizes.index(max(label_sizes)) + 1
        mask1[tumor_labels != biggest_label] = 0

    mask1 = binary_opening(binary_closing(mask1, structure=B2, iterations=2),
                           structure=B2,
                           iterations=2)

    if num_tumors == 1:
        tumor_labels, num_labels = label(mask1, return_num=True)
        label_sizes = [
            np.sum(tumor_labels == label_id)
            for label_id in range(1, num_labels + 1)
        ]
        biggest_label = label_sizes.index(max(label_sizes)) + 1
        mask1[tumor_labels != biggest_label] = 0

    target_mask = mask1 * tumor_mask
    nontarget_mask = (1 - mask1) * tumor_mask

    masks.save_mask(target_mask,
                    join(P["mask"], "target_lip"),
                    D,
                    save_mesh=True)
    masks.save_mask(nontarget_mask,
                    join(P["mask"], "nontarget_lip"),
                    D,
                    save_mesh=True)
Пример #5
0
def lip_to_response_ball(lesion_id, target_dir, liplvls, exclude_small=True):
    paths = lm.get_paths(lesion_id, target_dir, check_valid=False)
    L = liplvls + [10000]

    mrbl_enh = masks.get_mask(P['ball']['mrbl']['enh'])

    mr30d_nec = masks.difference(ball_mask_path, P['ball']['mr30']['enh'])
    mr30d_nec = mr30d_nec / mr30d_nec.max()

    ct24 = hf.nii_load(P['ball']['ct24']['img'])[0]
    resp = mrbl_enh * mr30d_nec

    enh_ct = ct24 * mrbl_enh
    V = np.sum(enh_ct > 0)

    resp_ct = ct24 * resp
    lips = []
    for i in range(len(L) - 1):
        den = np.sum([(enh_ct > L[i]) & (enh_ct <= L[i + 1])])
        if den == 0 or (exclude_small and den <= 25):
            lips.append(np.nan)
        else:
            lips.append(
                np.sum([(resp_ct > L[i]) & (resp_ct <= L[i + 1])]) / den)

    return lips
Пример #6
0
def get_best_T_lip(lesion_id, target_dir, T_lip=150):
    P = lm.get_paths_dict(lesion_id, target_dir)
    ct = hf.nii_load(P['ct24Tx']['crop']['img'])[0]
    M = masks.get_mask(P['ct24Tx']['crop']['tumor'])
    ct[M == 0] = np.nan
    ct_U = ct >= T_lip
    ct_L = ct < T_lip
    art = hf.nii_load(P['ct24Tx']['mrbl']['art'])[0].astype(int)
    sub = hf.nii_load(P['ct24Tx']['mrbl']['sub'])[0].astype(int)

    dice_best_art = 0
    for T_art in range(art[M != 0].min(), art[M != 0].max() + 1):
        intersec = ct_U[art >= T_art].sum() + ct_L[art < T_art].sum()
        if intersec > dice_best_art:
            T_best_art = T_art
            dice_best_art = intersec
    dice_best_art /= (M > 0).sum()

    dice_best_sub = 0
    for T_sub in range(sub[M != 0].min(), sub[M != 0].max() + 1):
        intersec = ct_U[sub >= T_sub].sum() + ct_L[sub < T_sub].sum()
        if intersec > dice_best_sub:
            T_best_sub = T_sub
            dice_best_sub = intersec
    dice_best_sub /= (M > 0).sum()

    return T_best_art, dice_best_art, T_best_sub, dice_best_sub
Пример #7
0
def get_RECIST(P):
    tumor_M, D = masks.get_mask(P["mrbl"]["tumor"],
                                img_path=P["mrbl"]["art"],
                                return_dims=True)
    areas = [np.sum(tumor_M[..., sl]) for sl in range(tumor_M.shape[-1])]
    max_sl = areas.index(max(areas))
    return lmet.estimate_RECIST(tumor_M[..., max_sl]) * D[0]
Пример #8
0
def get_rim_coverage(lesion_id, target_dir, min_threshold, r_frac=.15):
    P = lm.get_paths_dict(lesion_id, target_dir)

    if not exists(P['ball']['ct24']['img']):
        return np.nan

    img, D = hf.nii_load(P['ct24']['img'])
    M = masks.get_mask(P['ct24']['tumor'], D, img.shape)

    V = M.sum() * np.product(D)
    R = round(10 * V**(1 / 3) * r_frac)

    B3 = ball(R)
    B3 = tr.rescale_img(B3, D, [.1] * 3)
    B3[B3 < B3.max() / 2] = 0
    B3[B3 > 0] = 1

    coreM = binary_erosion(M, B3)
    T = max(min_threshold, img[coreM != 0].sum() / coreM.sum())
    rimM = M.astype(int) - coreM

    img[img > 450] = 450
    img = (img * rimM - T) / 34
    img[img < 0] = 0
    return img.sum() / rimM.sum()

    return (img[rimM > 0] > T).sum() / rimM.sum()
    """img, dims = hf.nii_load(P['ball']['ct24']['img'])
Пример #9
0
def seg_lipiodol(P, thresholds=[75, 160, 215]):
    #P = get_paths_dict(lesion_id, target_dir)

    img, dims = hf.nii_load(P['ct24']['img'])

    low_mask = copy.deepcopy(img)
    low_mask = low_mask > thresholds[0]
    low_mask = binary_closing(binary_opening(low_mask,
                                             structure=np.ones((3, 3, 2))),
                              structure=np.ones((2, 2, 1)))  #2,2,1
    mid_mask = copy.deepcopy(img)
    mid_mask = mid_mask > thresholds[1]
    mid_mask = binary_closing(mid_mask)
    high_mask = copy.deepcopy(img)
    high_mask = high_mask > thresholds[2]

    mask, _ = masks.get_mask(P['ct24']['liver'], dims, img.shape)
    low_mask = low_mask * mask
    mid_mask = mid_mask * mask
    high_mask = high_mask * mask

    masks.save_mask(low_mask, P['ct24']['lowlip'], dims, save_mesh=True)
    masks.save_mask(mid_mask, P['ct24']['midlip'], dims, save_mesh=True)
    masks.save_mask(high_mask, P['ct24']['highlip'], dims, save_mesh=True)

    return low_mask, mid_mask, high_mask
Пример #10
0
def get_peripheral_coverage(lesion_id, target_dir, thresholds, R=35):
    P = lm.get_paths_dict(lesion_id, target_dir)
    img, D = hf.nii_load(P['ct24']['img'])
    M = masks.get_mask(P['ct24']['tumor'], D, img.shape)

    #B4 = ball(4)
    #B4 = B4[:,:,[1,3,5,6,8]]
    B3 = ball(R)
    B3 = tr.rescale_img(B3, D, [.1] * 3)
    B3[B3 < B3.max() / 2] = 0
    B3[B3 > 0] = 1
    M = binary_dilation(M, B3) - M.astype(int)

    return [(img * M > T).sum() / M.sum() for T in thresholds]
Пример #11
0
def vascular_to_deposition(lesion_id, target_dir, liplvls, exclude_small=True):
    P = lm.get_paths_dict(lesion_id, target_dir)
    L = liplvls + [10000]

    M = masks.get_mask(P['ct24Tx']['crop']['tumor'])
    if exists(P['ct24Tx']['mrbl']['enh'] + ".off"):
        mrbl_enh = masks.get_mask(P['ct24Tx']['mrbl']['enh'])
    else:
        mrbl_enh = np.zeros(M.shape)
    mrbl_nec = M.astype(int) - mrbl_enh
    mrbl_nec[mrbl_nec < 0] = 0

    ct24 = hf.nii_load(P['ct24Tx']['crop']['img'])[0]
    ct24[ct24 <= 0] = 1
    enh_ct = ct24 * mrbl_enh
    nec_ct = ct24 * mrbl_nec
    lips_enh = []
    lips_nec = []
    lips_avg = []
    for i in range(len(L) - 1):
        den = np.sum(mrbl_enh)
        if den == 0 or (exclude_small and den <= 25):  #den / V <= .05
            lips_enh.append(np.nan)
        else:
            lips_enh.append(np.nansum(enh_ct > L[i]) /
                            den)  # & (enh_ct <= L[i+1])

        den = np.sum(mrbl_nec)
        if den == 0 or (exclude_small and den <= 25):  #den / V <= .05
            lips_nec.append(np.nan)
        else:
            lips_nec.append(np.nansum(nec_ct > L[i]) /
                            den)  # & (nec_ct <= L[i+1])

        lips_avg.append(np.sum(ct24[M != 0] > L[i]) / M.sum())

    return lips_nec + lips_enh + lips_avg
Пример #12
0
def seg_liver_mri(mri_img, save_path, mri_dims, model, tumor_mask_path=None):
    """Use a UNet to segment liver on MRI"""

    C = config.Config()
    #correct bias field!

    orig_shape = mri_img.shape

    x = mri_img
    x -= np.amin(x)
    x /= np.std(x)

    crops = list(map(int,[.05 * x.shape[0], .95 * x.shape[0]] + \
        [.05 * x.shape[1], .95 * x.shape[1]] + \
        [.05 * x.shape[2], .95 * x.shape[2]]))

    x = x[crops[0]:crops[1], crops[2]:crops[3], crops[4]:crops[5]]
    scale_shape = x.shape
    x = tr.rescale_img(x, C.dims)

    y = model.predict(np.expand_dims(x, 0))[0]
    liver_mask = (y[:, :, :, 1] > y[:, :, :, 0]).astype(float)
    liver_mask = tr.rescale_img(liver_mask, scale_shape)  #orig_shape)
    liver_mask = np.pad(liver_mask, ((crops[0], orig_shape[0] - crops[1]),
                                     (crops[2], orig_shape[1] - crops[3]),
                                     (crops[4], orig_shape[2] - crops[5])),
                        'constant')
    liver_mask = liver_mask > .5

    B3 = ball(3)
    B3 = B3[:, :, [0, 2, 3, 4, 6]]
    #B3 = ball(4)
    #B3 = B3[:,:,[1,3,5,6,8]]
    liver_mask = binary_opening(binary_closing(liver_mask, B3, 1), B3, 1)

    labels, num_labels = label(liver_mask, return_num=True)
    label_sizes = [
        np.sum(labels == label_id) for label_id in range(1, num_labels + 1)
    ]
    biggest_label = label_sizes.index(max(label_sizes)) + 1
    liver_mask[labels != biggest_label] = 0

    if tumor_mask_path is not None:
        tumor_mask, _ = masks.get_mask(tumor_mask_path, mri_dims,
                                       mri_img.shape)
        liver_mask[tumor_mask > tumor_mask.max() / 2] = liver_mask.max()

    masks.save_mask(liver_mask, save_path, mri_dims, save_mesh=True)
Пример #13
0
def draw_reg_fig(img_path, mask_path, save_path, color, modality):
    img, _ = hf.nii_load(img)
    mask = masks.get_mask(mask_path)
    img = np.transpose(img, (1, 0, 2))
    mask = np.transpose(mask, (1, 0, 2))

    for sl in range(img.shape[-1] // 5 + 1, img.shape[-1] * 4 // 5,
                    max(img.shape[-1] // 8, 1)):
        plt.close()
        if modality == "mr":
            plt.imshow(img[..., sl], cmap='gray')
        elif modality == "ct":
            plt.imshow(img[..., sl], cmap='gray', vmin=30, vmax=250)
        plt.contour(mask[:, :, sl], colors=color, alpha=.4)
        plt.axis('off')
        plt.savefig(save_path + "_%d.png" % sl, dpi=100, bbox_inches='tight')
Пример #14
0
def seg_liver_ct(ct_path, save_path, model, tumor_mask_path=None):
    """Use a UNet to segment liver on CT"""

    C = config.Config()
    ct_img, ct_dims = hf.nii_load(ct_path)

    orig_shape = ct_img.shape

    x = tr.apply_window(ct_img)
    x -= np.amin(x)

    crops = list(map(int,[.05 * x.shape[0], .95 * x.shape[0]] + \
        [.05 * x.shape[1], .95 * x.shape[1]] + \
        [.05 * x.shape[2], .95 * x.shape[2]]))

    x = x[crops[0]:crops[1], crops[2]:crops[3], crops[4]:crops[5]]
    scale_shape = x.shape
    x = tr.rescale_img(x, C.dims)

    y = model.predict(np.expand_dims(x, 0))[0]
    liver_mask = (y[:, :, :, 1] > y[:, :, :, 0]).astype(float)
    liver_mask[x < 30] = 0
    liver_mask = tr.rescale_img(liver_mask, scale_shape)
    liver_mask = np.pad(liver_mask, ((crops[0], orig_shape[0] - crops[1]),
                                     (crops[2], orig_shape[1] - crops[3]),
                                     (crops[4], orig_shape[2] - crops[5])),
                        'constant')

    B3 = ball(3)
    B3 = B3[:, :, [0, 2, 3, 4, 6]]
    liver_mask = binary_opening(binary_closing(liver_mask, B3, 1), B3, 1)

    labels, num_labels = label(liver_mask, return_num=True)
    label_sizes = [
        np.sum(labels == label_id) for label_id in range(1, num_labels + 1)
    ]
    biggest_label = label_sizes.index(max(label_sizes)) + 1
    liver_mask[labels != biggest_label] = 0

    if tumor_mask_path is not None:
        tumor_mask, _ = masks.get_mask(tumor_mask_path, ct_dims, ct_img.shape)
        liver_mask[tumor_mask > tumor_mask.max() / 2] = liver_mask.max()

    masks.save_mask(liver_mask, save_path, ct_dims, save_mesh=True)
Пример #15
0
def draw_unreg_fig(img_path,
                   mask_path,
                   save_path,
                   color,
                   modality,
                   midslice=True):
    img, D = hf.nii_load(img_path)
    mask = masks.get_mask(mask_path, D, img.shape)
    nz = np.argwhere(mask)

    pad = [img.shape[0] // 5, img.shape[1] // 5]
    sl1 = slice(max(nz[:, 0].min() - pad[0], 0), nz[:, 0].max() + pad[0])
    sl2 = slice(max(nz[:, 1].min() - pad[1], 0), nz[:, 1].max() + pad[1])
    img = np.transpose(img[sl1, sl2], (1, 0, 2))
    mask = np.transpose(mask[sl1, sl2], (1, 0, 2))
    sl1, sl2 = nz[:, -1].min(), nz[:, -1].max()

    if midslice:
        RNG = [(sl1 + sl2) // 2]
    else:
        RNG = range(sl1, sl2, max((sl2 - sl1) // 10, 1))

    if not exists(dirname(save_path)):
        os.makedirs(dirname(save_path))

    for sl in RNG:
        plt.close()
        if modality == "mr":
            plt.imshow(img[..., sl], cmap='gray')
        elif modality == "ct":
            plt.imshow(img[..., sl], cmap='gray', vmin=30, vmax=250)
        plt.contour(mask[:, :, sl], colors=color, alpha=.4)
        plt.axis('off')
        if midslice:
            plt.savefig(save_path + ".png", dpi=100, bbox_inches='tight')
        else:
            plt.savefig(save_path + "_%d.png" % sl,
                        dpi=100,
                        bbox_inches='tight')
Пример #16
0
def seg_tumor_ct(P, threshold=150, num_tumors=1):
    ct_img, D = hf.nii_load(P["ct24"]["img"])
    mask, _ = masks.get_mask(P["ct24"]["liver"], D, ct_img.shape)

    tumor_mask = (mask > 0) * ct_img > threshold
    tumor_mask = binary_closing(tumor_mask)

    if num_tumors == 1:
        tumor_labels, num_labels = label(tumor_mask, return_num=True)
        label_sizes = [
            np.sum(tumor_labels == label_id)
            for label_id in range(1, num_labels + 1)
        ]
        biggest_label = label_sizes.index(max(label_sizes)) + 1
        tumor_mask[tumor_labels != biggest_label] = 0

    B3 = ball(3)
    B3 = B3[:, :, [0, 2, 3, 4, 6]]
    tumor_mask = binary_opening(binary_closing(mask1, B3), B3)

    masks.save_mask(tumor_mask, P["ct24"]["tumor"], D)

    return tumor_mask
Пример #17
0
def spherize(lesion_id, target_dir, R=1.):
    importlib.reload(reg)

    def ball_ct_batch():
        reg.transform_region(P['ct24']['img'],
                             xform_path,
                             crops,
                             pads, [R] * 3,
                             P['ball']['ct24']['img'],
                             intermed_shape=ball_shape)
        #if exists(P['ct24']['midlip']+".off"):
        #	reg.transform_mask(P['ct24']['midlip'], P['ct24']['img'], xform_path,
        #						 crops, pads, [R]*3, P['ball']['ct24']['midlip'], intermed_shape=ball_shape)
        #	if exists(P['ct24']['highlip']+".off"):
        #		reg.transform_mask(P['ct24']['highlip'], P['ct24']['img'], xform_path,
        #							 crops, pads, [R]*3, P['ball']['ct24']['highlip'], intermed_shape=ball_shape)

    def ball_mr_batch(mod):
        reg.transform_region(P[mod]['art'],
                             xform_path,
                             crops,
                             pads, [R] * 3,
                             P['ball'][mod]['art'],
                             intermed_shape=ball_shape)

        if exists(P['ball'][mod]['enh'] + ".off"):
            reg.transform_mask(P[mod]['enh'],
                               P[mod]['art'],
                               xform_path,
                               crops,
                               pads, [R] * 3,
                               P['ball'][mod]['enh'],
                               intermed_shape=ball_shape)

    P = get_paths_dict(lesion_id, target_dir)

    ctmask, ctd = masks.get_mask(P['ct24']['tumor'], img_path=P['ct24']['img'])
    mrmask, mrd = masks.get_mask(P['mrbl']['tumor'], img_path=P['mrbl']['art'])
    ctmask = hf.crop_nonzero(ctmask)[0]
    mrmask = hf.crop_nonzero(mrmask)[0]
    CT = np.max([ctmask.shape[i] * ctd[i] for i in range(3)])
    MRBL = np.max([mrmask.shape[i] * mrd[i] for i in range(3)])

    mrmask, mrd = masks.get_mask(P['mr30']['tumor'], img_path=P['mr30']['art'])
    mrmask = hf.crop_nonzero(mrmask)[0]
    MR30 = np.max([mrmask.shape[i] * mrd[i] for i in range(3)])

    if CT > MRBL and CT > MR30:
        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['ct24']['img'], P['ct24']['tumor'], mask_path=P['ball']['mask'])
        ball_shape = masks.get_mask(P['ball']['mask'])[0].shape
        ball_ct_batch()

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mrbl']['art'],
            P['mrbl']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_mr_batch('mrbl')

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mr30']['art'],
            P['mr30']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_mr_batch('mr30')

    elif MRBL > MR30:
        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mrbl']['art'], P['mrbl']['tumor'], mask_path=P['ball']['mask'])
        ball_shape = masks.get_mask(P['ball']['mask'])[0].shape
        ball_mr_batch('mrbl')

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['ct24']['img'],
            P['ct24']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_ct_batch()

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mr30']['art'],
            P['mr30']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_mr_batch('mr30')

    else:
        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mr30']['art'], P['mr30']['tumor'], mask_path=P['ball']['mask'])
        ball_shape = masks.get_mask(P['ball']['mask'])[0].shape
        ball_mr_batch('mr30')

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['mrbl']['art'],
            P['mrbl']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_mr_batch('mrbl')

        xform_path, crops, pads = reg.get_mask_Tx_shape(
            P['ct24']['img'],
            P['ct24']['tumor'],
            ball_mask_path=P['ball']['mask'])
        ball_ct_batch()
Пример #18
0
def get_vol_coverage(lesion_id, target_dir, L):
    P = lm.get_paths_dict(lesion_id, target_dir)
    img, D = hf.nii_load(P['ct24']['img'])
    tumor = masks.get_mask(P['ct24']['tumor'], D, img.shape)
    return [(img[tumor] > T).sum() / tumor.sum() for T in L[-2:]]
Пример #19
0
def get_inputs_gui():
    """UI flow. Returns None if cancelled or terminated with error,
	else returns [user, pw, acc_nums, save_dir]."""
    try:
        title = "Lipiodol Analysis Tool"
        msg = "What analysis do you want to perform?"
        choices = [
            "Characterize Lipiodol deposition on post-procedural CT",
            "Predict short-term Lipiodol deposition from pre-procedural MR",
            "Predict short-term tumor response from pre-procedural MR and post-procedural CT"
        ]
        reply = easygui.choicebox(msg, title, choices)
        if reply == choices[0]:
            needed_inputs = ["ct24"]
        elif reply == choices[1]:
            needed_inputs = ["mrbl"]
        elif reply == choices[2]:
            needed_inputs = ["mrbl", "ct24"]
        else:
            return None

        out_dir = easygui.diropenbox(msg='Select a folder to save all files.')
        if out_dir is None:
            return None
        P = get_paths_dict(out_dir)

        if "ct24" in needed_inputs:
            get_ct24(P)
        if "mrbl" in needed_inputs:
            get_mrbl(P)

        if reply == choices[0]:
            lm.seg_lipiodol(P)
            img, D = hf.nii_load(P['ct24']['img'])
            M = masks.get_mask(P['ct24']['tumor'], D, img.shape)[0]
            M = M / M.max()
            V = M.sum() * np.product(D) / 1000
            L = (img > 75).sum() * np.product(D) / 1000
            tumor = img * M
            targL = (tumor > 75).sum() * np.product(D) / 1000
            lowTL = ((tumor > 75) &
                     (tumor <= 160)).sum() * np.product(D) / 1000
            midTL = ((tumor > 160) &
                     (tumor <= 215)).sum() * np.product(D) / 1000
            highTL = (tumor > 215).sum() * np.product(D) / 1000
            #pattern = lan.get_row_entry(P)
            easygui.msgbox((
                'Segmentations have been generated for Lipiodol deposition.\n\n',
                ' Lipiodol coverage: %.2fcc\n' % L,
                ' Target tumor volume: %.2fcc\n' % V,
                ' Target Lipiodol coverage: %.2fcc (%d%% of the tumor)\n' %
                (targL, targL * 100 / V),
                '\t- Low density (75-160 HU): %.2fcc (%d%% of the tumor)\n' %
                (lowTL, lowTL * 100 / V),
                '\t- Medium density (160-215 HU): %.2fcc (%d%% of the tumor)\n'
                % (midTL, midTL * 100 / V),
                '\t- High density (>215 HU): %.2fcc (%d%% of the tumor)\n' %
                (highTL, highTL * 100 / V)))
            return None

        elif reply == choices[1]:
            raise ValueError("Not yet available")
            lm.seg_lipiodol(P)
            easygui.msgbox((
                'Segmentations have been generated for predicted Lipiodol deposition.\n\n',
                ' Tumor volume: %.2fcc' % V,
                ' Lipiodol coverage: %.2fcc' % targL,
                ' Target Lipiodol coverage: %.2fcc (%d%% of the tumor)\n' %
                (targL, targL * 100 / V),
                '\t- Low density (75-160 HU): %.2fcc (%d%% of the tumor)\n' %
                (lowTL, lowTL * 100 / V),
                '\t- Medium density (160-215 HU): %.2fcc (%d%% of the tumor)\n'
                % (midTL, midTL * 100 / V),
                '\t- High density (>215 HU): %.2fcc (%d%% of the tumor)\n' %
                (highTL, highTL * 100 / V),
                'Pattern of target Lipiodol deposition: %s\n' % pattern),
                           'Results')
            return None

        elif reply == choices[2]:
            raise ValueError("Not yet available")

    except:
        easygui.exceptionbox()
        return None

    return [user, pw, query_terms, options]
Пример #20
0
def draw_reg_seq(lesion_id, target_dir, save_dir):
    importlib.reload(hf)
    importlib.reload(masks)
    P = lm.get_paths_dict(lesion_id, target_dir)

    out_img = []
    bl_img = masks.crop_img_to_mask_vicinity(P['mrbl']['sub'],
                                             P['mrbl']['tumor'],
                                             .5,
                                             add_mask_cont=True)
    fu_img = masks.crop_img_to_mask_vicinity(P['mr30']['sub'],
                                             P['mr30']['tumor'],
                                             .5,
                                             add_mask_cont=True)
    ct_img = masks.crop_img_to_mask_vicinity(P['ct24']['img'],
                                             P['ct24']['tumor'],
                                             .5,
                                             add_mask_cont=True,
                                             window=[0, 300])
    bl_Tx, D = hf.nii_load(P['ct24Tx']['mrbl']['art'])
    fu_Tx = hf.nii_load(P['ct24Tx']['mr30']['art'])[0]

    tumor_mask = masks.get_mask(P['ct24Tx']['crop']['tumor'])
    sl = bl_Tx.shape[-1] // 2

    if exists(P['ct24Tx']['mrbl']['enh'] + ".off"):
        bl_M = masks.get_mask(P['ct24Tx']['mrbl']['enh'], D, bl_Tx.shape)
    else:
        bl_M = np.zeros(bl_Tx.shape)

    if exists(P['ct24Tx']['mr30']['enh'] + ".off"):
        fu_M = masks.get_mask(P['ct24Tx']['mr30']['enh'], D, bl_Tx.shape)
    else:
        fu_M = np.zeros(bl_Tx.shape)

    mask_overlay = np.stack(
        [bl_M[..., sl], np.zeros(bl_M.shape[:2]), fu_M[..., sl]], -1)

    bl_Tx_cont = vis.create_contour_img(bl_Tx[..., sl],
                                        [tumor_mask[..., sl], bl_M[..., sl]],
                                        colors=[(0, 255, 0), (255, 0, 0)])
    fu_Tx_cont = vis.create_contour_img(fu_Tx[..., sl],
                                        [tumor_mask[..., sl], fu_M[..., sl]],
                                        colors=[(0, 255, 0), (0, 0, 255)])

    #if exists(P['ct24Tx']['crop']['midlip'] + ".off"):
    #	ct_M = masks.get_mask(P['ct24Tx']['crop']['midlip'], D, bl_Tx.shape)
    #else:
    #	ct_M = np.zeros(bl_Tx.shape)
    #mask_overlay2 = np.stack([bl_M[...,sl]*fu_M[...,sl]/fu_M.max(), ct_M[...,sl], bl_M[...,sl]*(1-fu_M[...,sl]/fu_M.max())], -1)

    vis.display_sequence(
        [
            bl_img,
            fu_img,
            ct_img,  #bl_img[...,bl_img.shape[-1]//2], fu_img[...,fu_img.shape[-1]//2], #ct_img[...,ct_img.shape[-1]//2]
            bl_Tx_cont,  #np.transpose(ct_Tx_cont, (1,0,2)), 
            fu_Tx_cont,
            mask_overlay
        ],  #, mask_overlay2],
        2,
        3,
        join(save_dir, "%s.png" % lesion_id))
Пример #21
0
def reg_to_ct24(lesion_id, target_dir, D=[1., 1., 2.5], padding=.2):
    importlib.reload(reg)
    P = get_paths_dict(lesion_id, target_dir)

    ct24, ct24_dims = hf.nii_load(P['ct24']['img'])
    fmod = 'ct24'

    mod = 'mrbl'
    xform_path, crops, pad_m = reg.get_mask_Tx(P[fmod]['img'],
                                               P[fmod]['tumor'],
                                               P[mod]['art'],
                                               P[mod]['tumor'],
                                               padding=padding,
                                               D=D)

    crop_ct24 = hf.crop_nonzero(ct24, crops[1])[0]
    t_shape = crop_ct24.shape
    reg.transform_region(P[mod]['art'],
                         xform_path,
                         crops,
                         pad_m,
                         ct24_dims,
                         P['ct24Tx'][mod]['art'],
                         target_shape=t_shape,
                         D=D)
    reg.transform_region(P[mod]['sub'],
                         xform_path,
                         crops,
                         pad_m,
                         ct24_dims,
                         P['ct24Tx'][mod]['sub'],
                         target_shape=t_shape,
                         D=D)
    #reg.transform_region(P[mod]['equ'], xform_path, crops, pad_m, ct24_dims,
    #			P['ct24Tx'][mod]['equ'], target_shape=t_shape, D=D);
    if exists(P[mod]['enh'] + ".off"):
        reg.transform_mask(P[mod]['enh'],
                           P[mod]['art'],
                           xform_path,
                           crops,
                           pad_m,
                           ct24_dims,
                           P['ct24Tx'][mod]['enh'],
                           target_shape=t_shape,
                           D=D)

    hf.save_nii(crop_ct24, P['ct24Tx']['crop']['img'], ct24_dims)
    M = masks.get_mask(P['ct24']['tumor'], ct24_dims, ct24.shape)[0]
    M = hf.crop_nonzero(M, crops[1])[0]
    masks.save_mask(M, P['ct24Tx']['crop']['tumor'], ct24_dims)

    mod = 'mr30'
    xform_path, crops, pad_m = reg.get_mask_Tx(P[fmod]['img'],
                                               P[fmod]['tumor'],
                                               P[mod]['art'],
                                               P[mod]['tumor'],
                                               padding=padding,
                                               D=D)

    reg.transform_region(P[mod]['art'],
                         xform_path,
                         crops,
                         pad_m,
                         ct24_dims,
                         P['ct24Tx'][mod]['art'],
                         target_shape=t_shape,
                         D=D)
    if exists(P[mod]['enh'] + ".off"):
        reg.transform_mask(P[mod]['enh'],
                           P[mod]['art'],
                           xform_path,
                           crops,
                           pad_m,
                           ct24_dims,
                           P['ct24Tx'][mod]['enh'],
                           target_shape=t_shape,
                           D=D)