LiTS2017数据集的路径为C:\Users\Administrator\Desktop\LiTS2017,将数据集的3D图像在z轴上切割成2D的三通道png格式图像,数据集的3D标签在z轴上切割成(要求背景灰度值0、肝脏灰度值1、肝脏肿瘤灰度值2的)2D的png格式标签。,LiTS2017数据集里面包含Training Batch 1和Training Batch 2两个文件夹,Training Batch 1文件夹里面有图像,图像的拓展名为.nii。Training Batch 2文件夹里面有标签,标签拓展名为.nii,保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,请帮我创建好对应文件夹,并且将转换好的保存到对应的文件夹
时间: 2024-01-22 07:18:30 浏览: 74
好的,以下是对应的Python代码实现:
```python
import os
import numpy as np
import nibabel as nib
from PIL import Image
# 数据集路径
data_path = r"C:\Users\Administrator\Desktop\LiTS2017"
# 保存路径
save_path = r"C:\Users\Administrator\Desktop\2D-LiTS2017"
# 创建保存路径
if not os.path.exists(save_path):
os.makedirs(save_path)
if not os.path.exists(os.path.join(save_path, "image")):
os.makedirs(os.path.join(save_path, "image"))
if not os.path.exists(os.path.join(save_path, "label")):
os.makedirs(os.path.join(save_path, "label"))
# 循环处理每个训练批次
for batch in range(1, 3):
print("Processing Batch %d..." % batch)
# 读取图像和标签
image_path = os.path.join(data_path, "Training Batch %d" % batch, "volume-*.nii")
label_path = os.path.join(data_path, "Training Batch %d" % batch, "segmentation-*.nii")
image_files = sorted(glob.glob(image_path))
label_files = sorted(glob.glob(label_path))
assert len(image_files) == len(label_files)
for i in range(len(image_files)):
# 读取图像和标签
image = nib.load(image_files[i]).get_fdata()
label = nib.load(label_files[i]).get_fdata()
# 将3D图像在z轴上切割成2D的三通道png格式图像
for z in range(image.shape[2]):
img_slice = image[:, :, z]
img_slice = np.stack([img_slice] * 3, axis=-1)
img_slice = (img_slice - np.min(img_slice)) / (np.max(img_slice) - np.min(img_slice)) * 255
img_slice = img_slice.astype(np.uint8)
# 将3D标签在z轴上切割成2D的png格式标签
label_slice = label[:, :, z]
label_slice = np.where(label_slice == 2, 2, np.where(label_slice == 1, 1, 0))
label_slice = label_slice.astype(np.uint8)
# 保存图像和标签
img_filename = os.path.join(save_path, "image", "batch%d_%04d.png" % (batch, z))
label_filename = os.path.join(save_path, "label", "batch%d_%04d.png" % (batch, z))
Image.fromarray(img_slice).save(img_filename)
Image.fromarray(label_slice).save(label_filename)
print("Done.")
```
这段代码会循环处理LiTS2017数据集中的每个训练批次,读取图像和标签,并将它们在z轴上切割成2D的三通道png格式图像和2D的png格式标签。然后,它将它们保存到对应的文件夹中。
阅读全文