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')
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])
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 FlattenImages(data_list, is_show=True): if len(data_list) == 1: return data_list[0] width = 1 if data_list[0].ndim == 2: row, col = data_list[0].shape for one_data in data_list: temp_row, temp_col = one_data.shape assert (temp_row == row and temp_col == col) while True: if width * width >= len(data_list): break else: width += 1 imshow_data = np.zeros((row * width, col * width)) case_index = range(0, len(data_list)) x, y = Index2XY(case_index, (width, width)) for x_index, y_index, index in zip(x, y, case_index): imshow_data[x_index * row:(x_index + 1) * row, y_index * col:(y_index + 1) * col] = data_list[index] if is_show: plt.imshow(Normalize01(imshow_data), cmap='gray') plt.show() return imshow_data elif data_list[0].ndim == 3: row, col, slice = data_list[0].shape for one_data in data_list: temp_row, temp_col, temp_slice = one_data.shape assert (temp_row == row and temp_col == col and temp_slice == slice) while True: if width * width >= len(data_list): break else: width += 1 imshow_data = np.zeros((row * width, col * width, slice)) case_index = range(0, len(data_list)) x, y = Index2XY(case_index, (width, width)) for x_index, y_index, index in zip(x, y, case_index): imshow_data[x_index * row:(x_index + 1) * row, y_index * col:(y_index + 1) * col, :] = data_list[index] if is_show: Imshow3DArray(Normalize01(imshow_data), cmap='gray') return imshow_data
def TestOneHot(): t2 = np.load(r'D:\ProblemData\StoreFormatData\CAI NING_0007947872\t2.npy') roi_onehot = np.load( r'D:\ProblemData\StoreFormatData\CAI NING_0007947872\roi_onehot.npy') print(type(t2), type(roi_onehot)) from MeDIT.Visualization import Imshow3DArray from MeDIT.Normalize import Normalize01 Imshow3DArray(Normalize01(t2), roi_onehot[..., 0]) Imshow3DArray(Normalize01(t2), roi_onehot[..., 1]) Imshow3DArray(Normalize01(t2), roi_onehot[..., 2])
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 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 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 = LoadImage(t2_path) _, _, cg = LoadImage(cg_path, dtype=np.uint8) _, _, wg = LoadImage(wg_path, dtype=np.uint8) Imshow3DArray(Normalize01(t2), roi=[Normalize01(cg), Normalize01(wg)])
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)
def CheckData(): import matplotlib.pyplot as plt from MeDIT.Normalize import Normalize01 # case_folder = r'D:\ZYH\Data\TZ roi\Input_0_Output_0\TzRoiAdd65\train' case_folder = r'D:\ZYH\Data\TZ roi\Input_0_output_downsample_3\FormatH5\test' case_list = os.listdir(case_folder) for i in range(len(case_list)): case_path = os.path.join(case_folder, case_list[i]) with h5py.File(case_path, 'r') as h5_file: image = np.asarray(h5_file['input_0'], dtype=np.float32) label0 = np.asarray(h5_file['output_0'], dtype=np.uint8) label1 = np.asarray(h5_file['output_1'], dtype=np.float32) label2 = np.asarray(h5_file['output_2'], dtype=np.uint8) plt.subplot(221) plt.imshow(Normalize01(image), cmap='gray') plt.title('{:.3f}-{:.3f}'.format(image.max(), image.min())) plt.subplot(222) plt.imshow((np.argmax(label0, axis=-1)), cmap='gray') plt.title('{}-{}, size:{}'.format(label0.max(), label0.min(), label0.shape)) plt.subplot(223) plt.imshow((np.argmax(label1, axis=-1)), cmap='gray') plt.title('{}-{}, size:{}'.format(label1.max(), label1.min(), label1.shape)) plt.subplot(224) plt.imshow((np.argmax(label2, axis=-1)), cmap='gray') plt.title('{}-{}, size:{}'.format(label2.max(), label2.min(), label2.shape)) plt.show()
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 MergeImageWithROI(data, roi): if data.ndim >= 3: print("Should input 2d image") return data if not isinstance(roi, list): roi = [roi] if len(roi) > 3: print('Only show 3 ROIs') return data data = np.asarray(Normalize01(data) * 255, dtype=np.uint8) kernel = np.ones((3, 3)) new_data = np.stack([data, data, data], axis=2) boundary = binary_dilation(input=roi[0], structure=kernel, iterations=1) - roi[0] index_x, index_y = np.where(boundary == 1) new_data[index_x, index_y, :] = 0 new_data[index_x, index_y, 0] = np.max(data) if len(roi) > 1: boundary = binary_dilation( input=roi[1], structure=kernel, iterations=1) - roi[1] index_x, index_y = np.where(boundary == 1) new_data[index_x, index_y, :] = 0 new_data[index_x, index_y, 1] = np.max(data) if len(roi) > 2: boundary = binary_dilation( input=roi[2], structure=kernel, iterations=1) - roi[2] index_x, index_y = np.where(boundary == 1) new_data[index_x, index_y, :] = 0 new_data[index_x, index_y, 2] = np.max(data) return new_data
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 AddBiasField(image, drop_ratio, center=[]): shape = image.shape field = BiasField(shape, center, drop_ratio) min_value = image.min() # new_image = np.multiply(field, image - min_value) + min_value new_image = field * Normalize01(image) return new_image, field
def TestResampleData(): roi_path = r'X:\PrcoessedData\ProstateCancerECE\ZJ^zhang jian\roi.nii' t2_path = r'X:\PrcoessedData\ProstateCancerECE\ZJ^zhang jian\t2.nii' dwi_path = r'X:\PrcoessedData\ProstateCancerECE\ZJ^zhang jian\dwi.nii' adc_path = r'X:\PrcoessedData\ProstateCancerECE\ZJ^zhang jian\adc.nii' from MeDIT.Visualization import Imshow3DArray from MeDIT.Normalize import Normalize01 _, _, t2 = LoadImage(t2_path, is_show_info=True) _, _, dwi = LoadImage(dwi_path, is_show_info=True) img, _, adc = LoadImage(adc_path, is_show_info=True) _, _, roi = LoadImage(roi_path, dtype=np.uint8, is_show_info=True) # new_dwi = dwi[..., 2] new_img = sitk.GetImageFromArray(new_dwi) new_img.SetDirection(img.GetDirection()) new_img.SetSpacing(img.GetSpacing()) new_img.SetOrigin(img.GetOrigin()) sitk.WriteImage( new_img, os.path.join(r'X:\PrcoessedData\ProstateCancerECE\ZJ^zhang jian', 'max_dwi.nii')) # Imshow3DArray(Normalize01(t2), roi=Normalize01(roi)) Imshow3DArray(Normalize01(dwi)) # Imshow3DArray(Normalize01(adc)) # TestResampleData() ###################################################### # for case in os.listdir(r'X:\PrcoessedData\BCR-ECE-score'): # case_folder = os.path.join(r'X:\PrcoessedData\BCR-ECE-score', case) # if len(os.listdir(case_folder)) < 1: # shutil.copytree(os.path.join(r'X:\RawData\BCR-ECE-score\BCR-ECE-score', case), os.path.join(r'C:\Users\ZhangYihong\Desktop\aaaa', case)) # for case in os.listdir(r'C:\Users\ZhangYihong\Desktop\aaaa\NoPath'): # if case not in os.listdir(r'X:\StoreFormatData\ProstateCancerECE\ResampleData'): # print(case) # # t2_1 = sitk.GetArrayFromImage(sitk.ReadImage(r'X:\RawData\BCR-ECE-score\BCR-ECE-score\CSJ^chen shi jie\dwi.nii')) # t2_2 = sitk.GetArrayFromImage(sitk.ReadImage(r'C:\Users\ZhangYihong\Desktop\aaaa\OriginalPath\CSJ^chen shi jie\dwi.nii')) # print((t2_2 == t2_1).all())
def ShowColorByROI(background_array, fore_array, roi, threshold_value=1e-6, color_map='rainbow', store_path='', is_show=True): if background_array.shape != roi.shape: print('Array and ROI must have same shape') return background_array = Normalize01(background_array) fore_array = Normalize01(fore_array) cmap = plt.get_cmap(color_map) rgba_array = cmap(fore_array) rgb_array = np.delete(rgba_array, 3, 2) print(background_array.shape) print(rgb_array.shape) index_roi_x, index_roi_y = np.where(roi < threshold_value) for index_x, index_y in zip(index_roi_x, index_roi_y): rgb_array[index_x, index_y, :] = background_array[index_x, index_y] plt.imshow(rgb_array) plt.axis('off') plt.gca().set_axis_off() plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0) plt.margins(0, 0) plt.gca().xaxis.set_major_locator(plt.NullLocator()) plt.gca().yaxis.set_major_locator(plt.NullLocator()) if store_path: plt.savefig(store_path, format='tif', dpi=300, bbox_inches='tight', pad_inches=0) plt.close() if is_show: plt.show() return rgb_array
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 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])
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])
def SegmentLungAxialSlice(image, threshold_value=-374): ''' This funtion segments the lungs from the given 2D slice. ''' # Convert into a binary image. image = Normalize01(image) binary = image < threshold_value # plt.imshow(binary, cmap=plt.cm.gray) # Remove the blobs connected to the border of the image cleared = clear_border(binary) # Label the image label_image = label(cleared) # Keep the labels with 2 largest areas areas = [r.area for r in regionprops(label_image)] areas.sort() if len(areas) > 2: for region in regionprops(label_image): if region.area < areas[-2]: for coordinates in region.coords: label_image[coordinates[0], coordinates[1]] = 0 binary = label_image > 0 # Closure operation with disk of radius 12 selem = disk(2) binary = binary_erosion(binary, selem) selem = disk(10) binary = binary_closing(binary, selem) # Fill in the small holes inside the lungs edges = roberts(binary) binary = ndi.binary_fill_holes(edges) # Superimpose the mask on the input image get_high_vals = binary == 0 mask = np.ones(np.shape(image)) mask[get_high_vals] = 0 return mask
def FlattenAllSlices(data, is_show=True): assert (data.ndim == 3) row, col, slice = data.shape width = 1 while True: if width * width >= slice: break else: width += 1 imshow_data = np.zeros((row * width, col * width)) slice_indexs = range(0, slice) x, y = Index2XY(slice_indexs, (width, width)) for x_index, y_index, slice_index in zip(x, y, slice_indexs): imshow_data[x_index * row:(x_index + 1) * row, y_index * col:(y_index + 1) * col] = data[..., slice_index] if is_show: plt.imshow(Normalize01(imshow_data), cmap='gray') plt.show() return imshow_data
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))
def MakeH5(): from MeDIT.SaveAndLoad import SaveH5 from MeDIT.Log import CustomerCheck from MeDIT.Visualization import LoadWaitBar from DataProcess.MaxPool import maxpooling source_root = r'D:\ProblemData\StoreFormatData' dest_root = r'D:\ProblemData\SuccessfulData' crop_shape = (320, 320, 3) # 如果进入网络是240x240 my_log = CustomerCheck(r'D:\ProblemData\SuccessfulData\zyh_log.csv') for case in os.listdir(source_root): case_folder = os.path.join(source_root, case) if not os.path.isdir(case_folder): continue print('Making {} for H5'.format(case)) t2_data = np.load(os.path.join(case_folder, 't2.npy')) roi_data = np.load(os.path.join(case_folder, 'roi_onehot.npy')) _, _, ignorance_list = Remove(roi_data) new_data = [] new_roi = [] for index, slice_index in enumerate(range(t2_data.shape[-1])): if index in ignorance_list or slice_index == 0 or slice_index == ( t2_data.shape[-1] - 1): pass else: LoadWaitBar(t2_data.shape[-1], index) print("\n") t2_slice_before_crop = CropT2Data(t2_data, crop_shape, slice_index - 1) t2_slice_after_crop = CropT2Data(t2_data, crop_shape, slice_index + 1) t2_crop = CropT2Data(t2_data, crop_shape, slice_index) roi_crop = CropRoiData(roi_data, crop_shape, slice_index) down_sample_once = maxpooling(roi_crop) down_sample_twice = maxpooling(down_sample_once) new_data.append(t2_crop) new_roi.append(roi_crop) file_name = os.path.join( dest_root, '{}-slicer_index_{}.h5'.format(case, slice_index)) SaveH5(file_name, [ t2_slice_before_crop, t2_crop, t2_slice_after_crop, roi_crop, down_sample_once, down_sample_twice ], [ 'input_0', 'input_1', 'input_2', 'output_0', 'output_1', 'output_2' ]) my_log.AddOne( '{}-slicer_index_{}.h5'.format(case, slice_index), ['', case_folder]) new_data_array = np.transpose(np.asarray(new_data, dtype=np.float32), (1, 2, 0)) pz_array = Normalize01( np.transpose( np.asarray(new_roi, dtype=np.uint8)[..., 1], (1, 2, 0))) cg_array = Normalize01( np.transpose( np.asarray(new_roi, dtype=np.uint8)[..., 2], (1, 2, 0))) Imshow3DArray(Normalize01(new_data_array), roi=[pz_array, cg_array])
from MeDIT.Normalize import Normalize01 import matplotlib.pyplot as plt def GetH5(file_path): with h5py.File(file_path, 'r') as h5_file: image = np.asarray(h5_file['input_0'], dtype=np.float32) label = np.asarray(h5_file['output_0'], dtype=np.uint8) return image, label file_path = r'D:\ZYH\Data\TZ roi\TypeOfData\FormatH5\Problem\Chen ren geng-slicer_index_8.h5' image, label = GetH5(file_path) # normalize new_data = Normalize01(image) zero = np.zeros(shape=image.shape) # add noise image_noise = random_noise(new_data, mode='gaussian', var=0.0025) # image_noise = random_noise(zero, mode='gaussian', var=0.09) noise = image_noise - new_data plt.subplot(121) plt.title('original') plt.axis('off') plt.imshow(new_data, cmap='gray') plt.subplot(122) plt.title('add noise')