def getMaskLabelValue(): """ get max mask value brats mask have four value:0,1,2,4(0 is backgroud ) :return: """ pathhgg_list = file_name_path(bratshgg_path) pathlgg_list = file_name_path(bratslgg_path) for subsetindex in range(len(pathhgg_list)): brats_subset_path = bratshgg_path + "/" + str( pathhgg_list[subsetindex]) + "/" mask_image = brats_subset_path + str( pathhgg_list[subsetindex]) + mask_name seg = sitk.ReadImage(mask_image, sitk.sitkUInt8) segimg = sitk.GetArrayFromImage(seg) seg_maskimage = segimg.copy() seg_maskimage = seg_maskimage.flatten() bcounts = np.bincount(seg_maskimage) print("mask_value:", bcounts) print('lgg') for subsetindex in range(len(pathlgg_list)): brats_subset_path = bratslgg_path + "/" + str( pathlgg_list[subsetindex]) + "/" mask_image = brats_subset_path + str( pathlgg_list[subsetindex]) + mask_name seg = sitk.ReadImage(mask_image, sitk.sitkUInt8) segimg = sitk.GetArrayFromImage(seg) seg_maskimage = segimg.copy() seg_maskimage = seg_maskimage.flatten() bcounts = np.bincount(seg_maskimage) print("mask_value:", bcounts)
def getImageSizeandSpacing(): """ get image and spacing :return: """ pathhgg_list = file_name_path(bratshgg_path) pathlgg_list = file_name_path(bratslgg_path) for subsetindex in range(len(pathhgg_list)): brats_subset_path = bratshgg_path + "/" + str( pathhgg_list[subsetindex]) + "/" flair_image = brats_subset_path + str( pathhgg_list[subsetindex]) + flair_name t1_image = brats_subset_path + str(pathhgg_list[subsetindex]) + t1_name t1ce_image = brats_subset_path + str( pathhgg_list[subsetindex]) + t1ce_name t2_image = brats_subset_path + str(pathhgg_list[subsetindex]) + t2_name flair_src = sitk.ReadImage(flair_image, sitk.sitkInt16) t1_src = sitk.ReadImage(t1_image, sitk.sitkInt16) t1ce_src = sitk.ReadImage(t1ce_image, sitk.sitkInt16) t2_src = sitk.ReadImage(t2_image, sitk.sitkInt16) print('subsetindex:', subsetindex) print("flair_src image size,flair_src image Spacing:", (flair_src.GetSize(), flair_src.GetSpacing())) print("t1_src image size,t1_src image Spacing:", (t1_src.GetSize(), t1_src.GetSpacing())) print("t1ce_src image size,t1ce_src image Spacing:", (t1ce_src.GetSize(), t1ce_src.GetSpacing())) print("t2_src image size,t2_src image Spacing:", (t2_src.GetSize(), t2_src.GetSpacing())) for subsetindex in range(len(pathlgg_list)): brats_subset_path = bratslgg_path + "/" + str( pathlgg_list[subsetindex]) + "/" flair_image = brats_subset_path + str( pathlgg_list[subsetindex]) + flair_name t1_image = brats_subset_path + str(pathlgg_list[subsetindex]) + t1_name t1ce_image = brats_subset_path + str( pathlgg_list[subsetindex]) + t1ce_name t2_image = brats_subset_path + str(pathlgg_list[subsetindex]) + t2_name flair_src = sitk.ReadImage(flair_image, sitk.sitkInt16) t1_src = sitk.ReadImage(t1_image, sitk.sitkInt16) t1ce_src = sitk.ReadImage(t1ce_image, sitk.sitkInt16) t2_src = sitk.ReadImage(t2_image, sitk.sitkInt16) print('subsetindex:', subsetindex) print("flair_src image size,flair_src image Spacing:", (flair_src.GetSize(), flair_src.GetSpacing())) print("t1_src image size,t1_src image Spacing:", (t1_src.GetSize(), t1_src.GetSpacing())) print("t1ce_src image size,t1ce_src image Spacing:", (t1ce_src.GetSize(), t1ce_src.GetSpacing())) print("t2_src image size,t2_src image Spacing:", (t2_src.GetSize(), t2_src.GetSpacing()))
def preparetraindata(): """ :return: """ bratshgg_path = "D:\Data\\brats18\HGG" bratslgg_path = "D:\Data\\brats18\LGG" trainImage = "D:\Data\\brats18\\train\Image" trainMask = "D:\Data\\brats18\\train\Mask" pathhgg_list = file_name_path(bratshgg_path) pathlgg_list = file_name_path(bratslgg_path) prepare3dtraindata(pathhgg_list, bratshgg_path, trainImage, trainMask, (64, 128, 128), 3, 15, 1) prepare3dtraindata(pathlgg_list, bratslgg_path, trainImage, trainMask, (64, 128, 128), 3, 15, 2)
def removekidneysmallobj(): """ 去除Vnet肾脏结果的小物体 :return: """ kits_path = "D:\Data\kits19\kits19test\kidney_modify" result_path = "D:\Data\kits19\kits19test\\kidney_modify\\" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(kits_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" images = [] index = 0 for _ in os.listdir(kits_subset_path): image = cv2.imread(kits_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) images.append(image) index += 1 ys_pd_array = np.array(images) ys_pd_array = np.reshape(ys_pd_array, (index, 512, 512)) ys_pd_sitk = sitk.GetImageFromArray(ys_pd_array) ys_pd_array = removesmallConnectedCompont(ys_pd_sitk, 0.2) ys_pd_array = np.clip(ys_pd_array, 0, 255).astype('uint8') sub_src_path = result_path + path_list[subsetindex] if not os.path.exists(sub_src_path): os.makedirs(sub_src_path) for i in range(np.shape(ys_pd_array)[0]): cv2.imwrite(sub_src_path + "/" + str(i) + ".bmp", ys_pd_array[i])
def tumor2d3dinkidney(): """ 保留肾脏区域范围内的肿瘤2d和3d结果 :return: """ tumor3d_path = "D:\Data\kits19\kits19test\\tumor3d" tumor2d_path = "D:\Data\kits19\kits19test\\tumor2d" kidney_path = "D:\Data\kits19\kits19test\kidney_modify" result_path = "D:\Data\kits19\kits19test\\tumor_modify1\\" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(tumor3d_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kidney_subset_path = kidney_path + "/" + str(path_list[subsetindex]) + "/" kits_subset_path = tumor3d_path + "/" + str(path_list[subsetindex]) + "/" tumor2d_subset_path = tumor2d_path + "/" + str(path_list[subsetindex]) + "/" kidneys = [] images = [] tumor2dmasks = [] index = 0 for _ in os.listdir(kits_subset_path): kidney = cv2.imread(kidney_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) image = cv2.imread(kits_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(tumor2d_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) kidneys.append(kidney) images.append(image) tumor2dmasks.append(mask) index += 1 kidneys_array = np.array(kidneys) kidneys_array = np.reshape(kidneys_array, (index, 512, 512)) kidneys_array_sitk = sitk.GetImageFromArray(kidneys_array) kidneys_array = morphologicaloperation(kidneys_array_sitk, 5, "dilate") tumor3d_array = np.array(images) tumor3d_array = np.reshape(tumor3d_array, (index, 512, 512)) tumor2d_array = np.array(tumor2dmasks) tumor2d_array = np.reshape(tumor2d_array, (index, 512, 512)) tumor3d_array = tumor3d_array & kidneys_array tumor2d_array = tumor2d_array & kidneys_array tumor_array = tumor3d_array | tumor2d_array tumor_array_sitk = sitk.GetImageFromArray(tumor_array) tumor_array = removesmallConnectedCompont(tumor_array_sitk, 0.1) tumor_array = np.clip(tumor_array, 0, 255).astype('uint8') sub_tumor_path = result_path + path_list[subsetindex] if not os.path.exists(sub_tumor_path): os.makedirs(sub_tumor_path) for i in range(np.shape(tumor_array)[0]): cv2.imwrite(sub_tumor_path + "/" + str(i) + ".bmp", tumor_array[i])
def preparesampling3dtraindata(heart_imagepath, heart_labelpath, trainImage, trainMask, shape=(16, 256, 256), subnumbers=1000): mask_path_list = file_name_path(heart_labelpath, False, True) image_path_list = file_name_path(heart_imagepath, False, True) newSpacing = (1.0, 1.0, 1.0) for subsetindex in range(len(image_path_list)): # step1 load src image with window center and window level,then resize to new Spacing file_image = heart_imagepath + "/" + str(image_path_list[subsetindex]) src = sitk.ReadImage(file_image, sitk.sitkInt16) _, src = resize_image_itk(src, newSpacing, src.GetSpacing(), sitk.sitkLinear) srcimg = sitk.GetArrayFromImage(src) # step2 load mask image ,then resize to new Spacing mask_path = heart_labelpath + "/" + str(mask_path_list[subsetindex]) seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) _, seg = resize_image_itk(seg, newSpacing, seg.GetSpacing(), sitk.sitkNearestNeighbor, False) segimg = sitk.GetArrayFromImage(seg) # step 3 normalize image srcimg = normalize(srcimg) # step 4 get subimages and submasks gen_image_mask(srcimg, segimg, subsetindex, shape=shape, subnumbers=subnumbers, trainImage=trainImage, trainMask=trainMask)
def analyse_image(input_path): image = "image" file_image_dir = input_path + "/" + image file_paths = file_name_path(file_image_dir, dir=False, file=True) size = [] for index in range(len(file_paths)): file_image_path = file_image_dir + "/" + file_paths[index] image = cv2.imread(file_image_path, 0) print(image.shape) size.append(np.array(image.shape)) print("mean size:", (np.mean(np.array(size), axis=0)))
def getImageSizeandSpacing(): """ get image and spacing :return: """ path_list = file_name_path(kits_path) for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name src = sitk.ReadImage(file_image, sitk.sitkInt16) imageSize = src.GetSize() imageSpacing = src.GetSpacing() print("image size,image spcing:", (imageSize, imageSpacing))
def getImageSizeandSpacing(): """ get image and spacing :return: """ mutilorgan_pathtmp = heart_path + "/" + image_name file_path_list = file_name_path(mutilorgan_pathtmp, False, True) for subsetindex in range(len(file_path_list)): mutilorgan_subset_path = mutilorgan_pathtmp + "/" + str(file_path_list[subsetindex]) src = sitk.ReadImage(mutilorgan_subset_path, sitk.sitkInt16) imageSize = src.GetSize() imageSpacing = src.GetSpacing() print("image size,image spcing:", (imageSize, imageSpacing))
def inference(): height = 512 width = 512 Vnet2d = BLVnet2dModule( 512, 512, channels=1, costname=("dice coefficient", ), inference=True, model_path="log\\tumor\diceVnet2d\model\BLVNet2ddiceloss.pd") tumor3d_path = "D:\Data\kits19\kits19test\kidney_modify" kits_path = "D:\Data\kits19\kits19test\src" tumor2d_path = "D:\Data\kits19\kits19test\\tumor2d" # step2 get all train image path_list = file_name_path(kits_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" kidney_mask_path = tumor3d_path + "/" + str( path_list[subsetindex]) + "/" tumor_mask_path = tumor2d_path + "/" + str( path_list[subsetindex]) + "/" index = 0 imagelist = [] masklist = [] for _ in os.listdir(kits_subset_path): image = cv2.imread(kits_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(kidney_mask_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) imagelist.append(image) masklist.append(mask) index += 1 imagearray = np.array(imagelist) imagearray = np.reshape(imagearray, (index, height, width)) maskarray = np.array(masklist) maskarray = np.reshape(maskarray, (index, height, width)) imagemask = np.zeros((index, height, width), np.uint8) for z in range(index): if np.max(maskarray[z]) != 0: imagemask[z, :, :] = Vnet2d.prediction(imagearray[z]) mask = imagemask.copy() mask[imagemask > 0] = 255 result = np.clip(mask, 0, 255).astype('uint8') if not os.path.exists(tumor_mask_path): os.makedirs(tumor_mask_path) for j in range(index): cv2.imwrite(tumor_mask_path + str(j) + ".bmp", result[j])
def preparesampling3dtraindata(heart_imagepath, heart_labelpath, trainImage, trainMask, shape=(96, 96, 96)): mask_path_list = file_name_path(heart_labelpath, False, True) image_path_list = file_name_path(heart_imagepath, False, True) newSize = shape for subsetindex in range(len(image_path_list)): # step1 load mask image ,then resize to new Spacing mask_path = heart_labelpath + "/" + str(mask_path_list[subsetindex]) seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) seg_array = sitk.GetArrayFromImage(seg) z_min, z_max = getRangImageRange(seg_array, 0) y_min, y_max = getRangImageRange(seg_array, 1) x_min, x_max = getRangImageRange(seg_array, 2) roi_seg = sitk.GetImageFromArray(seg_array[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]) roi_seg.SetOrigin(seg.GetOrigin()) roi_seg.SetSpacing(seg.GetSpacing()) roi_seg.SetDirection(seg.GetDirection()) _, roi_seg = resize_image_itkwithsize(roi_seg, newSize, roi_seg.GetSize(), sitk.sitkNearestNeighbor) segimg = sitk.GetArrayFromImage(roi_seg) # step2 load src image with window center and window level,then resize to new Spacing file_image = heart_imagepath + "/" + str(image_path_list[subsetindex]) src = sitk.ReadImage(file_image, sitk.sitkInt16) src_array = sitk.GetArrayFromImage(src) roi_src = sitk.GetImageFromArray(src_array[z_min:z_max + 1, y_min:y_max + 1, x_min:x_max + 1]) roi_src.SetOrigin(src.GetOrigin()) roi_src.SetSpacing(src.GetSpacing()) roi_src.SetDirection(src.GetDirection()) _, roi_src = resize_image_itkwithsize(roi_src, newSize, roi_src.GetSize(), sitk.sitkLinear) roi_src = ConvertitkTrunctedValue(roi_src, 600, -1000, True) srcimg = sitk.GetArrayFromImage(roi_src) # step 3 get subimages and submasks if not os.path.exists(trainImage): os.makedirs(trainImage) if not os.path.exists(trainMask): os.makedirs(trainMask) filepath1 = trainImage + "\\" + str(subsetindex) + ".npy" filepath = trainMask + "\\" + str(subsetindex) + ".npy" np.save(filepath1, srcimg) np.save(filepath, segimg)
def getMaskLabelMaxValue(): """ get max mask value kits mask have three value:0,1,2(0 is backgroud ,1 is kidney,2 is tumor) :return: """ path_list = file_name_path(kits_path) for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" mask_path = kits_subset_path + mask_name seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) segimg = sitk.GetArrayFromImage(seg) seg_maskimage = segimg.copy() max_value = np.max(seg_maskimage) print("max_mask_value:", max_value)
def getMaskLabelMaxValue(): """ get max mask value kits mask have three value:0,1,2(0 is backgroud ,1 is heart,2 is myocardium) :return: """ mutilorgan_pathtmp = heart_path + "/" + mask_name file_path_list = file_name_path(mutilorgan_pathtmp, False, True) for subsetindex in range(len(file_path_list)): mask_path = mutilorgan_pathtmp + "/" + str(file_path_list[subsetindex]) seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) segimg = sitk.GetArrayFromImage(seg) seg_maskimage = segimg.copy() max_value = np.max(seg_maskimage) print("max_mask_value:", max_value)
def getresizeImageSize(): """ get image and spacing :return: """ mutilorgan_pathtmp = heart_path file_path_list = file_name_path(mutilorgan_pathtmp, False, True) newSpacing = (1.0, 1.0, 1.0) for subsetindex in range(len(file_path_list)): mutilorgan_subset_path = mutilorgan_pathtmp + "/" + str(file_path_list[subsetindex]) src = sitk.ReadImage(mutilorgan_subset_path, sitk.sitkInt16) _, src = resize_image_itk(src, newSpacing, src.GetSpacing(), sitk.sitkLinear) imageSize = src.GetSize() imageSpacing = src.GetSpacing() print("image size,image spcing:", (imageSize, imageSpacing))
def remove2d3dtumorsmallobj(): """ 去除2d和3dVnet的肿瘤的小物体 :return: """ tumor3d_path = "D:\Data\kits19\kits19test\\tumor3d" tumor2d_path = "D:\Data\kits19\kits19test\\tumor2d" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(tumor3d_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = tumor3d_path + "/" + str(path_list[subsetindex]) + "/" tumor2d_subset_path = tumor2d_path + "/" + str(path_list[subsetindex]) + "/" images = [] tumor2dmasks = [] index = 0 for _ in os.listdir(kits_subset_path): image = cv2.imread(kits_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(tumor2d_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) images.append(image) tumor2dmasks.append(mask) index += 1 tumor3d_array = np.array(images) tumor3d_array = np.reshape(tumor3d_array, (index, 512, 512)) tumor2d_array = np.array(tumor2dmasks) tumor2d_array = np.reshape(tumor2d_array, (index, 512, 512)) tumor2d_array_sitk = sitk.GetImageFromArray(tumor2d_array) tumor2d_array = removesmallConnectedCompont(tumor2d_array_sitk, 0.2) tumor2d_array_sitk = sitk.GetImageFromArray(tumor3d_array) tumor3d_array = removesmallConnectedCompont(tumor2d_array_sitk, 0.2) tumor2d_array = np.clip(tumor2d_array, 0, 255).astype('uint8') tumor3d_array = np.clip(tumor3d_array, 0, 255).astype('uint8') sub_tumor3d_path = tumor3d_path + "/" + path_list[subsetindex] sub_tumor2d_path = tumor2d_path + "/" + path_list[subsetindex] if not os.path.exists(sub_tumor3d_path): os.makedirs(sub_tumor3d_path) if not os.path.exists(sub_tumor2d_path): os.makedirs(sub_tumor2d_path) for i in range(np.shape(tumor3d_array)[0]): cv2.imwrite(sub_tumor3d_path + "/" + str(i) + ".bmp", tumor3d_array[i]) cv2.imwrite(sub_tumor2d_path + "/" + str(i) + ".bmp", tumor2d_array[i])
def getImageSizeandSpacing(): """ get image and spacing :return: """ kits_Spacings = getImageSpacing() path_list = file_name_path(kits_path) for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name src = sitk.ReadImage(file_image, sitk.sitkInt16) imageSize = src.GetSize() for index in range(len(kits_Spacings)): if str(path_list[subsetindex]) == kits_Spacings[index][case_id]: widthspacing = kits_Spacings[index][width_spacing] thickspacing = kits_Spacings[index][slice_spacing] print("image size,widthspcing,thickspacing:", (imageSize, widthspacing, thickspacing))
def getTrunctedThresholdValue(): """ remove outside of liver region value,and expand the tumor range when normalization 0 to 1. calculate the overlap between liver mask and src image with range of lower and upper value. :return:None """ # step1 set threshold value upper = 300 lower = -200 num_points = 0.0 num_inliers = 0.0 # step2 get all train image path_list = file_name_path(kits_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name src = sitk.ReadImage(file_image, sitk.sitkInt16) srcimg = sitk.GetArrayFromImage(src) mask_path = kits_subset_path + mask_name seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) segimg = sitk.GetArrayFromImage(seg) seg_maskimage = segimg.copy() seg_maskimage[segimg > 0] = 255 inliers = 0 num_point = 0 for z in range(seg_maskimage.shape[0]): for y in range(seg_maskimage.shape[1]): for x in range(seg_maskimage.shape[2]): if seg_maskimage[z][y][x] != 0: num_point += 1 if (srcimg[z][y][x] < upper) and (srcimg[z][y][x] > lower): inliers += 1 # if not seg mask,not calculate if num_point != 0: print('{:.4}%'.format(inliers / num_point * 100)) num_points += num_point num_inliers += inliers print("all percent:", num_inliers / num_points)
def tumormodifyallmerge(): """ 将肾脏区域内的2d和3d肿瘤区域并集结果与2d和3d肿瘤交集结果相加 :return: """ tumor2_path = "D:\Data\kits19\kits19test\\tumor_modify2" tumor1_path = "D:\Data\kits19\kits19test\\tumor_modify1" result_path = "D:\Data\kits19\kits19test\\tumor_modify" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(tumor2_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset2_path = tumor2_path + "/" + str(path_list[subsetindex]) + "/" kits_subset1_path = tumor1_path + "/" + str(path_list[subsetindex]) + "/" images = [] masks = [] index = 0 for _ in os.listdir(kits_subset1_path): image = cv2.imread(kits_subset1_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(kits_subset2_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) images.append(image) masks.append(mask) index += 1 tumor3d_array = np.array(images) tumor3d_array = np.reshape(tumor3d_array, (index, 512, 512)) tumor2d_array = np.array(masks) tumor2d_array = np.reshape(tumor2d_array, (index, 512, 512)) tumor_array = tumor2d_array + tumor3d_array tumor_array = np.clip(tumor_array, 0, 255).astype('uint8') sub_tumor3d_path = result_path + "/" + path_list[subsetindex] if not os.path.exists(sub_tumor3d_path): os.makedirs(sub_tumor3d_path) for i in range(np.shape(tumor_array)[0]): cv2.imwrite(sub_tumor3d_path + "/" + str(i) + ".bmp", tumor_array[i])
def inference(): """ Vnet network segmentation kidney fine segmatation :return: """ channel = 1 numclass = 7 # step1 init vnet model imagex = 144 imagey = 112 imagez = 112 Vnet3d = Vnet3dModuleMultiLabel( imagey, imagex, imagez, channels=channel, numclass=numclass, costname=("categorical_dice", ), inference=True, model_path="log\VNetwithSize\categorical_focal_loss\model\Vnet3d.pd") heart_path = "E:\MedicalData\lung_lobe_Segmentation\\test\Image" out_path = "E:\MedicalData\lung_lobe_Segmentation\\test\Predict" # step1 get all test image path path_list = file_name_path(heart_path, dir=False, file=True) # step2 get test image(4 model) and mask for subsetindex in range(len(path_list)): subset_path = heart_path + "/" + str(path_list[subsetindex]) heart_src = sitk.ReadImage(subset_path, sitk.sitkInt16) heart_array = sitk.GetArrayFromImage(heart_src) ys_pd = Vnet3d.prediction(heart_array / 255.) ys_pd_sitk = sitk.GetImageFromArray(ys_pd) ys_pd_sitk.SetDirection(heart_src.GetDirection()) ys_pd_sitk.SetSpacing(heart_src.GetSpacing()) ys_pd_sitk.SetOrigin(heart_src.GetOrigin()) # step3 save output image out_mask_image = out_path + "/" + str(path_list[subsetindex]) sitk.WriteImage(ys_pd_sitk, out_mask_image)
def tumor2d3dmerge(): """ 求2d和3d交集的区域分别与2d和3d相连接的区域都保留下来 :return: """ tumor3d_path = "D:\Data\kits19\kits19test\\tumor3d" tumor2d_path = "D:\Data\kits19\kits19test\\tumor2d" tumor2d3d_path = "D:\Data\kits19\kits19test\\tumor2_3d" result_path = "D:\Data\kits19\kits19test\\tumor_modify2\\" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(tumor3d_path) # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = tumor3d_path + "/" + str(path_list[subsetindex]) + "/" tumor2d_subset_path = tumor2d_path + "/" + str(path_list[subsetindex]) + "/" tumor2d3d_subset_path = tumor2d3d_path + "/" + str(path_list[subsetindex]) + "/" images = [] tumor2dmasks = [] tumo2d3dmasks = [] index = 0 for _ in os.listdir(kits_subset_path): image = cv2.imread(kits_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(tumor2d_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) tumor = cv2.imread(tumor2d3d_subset_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) images.append(image) tumor2dmasks.append(mask) tumo2d3dmasks.append(tumor) index += 1 tumor3d_array = np.array(images) tumor3d_array = np.reshape(tumor3d_array, (index, 512, 512)) tumor2d_array = np.array(tumor2dmasks) tumor2d_array = np.reshape(tumor2d_array, (index, 512, 512)) tumor2d3d_array = np.array(tumo2d3dmasks) tumor2d3d_array = np.reshape(tumor2d3d_array, (index, 512, 512)) tumor_array = np.zeros((index, 512, 512), np.int) for z in range(index): tumor2d3d = tumor2d3d_array[z] if np.max(tumor2d3d) != 0: tumor2d3dlabels, tumor2d3dout = cv2.connectedComponents(tumor2d3d) tumor3d = tumor3d_array[z] tumor3dlabels, tumor3dout = cv2.connectedComponents(tumor3d) tumor2d = tumor2d_array[z] tumor2dlabels, tumor2dout = cv2.connectedComponents(tumor2d) for i in range(1, tumor2d3dlabels): tumor2d3doutmask = np.zeros(tumor2d3dout.shape, np.int) tumor2d3doutmask[tumor2d3dout == i] = 255 for j in range(1, tumor3dlabels): tumor3doutmask = np.zeros(tumor3dout.shape, np.int) tumor3doutmask[tumor3dout == j] = 255 if cv2.countNonZero(tumor2d3doutmask & tumor3doutmask): tumor_array[z] = tumor_array[z] + tumor3doutmask for k in range(1, tumor2dlabels): tumor2doutmask = np.zeros(tumor2dout.shape, np.int) tumor2doutmask[tumor2dout == k] = 255 if cv2.countNonZero(tumor2d3doutmask & tumor2doutmask): tumor_array[z] = tumor_array[z] + tumor2doutmask tumor2d_array_sitk = sitk.GetImageFromArray(tumor_array) tumor2d_array = removesmallConnectedCompont(tumor2d_array_sitk, 0.2) tumor_array = np.clip(tumor2d_array, 0, 255).astype('uint8') sub_tumor_path = result_path + path_list[subsetindex] if not os.path.exists(sub_tumor_path): os.makedirs(sub_tumor_path) for i in range(np.shape(tumor_array)[0]): cv2.imwrite(sub_tumor_path + "/" + str(i) + ".bmp", tumor_array[i])
def inference(): """ Vnet network segmentation brats fine segmatation :return: """ channel = 4 numclass = 4 flair_name = "_flair.nii.gz" t1_name = "_t1.nii.gz" t1ce_name = "_t1ce.nii.gz" t2_name = "_t2.nii.gz" mask_name = "_seg.nii.gz" out_mask_name = "_outseg.nii.gz" # step1 init vnet model depth_z = 48 Vnet3d = Vnet3dModuleMultiLabel( 240, 240, depth_z, channels=channel, numclass=numclass, costname=("categorical_dice", ), inference=True, model_path= "log\segmeation2mm\weighted_categorical_crossentropy\model\Vnet3d.pd-10000" ) brats_path = "D:\Data\\brats18\\test" # step2 get all test image path dice_values0 = [] dice_values1 = [] dice_values2 = [] dice_values3 = [] path_list = file_name_path(brats_path) # step3 get test image(4 model) and mask for subsetindex in range(len(path_list)): # step4 load test image(4 model) and mask as ndarray brats_subset_path = brats_path + "/" + str( path_list[subsetindex]) + "/" flair_image = brats_subset_path + str( path_list[subsetindex]) + flair_name t1_image = brats_subset_path + str(path_list[subsetindex]) + t1_name t1ce_image = brats_subset_path + str( path_list[subsetindex]) + t1ce_name t2_image = brats_subset_path + str(path_list[subsetindex]) + t2_name mask_image = brats_subset_path + str( path_list[subsetindex]) + mask_name flair_src = sitk.ReadImage(flair_image, sitk.sitkInt16) t1_src = sitk.ReadImage(t1_image, sitk.sitkInt16) t1ce_src = sitk.ReadImage(t1ce_image, sitk.sitkInt16) t2_src = sitk.ReadImage(t2_image, sitk.sitkInt16) mask = sitk.ReadImage(mask_image, sitk.sitkUInt8) flair_array = sitk.GetArrayFromImage(flair_src) t1_array = sitk.GetArrayFromImage(t1_src) t1ce_array = sitk.GetArrayFromImage(t1ce_src) t2_array = sitk.GetArrayFromImage(t2_src) label = sitk.GetArrayFromImage(mask) # step5 mormazalation test image(4 model) and merage to 4 channels ndarray flair_array = normalize(flair_array) t1_array = normalize(t1_array) t1ce_array = normalize(t1ce_array) t2_array = normalize(t2_array) imagez, height, width = np.shape(flair_array)[0], np.shape( flair_array)[1], np.shape(flair_array)[2] fourmodelimagearray = np.zeros((imagez, height, width, channel), np.float) fourmodelimagearray[:, :, :, 0] = flair_array fourmodelimagearray[:, :, :, 1] = t1_array fourmodelimagearray[:, :, :, 2] = t1ce_array fourmodelimagearray[:, :, :, 3] = t2_array ys_pd_array = np.zeros((imagez, height, width), np.uint8) # step6 predict test image(4 model) last_depth = 0 for depth in range(0, imagez // depth_z, 1): patch_xs = fourmodelimagearray[depth * depth_z:(depth + 1) * depth_z, :, :, :] pathc_pd = Vnet3d.prediction(patch_xs) ys_pd_array[depth * depth_z:(depth + 1) * depth_z, :, :] = pathc_pd last_depth = depth if imagez != depth_z * last_depth: patch_xs = fourmodelimagearray[(imagez - depth_z):imagez, :, :, :] pathc_pd = Vnet3d.prediction(patch_xs) ys_pd_array[(imagez - depth_z):imagez, :, :] = pathc_pd ys_pd_array = np.clip(ys_pd_array, 0, 255).astype('uint8') all_ys_pd_array = ys_pd_array.copy() all_ys_pd_array[ys_pd_array != 0] = 1 outmask = getLargestConnectedCompont( sitk.GetImageFromArray(all_ys_pd_array)) ys_pd_array[outmask == 0] = 0 # step7 calcu test mask and predict mask dice value batch_ys = label.copy() batch_ys[label == 4] = 3 dice_value0 = 0 dice_value1 = 0 dice_value2 = 0 dice_value3 = 0 for num_class in range(4): ys_pd_array_tmp = ys_pd_array.copy() batch_ys_tmp = batch_ys.copy() ys_pd_array_tmp[ys_pd_array == num_class] = 1 batch_ys_tmp[label == num_class] = 1 if num_class == 0: dice_value0 = calcu_dice(ys_pd_array_tmp, batch_ys_tmp, 1) if num_class == 1: dice_value1 = calcu_dice(ys_pd_array_tmp, batch_ys_tmp, 1) if num_class == 2: dice_value2 = calcu_dice(ys_pd_array_tmp, batch_ys_tmp, 1) if num_class == 3: dice_value3 = calcu_dice(ys_pd_array_tmp, batch_ys_tmp, 1) print( "index,dice:", (subsetindex, dice_value0, dice_value1, dice_value2, dice_value3)) dice_values0.append(dice_value0) dice_values1.append(dice_value1) dice_values2.append(dice_value2) dice_values3.append(dice_value3) # step8 out put predict mask ys_pd_array = ys_pd_array.astype('float') outputmask = np.zeros((imagez, height, width), np.uint8) outputmask[ys_pd_array == 1] = 1 outputmask[ys_pd_array == 2] = 2 outputmask[ys_pd_array == 3] = 4 ys_pd_itk = sitk.GetImageFromArray(outputmask) ys_pd_itk.SetSpacing(mask.GetSpacing()) ys_pd_itk.SetOrigin(mask.GetOrigin()) ys_pd_itk.SetDirection(mask.GetDirection()) out_mask_image = brats_subset_path + str( path_list[subsetindex]) + out_mask_name sitk.WriteImage(ys_pd_itk, out_mask_image) average0 = sum(dice_values0) / len(dice_values0) average1 = sum(dice_values1) / len(dice_values1) average2 = sum(dice_values2) / len(dice_values2) average3 = sum(dice_values3) / len(dice_values3) print("average dice:", (average0, average1, average2, average3))
def inference1mm(): """ Vnet network segmentation kidney fine segmatation :return: """ channel = 1 numclass = 3 newSpacing = (1.0, 1.0, 1.0) # step1 init vnet model imagex = 256 imagey = 256 imagez = 208 Vnet3d = mutildepthVnet3dModuleMultiLabel( imagex, imagey, imagez, channels=channel, numclass=numclass, costname=("categorical_dice", ), inference=True, model_path="log\mutildepthVnet\categorical_dice\model\Vnet3d.pd") heart_path = "E:\MedicalData\HVSMR2016\cropedHeart\Test dataset" out_path = "E:\MedicalData\HVSMR2016\cropedHeart\Test_predict" # step2 get all test image path path_list = file_name_path(heart_path, dir=False, file=True) # step3 get test image(4 model) and mask for subsetindex in range(len(path_list)): # step4 load test image as ndarray subset_path = heart_path + "/" + str(path_list[subsetindex]) heart_src = sitk.ReadImage(subset_path, sitk.sitkInt16) srcSpacing = heart_src.GetSpacing() srcOrigin = heart_src.GetOrigin() srcSize = heart_src.GetSize() srcDirection = heart_src.GetDirection() zspacing, xpacing, yspacing = srcSpacing[2], srcSpacing[0], srcSpacing[ 1] _, heart_src = resize_image_itk(heart_src, newSpacing=newSpacing, originSpcaing=(xpacing, yspacing, zspacing), resamplemethod=sitk.sitkLinear) heart_array = sitk.GetArrayFromImage(heart_src) # step5 mormazalation test image heart_array = normalize(heart_array) depthz, heighty, widthx = np.shape(heart_array)[0], np.shape( heart_array)[1], np.shape(heart_array)[2] vnetinputarray = np.zeros((imagez, imagey, imagex, channel), np.float) vnetinputarray[0:depthz, 0:heighty, 0:widthx, 0] = heart_array # step6 predict test image Vnet3d_array = Vnet3d.prediction(vnetinputarray) ys_pd_array = Vnet3d_array[0:depthz, 0:heighty, 0:widthx] ys_pd_sitk = sitk.GetImageFromArray(ys_pd_array) ys_pd_sitk.SetSpacing(heart_src.GetSpacing()) ys_pd_sitk.SetOrigin(heart_src.GetOrigin()) ys_pd_sitk.SetDirection(heart_src.GetDirection()) # step7.1 resample output to origin size _, ys_pd_sitk = resize_image_itk( ys_pd_sitk, newSpacing=(xpacing, yspacing, zspacing), originSpcaing=newSpacing, resamplemethod=sitk.sitkNearestNeighbor, flag=False) # 7.2 make sure output size is same as input size ys_pd_array = sitk.GetArrayFromImage(ys_pd_sitk) ys_array = np.zeros((srcSize[2], srcSize[1], srcSize[0]), 'uint8') ys_array[0:np.shape(ys_pd_array)[0], 0:np.shape(ys_pd_array)[1], 0:np.shape(ys_pd_array)[2]] = ys_pd_array # step8 out put predict mask ys_array = ys_array.astype('uint8') ys_pd_itk = sitk.GetImageFromArray(ys_array) ys_pd_itk.SetSpacing(srcSpacing) ys_pd_itk.SetOrigin(srcOrigin) ys_pd_itk.SetDirection(srcDirection) out_mask_image = out_path + "/mask" + str(path_list[subsetindex]) sitk.WriteImage(ys_pd_itk, out_mask_image)
def inference(): """ Vnet network segmentation kidney corse segmatation,get range of kidney Course segmentation,resize image to fixed size,segmentation the mask and get mask range :return: """ depth_z = 64 height = 256 Vnet3d = Vnet3dModule( height, height, depth_z, channels=1, costname=("dice coefficient", ), inference=True, model_path="log\segmeation\CoarseVNet\model\Vnet3d.pd") fixed_size = [depth_z, height, height] kits_path = "D:\Data\kits19\kits19\\test" image_name = "imaging.nii.gz" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(kits_path) file_name = "kidneyrang.txt" out = open(file_name, 'w') # step3 get signal train image and mask for subsetindex in range(len(path_list)): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name # 1 load itk image and truncate value with upper and lower src = load_itkfilewithtrucation(file_image, 300, -200) originSize = src.GetSize() originSpacing = src.GetSpacing() thickspacing, widthspacing = originSpacing[0], originSpacing[1] # 2 change image size to fixed size(512,512,64) _, src = resize_image_itkwithsize( src, newSize=fixed_size, originSize=originSize, originSpcaing=[thickspacing, widthspacing, widthspacing], resamplemethod=sitk.sitkLinear) # 3 get resample array(image and segmask) srcimg = sitk.GetArrayFromImage(src) srcimg = np.swapaxes(srcimg, 0, 2) ys_pd_array = Vnet3d.prediction(srcimg) ys_pd_array = np.clip(ys_pd_array, 0, 255).astype('uint8') ys_pd_array = np.swapaxes(ys_pd_array, 0, 2) ys_pd_itk = sitk.GetImageFromArray(ys_pd_array) ys_pd_itk.SetSpacing(src.GetSpacing()) ys_pd_itk.SetOrigin(src.GetOrigin()) ys_pd_itk.SetDirection(src.GetDirection()) _, ys_pd_itk = resize_image_itkwithsize( ys_pd_itk, newSize=originSize, originSize=fixed_size, originSpcaing=[ src.GetSpacing()[0], src.GetSpacing()[1], src.GetSpacing()[2] ], resamplemethod=sitk.sitkNearestNeighbor) pd_array = sitk.GetArrayFromImage(ys_pd_itk) print(np.shape(pd_array)) # 4 get range of corse kidney expandslice = 5 startpostion, endpostion = getRangImageDepth(pd_array) if startpostion == endpostion: print("corse error") imagez = np.shape(pd_array)[2] startpostion = startpostion - expandslice endpostion = endpostion + expandslice if startpostion < 0: startpostion = 0 if endpostion > imagez: endpostion = imagez print("casenaem:", path_list[subsetindex]) print("startposition:", startpostion) print("endpostion:", endpostion) out.writelines(path_list[subsetindex] + "," + str(startpostion) + "," + str(endpostion) + "\n")
def outputresult(): """ 将最后肾脏结果和肿瘤结果输出成比赛结果 :return: """ kits_path = "D:\Data\kits19\kits19\\test_data" kidney_path = "D:\Data\kits19\kits19test\kidney_modify" tumor_path = "D:\Data\kits19\kits19test\\tumor_modify" image_name = "imaging.nii.gz" result_path = "D:\Data\kits19\kits19" height, width = 512, 512 """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(kits_path) read = open("kidneyrang.txt", 'r') # step3 get signal train image and mask for subsetindex in range(len(path_list)): line = read.readline() line = line.split(',') casename = line[0] start = int(line[1]) end = int(line[2][0:-1]) kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name kidney_mask_path = kidney_path + "/" + str(path_list[subsetindex]) + "/" tumor_mask_path = tumor_path + "/" + str(path_list[subsetindex]) + "/" index = 0 kidneylist = [] tumorlist = [] for _ in os.listdir(kidney_mask_path): image = cv2.imread(kidney_mask_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) mask = cv2.imread(tumor_mask_path + "/" + str(index) + ".bmp", cv2.IMREAD_GRAYSCALE) kidneylist.append(image) tumorlist.append(mask) index += 1 kidneyarray = np.array(kidneylist) kidneyarray = np.reshape(kidneyarray, (index, height, width)) tumorarray = np.array(tumorlist) tumorarray = np.reshape(tumorarray, (index, height, width)) outmask = np.zeros((index, height, width), np.uint8) outmask[kidneyarray == 255] = 1 outmask[tumorarray == 255] = 2 # 1 load itk image and truncate value with upper and lower and get rang kideny region src = load_itkfilewithtrucation(file_image, 300, -200) originSize = src.GetSize() originSpacing = src.GetSpacing() thickspacing, widthspacing = originSpacing[0], originSpacing[1] outmask = np.swapaxes(outmask, 0, 2) mask_sitk = sitk.GetImageFromArray(outmask) mask_sitk.SetSpacing((1.0, widthspacing, widthspacing)) mask_sitk.SetOrigin(src.GetOrigin()) mask_sitk.SetDirection(src.GetDirection()) # 2 change z spacing >1.0 to originspacing if thickspacing > 1.0: _, mask_sitk = resize_image_itk(mask_sitk, newSpacing=(thickspacing, widthspacing, widthspacing), originSpcaing=(1.0, widthspacing, widthspacing), resamplemethod=sitk.sitkLinear) else: mask_sitk.SetSpacing(originSpacing) src_mask_array = np.zeros((originSize[0], height, width), np.uint8) mask_array = sitk.GetArrayFromImage(mask_sitk) mask_array = np.swapaxes(mask_array, 0, 2) # make sure the subregion have same size if (end - start) != np.shape(mask_array)[0]: start = start end = start + np.shape(mask_array)[0] if end > originSize[0]: end = originSize[0] start = end - np.shape(mask_array)[0] src_mask_array[start:end] = mask_array src_mask_array = np.swapaxes(src_mask_array, 0, 2) mask_itk = sitk.GetImageFromArray(src_mask_array) mask_itk.SetSpacing(originSpacing) mask_itk.SetOrigin(src.GetOrigin()) mask_itk.SetDirection(src.GetDirection()) mask_name = result_path + "/" + "prediction" + casename[4:10] + ".nii.gz" sitk.WriteImage(mask_itk, mask_name)
def proKitsdata(): expandslice = 5 kits_path = "E:\junqiangchen\data\kits19\kits19\data" image_name = "imaging.nii.gz" mask_name = "segmentation.nii.gz" case_id = 'case_id' width_spacing = 'captured_pixel_width' slice_spacing = 'captured_slice_thickness' proImage = "E:\junqiangchen\data\kits19\kits19process\Image\\" proMask = "E:\junqiangchen\data\kits19\kits19process\Mask\\" protumorImage = "E:\junqiangchen\data\kits19\kits19tumorprocess\Image\\" protumorMask = "E:\junqiangchen\data\kits19\kits19tumorprocess\Mask\\" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ seriesindex = 0 # step2 get all train image path_list = file_name_path(kits_path) kits_Spacings = getImageSpacing() # step3 get signal train image and mask for subsetindex in range(0, 210, 1): kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" #kits_subset_path = kits_path + "/" + "case_00160" + "/" file_image = kits_subset_path + image_name # 1 load itk image and truncate value with upper and lower src = load_itkfilewithtrucation(file_image, 300, -200) mask_path = kits_subset_path + mask_name seg = sitk.ReadImage(mask_path, sitk.sitkUInt8) for space_index in range(len(kits_Spacings)): if str(path_list[subsetindex] ) == kits_Spacings[space_index][case_id]: widthspacing = kits_Spacings[space_index][width_spacing] thickspacing = kits_Spacings[space_index][slice_spacing] break # 2 change z spacing >1.0 to 1.0 if thickspacing > 1.0: _, seg = resize_image_itk( seg, newSpacing=(1.0, widthspacing, widthspacing), originSpcaing=(thickspacing, widthspacing, widthspacing), resamplemethod=sitk.sitkNearestNeighbor) _, src = resize_image_itk( src, newSpacing=(1.0, widthspacing, widthspacing), originSpcaing=(thickspacing, widthspacing, widthspacing), resamplemethod=sitk.sitkLinear) # 3 get resample array(image and segmask) segimg = sitk.GetArrayFromImage(seg) print(segimg.shape) segimg = np.swapaxes(segimg, 0, 2) print(segimg.shape) srcimg = sitk.GetArrayFromImage(src) srcimg = np.swapaxes(srcimg, 0, 2) trainimagefile = proImage + str(seriesindex) trainMaskfile = proMask + str(seriesindex) if not os.path.exists(trainimagefile): os.makedirs(trainimagefile) if not os.path.exists(trainMaskfile): os.makedirs(trainMaskfile) tumorimagefile = protumorImage + str(seriesindex) tumorMaskfile = protumorMask + str(seriesindex) if not os.path.exists(tumorimagefile): os.makedirs(tumorimagefile) if not os.path.exists(tumorMaskfile): os.makedirs(tumorMaskfile) # 4 get mask seg_kineryimage = segimg.copy() seg_kineryimage[segimg > 0] = 255 gen_subregion(srcimg, seg_kineryimage, trainimagefile, trainMaskfile, expandslice) seg_kinerytumorimage = segimg.copy() seg_kinerytumorimage[segimg == 2] = 255 gen_subregion(srcimg, seg_kinerytumorimage, tumorimagefile, tumorMaskfile, expandslice) seriesindex += 1
def inference(): """ Vnet network segmentation kidney fine segmatation :return: """ depth_z = 32 Vnet3d = Vnet3dModule(512, 512, depth_z, channels=1, costname=("dice coefficient", ), inference=True, model_path="log\segmeation\VNet\model\Vnet3d.pd") kits_path = "D:\Data\kits19\kits19\\test" image_name = "imaging.nii.gz" result_path = "D:\Data\kits19\kits19test" """ load itk image,change z Spacing value to 1,and save image ,liver mask ,tumor mask :return:None """ # step2 get all train image path_list = file_name_path(kits_path) read = open("kidneyrang.txt", 'r') # step3 get signal train image and mask for subsetindex in range(len(path_list)): line = read.readline() line = line.split(',') casename = line[0] start = int(line[1]) end = int(line[2][0:-1]) kits_subset_path = kits_path + "/" + str(path_list[subsetindex]) + "/" file_image = kits_subset_path + image_name # 1 load itk image and truncate value with upper and lower and get rang kideny region src = load_itkfilewithtrucation(file_image, 300, -200) originSpacing = src.GetSpacing() src_array = sitk.GetArrayFromImage(src) sub_src_array = src_array[:, :, start:end] sub_src = sitk.GetImageFromArray(sub_src_array) sub_src.SetSpacing(originSpacing) print(sub_src.GetSize()) thickspacing, widthspacing = originSpacing[0], originSpacing[1] # 2 change z spacing >1.0 to 1.0 if thickspacing > 1.0: _, sub_src = resize_image_itk( sub_src, newSpacing=(1.0, widthspacing, widthspacing), originSpcaing=(thickspacing, widthspacing, widthspacing), resamplemethod=sitk.sitkLinear) xs_array = sitk.GetArrayFromImage(sub_src) xs_array = np.swapaxes(xs_array, 0, 2) index = np.shape(xs_array)[0] ys_pd_array = np.zeros(np.shape(xs_array), np.uint8) last_depth = 0 for depth in range(0, index // depth_z, 1): patch_xs = xs_array[depth * depth_z:(depth + 1) * depth_z, :, :] pathc_pd = Vnet3d.prediction(patch_xs) ys_pd_array[depth * depth_z:(depth + 1) * depth_z, :, :] = pathc_pd last_depth = depth if index != depth_z * last_depth: patch_xs = xs_array[(index - depth_z):index, :, :] pathc_pd = Vnet3d.prediction(patch_xs) ys_pd_array[(index - depth_z):index, :, :] = pathc_pd ys_pd_sitk = sitk.GetImageFromArray(ys_pd_array) ys_pd_array = removesmallConnectedCompont(ys_pd_sitk, 0.2) ys_pd_array = np.clip(ys_pd_array, 0, 255).astype('uint8') sub_src_path = result_path + "/src/" + casename sub_pred_path = result_path + "/kidney_modify/" + casename if not os.path.exists(sub_src_path): os.makedirs(sub_src_path) if not os.path.exists(sub_pred_path): os.makedirs(sub_pred_path) for i in range(np.shape(xs_array)[0]): cv2.imwrite(sub_src_path + "/" + str(i) + ".bmp", xs_array[i]) cv2.imwrite(sub_pred_path + "/" + str(i) + ".bmp", ys_pd_array[i])