BraTs2020数据集下载地址https://aistudio.baidu.com/datasetdetail/225057
这是文件目录,代码在proccess_code下面
批量转图片
import nibabel as nib
import matplotlib.pyplot as plt
import numpy as np
path = '../BraTS2020_TrainingData/MICCAI_BraTS2020_TrainingData/'
file_list = os.listdir(path)
file_list = file_list[146:]
print(file_list)
for file_item in file_list:
sub_path = os.path.join(path,file_item)
nii_list = os.listdir(sub_path)
for nii_item in nii_list:
if 't1.nii' in nii_item:
print(nii_item)
nii_path = os.path.join(sub_path,nii_item)
img = nib.load(nii_path)
# print(img.shape) # shape(240, 240, 155)
# print(img.header['db_name'])
width, height, queue = img.dataobj.shape # 由文件本身维度确定,可能是3维,也可能是4维
# print("width",width) # 240
# print("height",height) # 240
# print("queue",queue) # 155
# nib.viewers.OrthoSlicer3D(img.dataobj).show()
choice=[20, 30, 60 ,70, 100, 110, 140, 150 ]
num = 1
for i in range(0, queue, 10):
if i<50:
continue
if i>120:
break
# print(i)
# if i not in choice:
# num += 1
# continue
# print(i)
img_arr = img.dataobj[:, :, i]
# plt.subplot(5, 4, num)
plt.tight_layout()
plt.imshow(img_arr,)
plt.savefig("../t1/"+nii_item[:-4]+'_'+str(i)+'_.png')
num += 1
# plt.show()
elif 't2.nii' in nii_item:
nii_path = os.path.join(sub_path,nii_item)
img = nib.load(nii_path)
width, height, queue = img.dataobj.shape # 由文件本身维度确定,可能是3维,也可能是4维
choice=[20, 30, 60 ,70, 100, 110, 140, 150 ]
num = 1
for i in range(0, queue, 10):
if i<50:
continue
if i>120:
break
# print(i)
# if i not in choice:
# num += 1
# continue
# print(i)
plt.tight_layout()
img_arr = img.dataobj[:, :, i]
# plt.subplot(5, 4, num)
plt.imshow(img_arr, )
plt.savefig("../t2/"+nii_item[:-4]+'_'+str(i)+'_.png')
num += 1
# plt.show()
对图片批量切割然后resize到256*256
import os
import cv2
def crop_border(image, y_up,y_down,x_left,x_right):
height, width = image.shape[:2]
# border_height, border_width = border_size
cropped_image = image[y_up:height-y_down, x_left:width-x_right]
return cropped_image
# 读取图像
# image = cv2.imread('../t1/BraTS20_Training_001_t1_50_.png')
# 指定要切掉的边框大小
# border_size = (55, 120) # 假设要切掉上下左右各 10 个像素
y_up=59
y_down=53
x_left=144
x_right=127
# # 切割图像
# cropped_image = crop_border(image, y_up,y_down,x_left,x_right)
#
# # 显示切割后的图像
# cv2.imshow('Cropped Image', cropped_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()
#
# # 保存切割后的图像
# cv2.imwrite('cropped_image.jpg', cropped_image)
path = '../t1'
file_list = os.listdir(path)
for file in file_list:
subpath = os.path.join(path,file)
image = cv2.imread(subpath)
cropped_image = crop_border(image, y_up, y_down, x_left, x_right)
cropped_image = cv2.resize(cropped_image, (256, 256))
cv2.imwrite('../A/'+file, cropped_image)
path = '../t2'
file_list = os.listdir(path)
for file in file_list:
subpath = os.path.join(path,file)
image = cv2.imread(subpath)
cropped_image = crop_border(image, y_up, y_down, x_left, x_right)
cropped_image = cv2.resize(cropped_image, (256, 256))
cv2.imwrite('../B/'+file, cropped_image)