def MergePzAndTz():
    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01
    root_folder = r'D:\ProblemData\Prcoessed'

    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        print('Estimating PZ of {}'.format(case))
        cg_path = os.path.join(case_folder, 'cg.nii')
        pz_path = os.path.join(case_folder, 'pz.nii')

        cg_image, _, cg_data = LoadNiiData(cg_path, dtype=np.uint8)
        pz_image, _, pz_data = LoadNiiData(pz_path, dtype=np.uint8)

        # Merge
        merge_roi = pz_data + 2 * cg_data
        # Imshow3DArray(np.concatenate((Normalize01(cg_data), Normalize01(pz_data), Normalize01(merge_roi)), axis=1))
        # print(np.unique(merge_roi))

        # Save PZ image
        merge_image = GetImageFromArrayByImage(merge_roi, pz_image)
        SaveNiiImage(os.path.join(case_folder, 'merge_pz1_cg2.nii'),
                     merge_image)
def OneHot():
    root_folder = r'D:\ProblemData\StoreFormatData'

    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        print('Onthot coding: {}'.format(case))
        t2_path = os.path.join(case_folder, 't2_Resize_05x05.nii')
        roi_path = os.path.join(case_folder, 'MergeRoi_Resize_05x05.nii')

        _, _, t2 = LoadNiiData(t2_path)
        _, _, merge_roi = LoadNiiData(roi_path, dtype=np.uint8)

        # One Hot
        # 这里3代表PZ, CG, 背景, output : row x column x slices x 3
        output = np.zeros(
            (merge_roi.shape[0], merge_roi.shape[1], merge_roi.shape[2], 3),
            dtype=np.uint8)
        output[..., 0] = np.asarray(merge_roi == 0,
                                    dtype=np.uint8)  # save background
        output[..., 1] = np.asarray(merge_roi == 1, dtype=np.uint8)  # save PZ
        output[..., 2] = np.asarray(merge_roi == 2, dtype=np.uint8)  # save CG

        np.save(os.path.join(case_folder, 't2.npy'), t2)
        np.save(os.path.join(case_folder, 'roi_onehot.npy'), output)
def ResampleData():
    from MIP4AIM.NiiProcess.Resampler import Resampler

    root_folder = r'D:\ProblemData\Prcoessed'
    dest_root = r'D:\ProblemData\StoreFormatData'

    resampler = Resampler()
    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        dest_case_folder = os.path.join(dest_root, case)
        if not os.path.exists(dest_case_folder):
            os.mkdir(dest_case_folder)

        print('Resample PZ of {}'.format(case))
        t2_path = os.path.join(case_folder, 't2.nii')
        merge_path = os.path.join(case_folder, 'merge_pz1_cg2.nii')

        t2_image, _, t2_data = LoadNiiData(t2_path)
        merge_image, _, merge_data = LoadNiiData(merge_path, dtype=np.uint8)

        resampler.ResizeSipmleITKImage(t2_image,
                                       expected_resolution=[0.5, 0.5, -1],
                                       store_path=os.path.join(
                                           dest_case_folder,
                                           't2_Resize_05x05.nii'))
        resampler.ResizeSipmleITKImage(merge_image,
                                       is_roi=True,
                                       expected_resolution=[0.5, 0.5, -1],
                                       store_path=os.path.join(
                                           dest_case_folder,
                                           'MergeRoi_Resize_05x05.nii'))
def Normalize():
    root_folder = r'D:\ProblemData\Prcoessed'

    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        print('Normalizing PZ of {}'.format(case))
        wg_path = os.path.join(case_folder, 'prostate_roi.nii.gz')
        cg_path = os.path.join(case_folder, 'cg.nii')
        if not os.path.exists(wg_path) and not os.path.exists(cg_path):
            continue

        wg_image, _, wg_data = LoadNiiData(wg_path, dtype=np.uint8)
        cg_image, _, cg_data = LoadNiiData(cg_path, dtype=np.uint8)

        print(np.unique(wg_data), np.unique(cg_data))

        if list(np.unique(wg_data)) == [0, 255]:
            wg = np.array(wg_data / 255, dtype=np.uint8)
        else:
            wg = wg_data

        if list(np.unique(cg_data)) == [0, 255]:
            cg = np.array(cg_data / 255, dtype=np.uint8)
        else:
            cg = cg_data

        wg_array = GetImageFromArrayByImage(wg, wg_image)
        cg_array = GetImageFromArrayByImage(cg, wg_image)
        SaveNiiImage(os.path.join(case_folder, 'normalize_prostate_roi.nii'),
                     wg_array)
        SaveNiiImage(os.path.join(case_folder, 'normalize_cg.nii'), cg_array)
        print(np.unique(wg), np.unique(cg))
Beispiel #5
0
def ShowData():
    from MeDIT.SaveAndLoad import LoadNiiData
    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01
    import matplotlib.pyplot as plt

    folder = r'Z:\RawData\TZ_ROI_20191119\prostate segmentation _PZ_TZ\Nii'
    case_list = os.listdir(folder)
    for case in case_list:
        print(case)
        case_path = os.path.join(folder, case)
        t2_path = os.path.join(case_path, 't2_Resize.nii')
        pz_path = os.path.join(case_path, 'ROI_jkw0.nii')
        cg_path = os.path.join(case_path, 'ROI_jkw1.nii')
        if not os.path.exists(cg_path):
            print('cg not exists')
            continue
        if not os.path.exists(pz_path):
            print('pz not exists')
            continue

        _, _, t2_data = LoadNiiData(t2_path,
                                    dtype=np.float32,
                                    is_show_info=False)
        _, _, pz_data = LoadNiiData(pz_path,
                                    dtype=np.float32,
                                    is_show_info=False)
        _, _, cg_data = LoadNiiData(cg_path,
                                    dtype=np.float32,
                                    is_show_info=False)

        Imshow3DArray(Normalize01(t2_data), roi=[pz_data, cg_data])
def testDetect():
    # model_folder_path = r'C:\MyCode\MPApp\DPmodel\CSPCaDetection'
    model_folder_path = r'Z:\SuccessfulModel\PCaDetection25_2'
    # pca_detect = CST2AdcDwiProstateRoiDetect()
    pca_detect = CST2AdcDwiDetect2_5D()
    pca_detect.LoadModel(model_folder_path)

    from MeDIT.SaveAndLoad import LoadNiiData
    t2_image, _, t2_data = LoadNiiData(r'z:\Data\CS_ProstateCancer_Detect_multicenter\ToTest\CAO YONG CHENG\004_t2_fse_tra_Resize.nii', dtype=np.float32, is_show_info=True)
    dwi_image, _, dwi_data = LoadNiiData(r'z:\Data\CS_ProstateCancer_Detect_multicenter\ToTest\CAO YONG CHENG\007_epi_dwi_tra_CBSF5_NL3_b750_Reg_Resize.nii', dtype=np.float32, is_show_info=True)
    adc_image, _, adc_data = LoadNiiData(r'z:\Data\CS_ProstateCancer_Detect_multicenter\ToTest\CAO YONG CHENG\010_epi_dwi_tra_CBSF5_NL3_ADC_Reg_Resize.nii', dtype=np.float32, is_show_info=True)
    prostate_roi_image, _, prostate_roi_data = LoadNiiData(r'z:\Data\CS_ProstateCancer_Detect_multicenter\ToTest\CAO YONG CHENG\prostate_roi.nii.gz', dtype=np.uint8)

    # dwi_data = dwi_data[..., -1]
    # dwi_image = GetImageFromArrayByImage(dwi_data, adc_image)

    print(t2_data.shape, adc_data.shape, dwi_data.shape)

    pred, _, mask, _ = pca_detect.Run(t2_image, adc_image, dwi_image,
                                                 model_folder_path, prostate_roi_image=prostate_roi_image)

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01
    show_data = np.concatenate((Normalize01(t2_data), Normalize01(dwi_data), Normalize01(adc_data), pred), axis=1)
    show_roi = np.concatenate((mask, mask, mask, mask), axis=1)
    show_prostate_roi = np.concatenate((prostate_roi_data, prostate_roi_data, prostate_roi_data), axis=1)
    Imshow3DArray(show_data, ROI=[show_roi, show_prostate_roi])
Beispiel #7
0
def ShowRoi(process_folder):
    for case in sorted(os.listdir(process_folder)):
        print(case)
        case = 'CDM^chen di ming'
        case_folder = os.path.join(process_folder, case)
        csv_path = os.path.join(case_folder, 'roi.csv')
        t2_path = os.path.join(case_folder, 't2.nii')

        roi_list = ['roi.nii', 'roi0.nii', 'roi1.nii', 'roi2.nii']

        with open(csv_path, 'r') as csvfile:
            reader = csv.DictReader(csvfile)
            column = [row['ECE'] for row in reader]
            print(column)

        _, t2, _ = LoadNiiData(t2_path)
        Imshow3DArray(Normalize01(t2.transpose((1, 2, 0))))
        for roi in roi_list:
            roi_path = os.path.join(case_folder, roi)
            if not os.path.exists(roi_path):
                continue
            _, roi, _ = LoadNiiData(roi_path)
            try:
                Imshow3DArray(Normalize01(t2.transpose((1, 2, 0))),
                              roi=Normalize01(roi.transpose(1, 2, 0)))
            except Exception as e:
                print('failed')
Beispiel #8
0
def CheckROIForSeries(root_folder, store_folder, key, roi_key):
    import glob
    from scipy.misc import imsave
    from MeDIT.SaveAndLoad import LoadNiiData, SaveArrayAsGreyImage

    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        print(case)
        key_path = glob.glob(os.path.join(case_folder, key))
        if len(key_path) != 1:
            print('More Key Image: ', case)
            continue
        image, _, data = LoadNiiData(key_path[0])
        show_data = FlattenAllSlices(data, is_show=False)

        show_roi_list = []
        roi_path_list = glob.glob(os.path.join(case_folder, roi_key))
        if len(roi_path_list) == 0:
            print('No ROI Image: ', case)
            continue
        for roi_path in roi_path_list:
            _, _, roi = LoadNiiData(roi_path, dtype=np.uint8)
            show_roi = FlattenAllSlices(roi, is_show=False)
            if show_data.shape != show_roi.shape:
                print('Data and ROI are not consistent: ', case)
            show_roi_list.append(show_roi)

        merge_data = MergeImageWithROI(show_data, show_roi_list)

        store_path = os.path.join(store_folder, case + '.jpg')
        imsave(store_path, merge_data)
Beispiel #9
0
def MultiRoi():
    from MeDIT.SaveAndLoad import LoadNiiData
    data_folder = r'X:\PrcoessedData\ProstateCancerECE'
    multi_list = [
        'CHEN REN', 'CHEN ZHENG', 'DING YONG MING', 'DU KE BIN',
        'FYK^fan yuan kai', 'GAO FA MING', 'GCD^gu chuan dao',
        'GCF^gao chang fu', 'GENG LONG XIANG^GENG LONG XIANG',
        'GSH^gao si hui', 'GU SI KANG', 'HFL^he fu lin', 'HONG QI YUN',
        'JCG^jiang cheng guang', 'JIANG TIAN CAI^JIANG TIAN CAI',
        'JJS^jin ju sheng', 'JZL^ji zhao lan', 'LCD^li cong de',
        'LCZ^li chao zhi', 'LDJ^lei dao jin', 'LI JIA LIN',
        'LLT^liang li tong', 'LRH^lu ronghua', 'MPX^ma pei xi',
        'PENG XIAN XIANG', 'QB^qian bin', 'SBQ^shao ba qian',
        'SHA GUANG YI^SHA GUANGYI', 'SHEN DAO XIANG', 'SSS^tang shan sheng',
        'SUN BING LIANG', 'SUN QING ZHI', 'SUN ZHANG BAO', 'SXC^su xue cao',
        'WANG YONG ZHENG', 'WEI CHANG HUA', 'WLB^wu lu bao',
        'WLJ^wu liang ju ^13815870351^6924-31', 'WRM^weng rong ming',
        'WU XIAO LEI', 'WZC^wu zhi chao', 'XJJ^xu jianjun',
        'XJS^xu jingshan ^^6875-+04', 'XNB^xu neng bao', 'XSL^xu sen lou',
        'XWC^xia wen cai', 'YANG YONG JIU', 'YFG^yang fu gang',
        'YHX^yang hong xiao', 'YRE^yang rong r', 'YRF^yan rong fa',
        'YU TU JUN', 'YYX^yin yong xing', 'ZGF^zhu guo fang', 'ZHAO YU LONG',
        'ZHP^zhang heping', 'ZMJ^zhao mao jin', 'ZOU SHOU ZHONG',
        'ZXJ^zhou xian jin ^^6698+5', 'ZXM^zhou xinmin', 'ZXT^zhu xiao ting',
        'ZZF^zhou zheng fang ^^6698', 'ZZQ^zhou zu quan'
    ]

    print(len(multi_list))

    for a, case in enumerate(multi_list):
        data_path = os.path.join(data_folder, case)
        # if not os.path.exists(data_path):
        #     print(case)
        # else:
        #     data_list = os.listdir(data_path)
        #     roi_dict = {}
        #     for info in data_list:
        #         roi_dict['name'] = case
        #         if 'roi' in info and '.nii' in info:
        #             roi_dict[data_list.index(info)] = info
        #             roi_path = os.path.join(data_path, info)
        #             _, roi, _ = LoadNiiData(roi_path)
        #             label_im, nb_labels = ndimage.label(roi)
        #             for index in range(1, nb_labels+1):
        #                 num = str(label_im.tolist()).count(str(index))
        #                 if num >= 10:
        #                     roi_dict[index] = num
        #         else:
        #             continue
        #     print(a, roi_dict)
        roi_path = os.path.join(data_path, 'roi.nii')
        t2_path = os.path.join(data_path, 't2.nii')
        _, _, roi = LoadNiiData(roi_path)
        _, _, t2 = LoadNiiData(t2_path)
        label_im, nb_labels = ndimage.label(roi)
        Imshow3DArray(Normalize01(t2), roi=Normalize01(label_im))
def main():
    # PredictNii()
    t2_folder = test_folder
    predict_folder = r'Y:\142\zhangyihong\Documents\TZ_ROI\DSN_Add65_3Input\input3_output0_down\prediction'
    t2_list = os.listdir(t2_folder)

    cg_dice_list = []
    pz_dice_list = []

    for case in t2_list:
        case_path = os.path.join(t2_folder, case)
        predict_path = os.path.join(predict_folder, case)

        t2_path = os.path.join(case_path, 't2.nii')
        merge_roi_path = os.path.join(case_path, 'merge_pz1_cg2.nii')
        predict_roi_path = os.path.join(predict_path, 'prediction.nii')

        t2_image, _, t2_data = LoadNiiData(t2_path,
                                           dtype=np.float32,
                                           is_show_info=False)
        _, _, roi_data = LoadNiiData(merge_roi_path,
                                     dtype=np.uint8,
                                     is_show_info=False)
        _, _, predict_roi_data = LoadNiiData(predict_roi_path,
                                             dtype=np.uint8,
                                             is_show_info=False)

        cg_dice_list.append(
            Dice((roi_data == 2).astype(int),
                 (predict_roi_data == 2).astype(int)))
        pz_dice_list.append(
            Dice((roi_data == 1).astype(int),
                 (predict_roi_data == 1).astype(int)))
        print(
            'cg dice:',
            Dice((roi_data == 2).astype(int),
                 (predict_roi_data == 2).astype(int)))
        print(
            'pz dice:',
            Dice((roi_data == 1).astype(int),
                 (predict_roi_data == 1).astype(int)))

        # from MeDIT.Visualization import Imshow3DArray
        # from MeDIT.Normalize import Normalize01
        #
        # Imshow3DArray(Normalize01(t2_data), roi=(roi_data == 1).astype(int))
        # Imshow3DArray(Normalize01(t2_data), roi=[(predict_roi_data == 1).astype(int), (roi_data == 1).astype(int)])
    ShowHist(cg_dice_list,
             save_path=os.path.join(model_path, 'cg_dice_hist.jpg'),
             title='dice of cg')
    ShowHist(pz_dice_list,
             save_path=os.path.join(model_path, 'pz_dice_hist.jpg'),
             title='dice of pz')

    print('mean dice of cg:', sum(cg_dice_list) / len(cg_dice_list))
    print('mean dice of pz:', sum(pz_dice_list) / len(pz_dice_list))
Beispiel #11
0
def main():
    # LoadPath
    data_folder = r'H:/data/TZ roi/data/Train'
    file_list = os.listdir(data_folder)
    t2PZ_save_path = r'H:/data/TZ roi/data/Train/t2_CG'
    t2_path = os.path.join(data_folder, file_list[25] + '/t2.nii')
    t2CG_path = os.path.join(data_folder, file_list[25] + '/t2_roi_hy.nii')
    t2WG_path = os.path.join(data_folder, file_list[25] + '/prostate_roi_TrumpetNet.nii')
    t2PZ_path = os.path.join(t2PZ_save_path, 't2_PZ_roi.nii.gz')
    t2_image, _, t2 = LoadNiiData(t2_path, dtype=np.float32)
    t2CG_image, _, t2CG_roi = LoadNiiData(t2CG_path, dtype=np.uint8)
    t2WG_image, _, t2WG_roi = LoadNiiData(t2WG_path, dtype=np.uint8)
    Roi_array = GetPZ(t2CG_roi, t2WG_roi)
def TestMergePzAndTz():
    merge_path = r'Z:\StoreFormatData\PzTzSegment_ZYH\ZYHDraw\2019-CA-formal-BAO TONG\merge_pz1_cg2.nii'
    t2_path = r'Z:\StoreFormatData\PzTzSegment_ZYH\ZYHDraw\2019-CA-formal-BAO TONG\t2.nii'
    pz_path = r'Z:\StoreFormatData\PzTzSegment_ZYH\ZYHDraw\2019-CA-formal-BAO TONG\pz.nii'

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01

    _, _, t2 = LoadNiiData(t2_path)
    _, _, pz = LoadNiiData(pz_path)
    _, _, merge_roi = LoadNiiData(merge_path, dtype=np.uint8)

    Imshow3DArray(
        np.concatenate((Normalize01(pz), Normalize01(merge_roi)), axis=1))
def TestResampleData():
    merge_path = r'D:\ProblemData\StoreFormatData\CAI NING_0007947872\MergeRoi_Resize_05x05.nii'
    t2_path = r'D:\ProblemData\StoreFormatData\CAI NING_0007947872\t2_Resize_05x05.nii'

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01

    _, _, t2 = LoadNiiData(t2_path, is_show_info=True)
    _, _, merge_roi = LoadNiiData(merge_path,
                                  dtype=np.uint8,
                                  is_show_info=True)

    Imshow3DArray(
        np.concatenate((Normalize01(t2), Normalize01(merge_roi)), axis=1))
def TestNormalize():
    # cg
    cg_path = r'X:\RawData\TZ_ROI_20191119\prostate segmentation _PZ_TZ\Nii\2019-CA-formal-QIAN SHENG KUN\ROI_jkw0.nii'
    # wg
    wg_path = r'X:\RawData\TZ_ROI_20191119\prostate segmentation _PZ_TZ\Nii\2019-CA-formal-QIAN SHENG KUN\ROI_jkw1.nii'
    t2_path = r'X:\RawData\TZ_ROI_20191119\prostate segmentation _PZ_TZ\Nii\2019-CA-formal-QIAN SHENG KUN\t2_Resize.nii'

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01

    _, _, t2 = LoadNiiData(t2_path)
    _, _, cg = LoadNiiData(cg_path, dtype=np.uint8)
    _, _, wg = LoadNiiData(wg_path, dtype=np.uint8)

    Imshow3DArray(Normalize01(t2), roi=[Normalize01(cg), Normalize01(wg)])
Beispiel #15
0
def NiiImageInfoStatistic(root_folder, key_word):
    case_list = os.listdir(root_folder)
    case_list.sort()

    shape_list = []
    spacing_list = []

    for case in case_list:
        case_folder = os.path.join(root_folder, case)
        candidate_file = glob.glob(os.path.join(case_folder, key_word))
        if len(candidate_file) != 1:
            print('Not unique file: ', case)
            continue

        image, _, data = LoadNiiData(candidate_file[0])

        shape_list.append(image.GetSize())
        spacing_list.append(image.GetSpacing())

    shape_info = np.array(shape_list)
    spacing_info = np.array(spacing_list)

    print('The number of cases is :', len(shape_list))
    print('The mean of the size is :', np.mean(shape_info, axis=0))
    print('The max of the size is :', np.max(shape_info, axis=0))
    print('The min of the size is :', np.min(shape_info, axis=0))
    print('The mean of the spacing is :', np.mean(spacing_info, axis=0))
    print('The max of the spacing is :', np.max(spacing_info, axis=0))
    print('The min of the spacing is :', np.min(spacing_info, axis=0))

    import matplotlib.pyplot as plt
    fig = plt.figure(0, [15, 5])
    ax1 = fig.add_subplot(131)
    ax1.hist(spacing_info[:, 0], bins=50)
    ax1.set_xlabel('Resolution')
    ax1.set_ylabel('Spacing/mm')
    ax1.set_title('Histogram of x-axis spacing')
    ax2 = fig.add_subplot(132)
    ax2.hist(spacing_info[:, 1], bins=50)
    ax2.set_xlabel('Resolution')
    ax2.set_ylabel('Spacing/mm')
    ax2.set_title('Histogram of y-axis spacing')
    ax3 = fig.add_subplot(133)
    ax3.hist(spacing_info[:, 2], bins=50)
    ax3.set_xlabel('Resolution')
    ax3.set_ylabel('Spacing/mm')
    ax3.set_title('Histogram of z-axis spacing')
    plt.show()
Beispiel #16
0
def testSeg():
    model_folder_path = r'z:\SuccessfulModel\ProstateSegmentation'
    prostate_segmentor = ProstateSegmentation2D()
    prostate_segmentor.LoadModel(model_folder_path)

    import os
    import glob
    from MeDIT.SaveAndLoad import LoadNiiData
    root_folder = r'z:\Data\CS_ProstateCancer_Detect_multicenter\ToTest\Cui hai pei'
    t2_candidate = glob.glob(os.path.join(root_folder, '*t2*tra*Resize.nii'))
    if len(t2_candidate) != 1:
        print('Check T2 Path')
        return
    t2_path = r'z:\temp_data\test_data_prostate\301_case2_1.2.840.113619.2.25.4.1415787.1457070159.316\004_AX T2 PROPELLER.nii'
    image, _, show_data = LoadNiiData(t2_path,
                                      dtype=np.float32,
                                      is_show_info=True)

    predict_data, mask, mask_image = prostate_segmentor.Run(
        image, model_folder_path)

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01
    Imshow3DArray(predict_data)
    Imshow3DArray(Normalize01(show_data),
                  ROI=np.asarray(predict_data > 0.5, dtype=np.uint8))
def TestGetPzRegion():
    # pz_path = r'X:\PrcoessedData\PzTzSegment_ZYH\DoctorDraw2\2019-CA-formal-JIANG HONG GEN\pz.nii'
    t2_path = r'D:\ProblemData\Prcoessed\Chen xian ming\t2.nii'
    cg_path = r'D:\ProblemData\Prcoessed\Chen xian ming\cg.nii'
    wg_path = r'D:\ProblemData\Prcoessed\Chen xian ming\prostate_roi.nii.gz'

    from MeDIT.Visualization import Imshow3DArray
    from MeDIT.Normalize import Normalize01
    import matplotlib.pyplot as plt

    _, _, t2 = LoadNiiData(t2_path)
    # _, _, pz = LoadNiiData(pz_path, dtype=np.uint8)
    _, _, cg = LoadNiiData(cg_path, dtype=np.uint8)
    _, _, wg = LoadNiiData(wg_path, dtype=np.uint8)

    Imshow3DArray(Normalize01(t2), roi=[wg, cg])
Beispiel #18
0
def ModelPre():
    import numpy as np

    from CNNModel.SuccessfulModel.ProstateSegment import ProstateSegmentationTrumpetNet
    # from MeDIT.UsualUse import *
    from MeDIT.SaveAndLoad import LoadNiiData
    from MeDIT.Normalize import Normalize01
    from MeDIT.Visualization import Imshow3DArray

    model_path = r'd:\SuccessfulModel\ProstateSegmentTrumpetNet'

    segment = ProstateSegmentationTrumpetNet()
    if not segment.LoadConfigAndModel(model_path):
        print('Load Failed')

    t2_image, _, t2 = LoadNiiData(
        r'd:\Data\HouYing\processed\BIAN JIN YOU\t2.nii')

    preds, mask, mask_image = segment.Run(t2_image)

    show_data = np.concatenate(
        (Normalize01(t2), np.clip(preds, a_min=0.0, a_max=1.0)), axis=1)
    show_roi = np.concatenate((mask, mask), axis=1)

    Imshow3DArray(show_data, roi=show_roi)
Beispiel #19
0
def ShowOne():
    path = r'X:\PrcoessedData\ProstateCancerECE\FCX^fang chun xiang\t2.nii'
    roi0_path = r'X:\PrcoessedData\ProstateCancerECE\FCX^fang chun xiang\roi0.nii'
    roi1_path = r'X:\PrcoessedData\ProstateCancerECE\FCX^fang chun xiang\roi1.nii'
    # roi2_path = r'X:\PrcoessedData\ProstateCancerECE\CDM^chen di ming\roi2.nii'
    _, data, _ = LoadNiiData(path)
    _, roi0, _ = LoadNiiData(roi0_path)
    _, roi1, _ = LoadNiiData(roi1_path)
    # _, roi2, _ = LoadNiiData(roi2_path)

    data = data.transpose((1, 2, 0))
    roi0 = roi0.transpose((1, 2, 0))
    roi1 = roi1.transpose((1, 2, 0))
    # roi2 = roi2.transpose((1, 2, 0))

    Imshow3DArray(Normalize01(data), roi=[roi0, roi1])
Beispiel #20
0
def SelectThree(PIRADS, ECE, roi0_path, roi1_path, roi2_path):
    if ECE[0] == ECE[1] == ECE[2]:
        if PIRADS[0] == PIRADS[1] == PIRADS[2]:
            _, data0, _ = LoadNiiData(roi0_path)
            _, data1, _ = LoadNiiData(roi1_path)
            _, data2, _ = LoadNiiData(roi2_path)
            volumn = [np.sum(data0), np.sum(data1), np.sum(data2)]
            roi = [volumn.index(max(volumn[0], volumn[1], volumn[2]))]
            # print(case, 'VolumnMax', roi)
        else:
            roi = GetPiradsMax(PIRADS)
            # print(case, 'MaxPIRADS', roi)
    else:
        roi = GetECETrue(ECE)
        # print(case, 'ECETrue', roi)
    return roi
def AugmentScript():
    from MeDIT.SaveAndLoad import LoadNiiData
    from MeDIT.Visualization import Imshow3DArray, DrawBoundaryOfBinaryMask
    from MeDIT.Normalize import Normalize01
    import numpy as np
    import time

    t2_image, _, t2 = LoadNiiData(r'H:/data/TZ roi/BIAN ZHONG BEN/t2.nii',
                                  dtype=np.float32)
    roi_image, _, roi = LoadNiiData(
        r'H:/data/TZ roi/BIAN ZHONG BEN/prostate_roi_TrumpetNet.nii',
        dtype=np.uint8)

    Imshow3DArray(t2, ROI=roi)

    t2_slice = t2[..., 10]
    roi_slice = roi[..., 10]

    # DrawBoundaryOfBinaryMask(t2_slice, roi_slice)
    import matplotlib.pyplot as plt
    # plt.imshow(np.concatenate((Normalize01(t2_slice), Normalize01(roi_slice)), axis=1), cmap='gray')
    # plt.show()

    from MeDIT.DataAugmentor import DataAugmentor2D, AugmentParametersGenerator
    param_dict = {
        'stretch_x': 0.1,
        'stretch_y': 0.1,
        'shear': 0.1,
        'rotate_z_angle': 20,
        'horizontal_flip': True
    }

    augment_generator = AugmentParametersGenerator()
    augmentor = DataAugmentor2D()

    while True:
        augment_generator.RandomParameters(param_dict)
        transform_param = augment_generator.GetRandomParametersDict()
        print(transform_param)

        augment_t2 = augmentor.Execute(t2_slice,
                                       aug_parameter=transform_param,
                                       interpolation_method='linear')
        augment_roi = augmentor.Execute(roi_slice,
                                        aug_parameter=transform_param,
                                        interpolation_method='linear')
Beispiel #22
0
def SelectTwo(PIRADS, ECE, roi0_path, roi1_path):
    if ECE[0] != ECE[1]:
        roi = GetECETrue(ECE)
        # print(case, 'ECE=True:', roi)
    else:
        if PIRADS[0] != PIRADS[1]:
            roi = GetPiradsMax(PIRADS)
            # print(case, 'PIRADSMAX', roi)
        else:
            _, data0, _ = LoadNiiData(roi0_path)
            _, data1, _ = LoadNiiData(roi1_path)
            volumn0 = np.sum(data0)
            volumn1 = np.sum(data1)
            if volumn0 > volumn1:
                roi = [0]
            else:
                roi = [1]
            # print(case, 'VolumnMax', roi)
    return roi
    def show_feature_map(self, show_img_path, show_roi_path,
                         show_feature_map_path, store_path):
        from MeDIT.SaveAndLoad import LoadNiiData
        _, _, feature_map_array = LoadNiiData(show_feature_map_path)
        featuremapvisualization = FeatureMapVisualizition()
        featuremapvisualization.LoadData(show_img_path, show_roi_path,
                                         show_feature_map_path)

        # hsv/jet/gist_rainbow
        featuremapvisualization.Show(color_map='rainbow',
                                     store_path=store_path)
Beispiel #24
0
def ShowProblemData(resample_folder, case):
    case_path = os.path.join(resample_folder, case)
    t2_path = os.path.join(case_path, 't2.nii')
    roi_path = os.path.join(case_path, 'roi.nii')
    dwi_path = os.path.join(case_path, 'dwi_Reg.nii')
    adc_path = os.path.join(case_path, 'adc_Reg.nii')

    # Load data
    _, t2, _ = LoadNiiData(t2_path, dtype=np.float32)
    _, dwi, _ = LoadNiiData(dwi_path, dtype=np.float32)
    _, adc, _ = LoadNiiData(adc_path, dtype=np.float32)
    _, roi, _ = LoadNiiData(roi_path, dtype=np.uint8)

    t2 = np.transpose(t2, [1, 2, 0])
    dwi = np.transpose(dwi, [1, 2, 0])
    adc = np.transpose(adc, [1, 2, 0])
    _, _, new_roi = KeepLargest(roi)
    new_roi = np.transpose(new_roi, [1, 2, 0])
    Imshow3DArray(Normalize01(t2), roi=Normalize01(new_roi))
    Imshow3DArray(Normalize01(dwi), roi=Normalize01(new_roi))
    Imshow3DArray(Normalize01(adc), roi=Normalize01(new_roi))
Beispiel #25
0
def test():
    t2_path = r'X:\PrcoessedData\ProstateCancerECE\CHEN ZHENG\t2.nii'
    roi0_path = r'X:\PrcoessedData\ProstateCancerECE\CHEN ZHENG\roi.nii'
    # roi1_path = r'X:\PrcoessedData\ProstateCancerECE\SXC^su xue cao\roi1.nii'
    # roi2_path = r'X:\PrcoessedData\ProstateCancerECE\SXC^su xue cao\roi.nii'
    _, _, t2 = LoadNiiData(t2_path)
    _, _, roi0 = LoadNiiData(roi0_path)
    # _, roi1, _ = LoadNiiData(roi1_path)
    # _, roi2, _ = LoadNiiData(roi2_path)
    label_im0, nb_labels0 = ndimage.label(roi0)

    # label_im1, nb_labels1 = ndimage.label(roi1)
    # label_im2, nb_labels2 = ndimage.label(roi2)
    # roi0_list = []
    # roi1_list = []
    # roi2_list = []
    # for index in range(1, nb_labels0 + 1):
    # num = str(label_im0.tolist()).count(str(index))
    # roi0_list.append(num)
    new_mask1 = np.zeros(roi0.shape)
    new_mask2 = np.zeros(roi0.shape)
    # new_mask3 = np.zeros(roi0.shape)
    new_mask1[label_im0 == 1] = 1
    new_mask2[label_im0 == 2] = 1
    # new_mask3[label_im0 == 3] = 1
    # for index in range(1, nb_labels1 + 1):
    #     num = str(label_im1.tolist()).count(str(index))
    #     roi1_list.append(num)
    # for index in range(1, nb_labels2 + 1):
    #     num = str(label_im2.tolist()).count(str(index))
    #     roi2_list.append(num)

    # volumn = [np.sum(data0), np.sum(data1), np.sum(data2)]
    # roi = volumn.index(max(volumn[0], volumn[1], volumn[2]))
    # print(roi0_list, roi1_list, roi2_list)
    Imshow3DArray(Normalize01(t2),
                  roi=[Normalize01(new_mask1),
                       Normalize01(new_mask2)])
def GetPzRegion():
    root_folder = r'D:\ProblemData\Prcoessed'

    for case in os.listdir(root_folder):
        case_folder = os.path.join(root_folder, case)
        if not os.path.isdir(case_folder):
            continue

        print('Estimating PZ of {}'.format(case))
        wg_path = os.path.join(case_folder, 'prostate_roi.nii.gz')
        cg_path = os.path.join(case_folder, 'cg.nii')
        t2_path = os.path.join(case_folder, 't2.nii')
        if not os.path.exists(wg_path) and not os.path.exists(cg_path):
            continue

        wg_image, _, wg_data = LoadNiiData(wg_path, dtype=np.uint8)
        cg_image, _, cg_data = LoadNiiData(cg_path, dtype=np.uint8)

        # # Calculating PZ
        pz_data = wg_data - cg_data
        # print(np.unique(pz_data))
        pz_data[pz_data == 255] = 0

        # from MeDIT.Visualization import Imshow3DArray
        # from MeDIT.Normalize import Normalize01
        #
        # _, _, t2 = LoadNiiData(t2_path)
        #
        # Imshow3DArray(np.concatenate([Normalize01(t2), Normalize01(t2)], axis=1), roi=np.concatenate([pz_data0, pz_data], axis=1))
        #
        # print(np.unique(pz_data), np.unique(wg_data), np.unique(cg_data))

        # Save PZ image
        pz_image = GetImageFromArrayByImage(pz_data, wg_image)

        SaveNiiImage(os.path.join(case_folder, 'pz.nii'), pz_image)
Beispiel #27
0
def main():
    pass
    # random_params = {'stretch_x': 0.1, 'stretch_y': 0.1, 'shear': 0.1, 'rotate_z_angle': 20, 'horizontal_flip': True}
    # param_generator = AugmentParametersGenerator()
    # aug_generator = DataAugmentor2D()

    # from MeDIT.SaveAndLoad import LoadNiiData
    # _, _, data = LoadNiiData(data_path)
    # _, _, roi = LoadNiiData(roi_path)

    # data = data[..., data.shape[2] // 2]
    # roi = roi[..., roi.shape[2] // 2]

    # from Visualization import DrawBoundaryOfBinaryMask
    # from Normalize import Normalize01

    # while True:
    #     param_generator.RandomParameters(random_params)
    #     aug_generator.SetParameter(param_generator.GetRandomParametersDict())
    #
    #     new_data = aug_generator.Execute(data, interpolation_method='linear')
    #     new_roi = aug_generator.Execute(roi, interpolation_method='nearest')
    #     DrawBoundaryOfBinaryMask(Normalize01(new_data), new_roi)

    # Test ElasticAugment
    from MeDIT.SaveAndLoad import LoadNiiData
    from MeDIT.Visualization import Imshow3DArray
    import matplotlib.pyplot as plt
    image, _, data = LoadNiiData(
        r'C:\Users\yangs\Desktop\QIAN XING CHUN_siemens\QIAN XING CHUN\MR\20190101\140102.198000\MR20190101140046\005_t2_tse_tra_384_p2.nii'
    )
    # data = data[..., data.shape[-1] // 2]
    # plt.imshow(data, cmap='gray')
    # plt.show()
    while True:
        aug_data = ElasticAugment(
            data,
            num_controlpoints=4,
            std_deformation_sigma=3,
            proportion_to_augment=0.5,
        )

        # plt.imshow(np.concatenate((data, aug_data, np.abs(data - aug_data)), axis=1), cmap='gray')
        # plt.show()
        Imshow3DArray(aug_data[0] - data)
Beispiel #28
0
def test(resample_folder):
    case_list = os.listdir(resample_folder)
    row_list = []
    channel_list = []
    for case in case_list:
        case_path = os.path.join(resample_folder, case)
        roi_path = os.path.join(case_path, 'roi.nii')
        if not os.path.exists(roi_path):
            print('% has no roi'.format(case))
            continue

        _, roi, _ = LoadNiiData(roi_path)

        slice = SelectMaxRoiSlice(roi)
        # max_row, max_channel = GetRoiSize(roi[slice, ...])
        size = GetRoiSize(roi[slice, ...])
        if size[0] >= 100 or size[1] >= 100:
            print(case, ':', size)
def PredictNii():
    model_folder_path = model_path
    t2_folder = test_folder
    store_folder = r'D:\test'
    t2_list = os.listdir(t2_folder)

    prostate_segmentor = ProstatePzCgSegmentationInput_3()
    prostate_segmentor.LoadConfigAndModel(model_folder_path)

    for case in t2_list:
        print('Predicting ', case)
        case_path = os.path.join(t2_folder, case)
        store_path = os.path.join(store_folder, case)
        if not os.path.exists(store_path):
            os.mkdir(store_path)
        t2_path = os.path.join(case_path, 't2.nii')

        t2_image, _, t2_data = LoadNiiData(t2_path,
                                           dtype=np.float32,
                                           is_show_info=False)

        prostate_segmentor.Run(t2_image,
                               store_folder=os.path.join(
                                   store_path, 'prediction.nii'))
Beispiel #30
0
def GetDWIPath(case):
    print(case)
    if case == 'WYB^wu yi bao' or case == 'ZYB^zhang yun bao':
        return 0

    b_value = ['0', '50', '700', '750', '1400', '1500']
    case_path = os.path.join(process_folder, case)

    if os.path.exists(os.path.join(case_path, 'adc.nii')):
        if os.path.exists(os.path.join(case_path, 'dwi.nii')):
            bval_path = os.path.join(case_path, 'dwi.bval')
            bval = open(bval_path, 'r')
            b_list = bval.read().split()
            if len(b_list) == 1:
                new_img, new_dwi, _ = LoadNiiData(os.path.join(case_path, 'dwi.nii'))

            else:
                b, index = NearTrueB(b_list)
                _, dwi, _ = LoadNiiData(os.path.join(case_path, 'dwi.nii'))
                img, _, _ = LoadNiiData(os.path.join(case_path, 'adc.nii'))
                new_dwi = dwi[index, ...]
                new_img = sitk.GetImageFromArray(new_dwi)
                new_img.SetDirection(img.GetDirection())
                new_img.SetSpacing(img.GetSpacing())
                new_img.SetOrigin(img.GetOrigin())

        elif os.path.exists(os.path.join(case_path, 'dki.nii')):
            bval_path = os.path.join(case_path, 'dki.bval')
            bval = open(bval_path, 'r')
            b_list = bval.read().split()