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 13:18:26 浏览: 58
YOLO目标检测+CCTSDB数据集已标注可以直接使用(4000张图像+对应VOC格式已标注txt、xml文件).rar
5星 · 资源好评率100%
好的,以下是Python代码实现该功能:
```python
import os
import numpy as np
import nibabel as nib
from PIL import Image
# 创建文件夹
if not os.path.exists('C:/Users/Administrator/Desktop/2D-LiTS2017'):
os.mkdir('C:/Users/Administrator/Desktop/2D-LiTS2017')
if not os.path.exists('C:/Users/Administrator/Desktop/2D-LiTS2017/train'):
os.mkdir('C:/Users/Administrator/Desktop/2D-LiTS2017/train')
if not os.path.exists('C:/Users/Administrator/Desktop/2D-LiTS2017/train/images'):
os.mkdir('C:/Users/Administrator/Desktop/2D-LiTS2017/train/images')
if not os.path.exists('C:/Users/Administrator/Desktop/2D-LiTS2017/train/labels'):
os.mkdir('C:/Users/Administrator/Desktop/2D-LiTS2017/train/labels')
# 读取数据集
data_dir = 'C:/Users/Administrator/Desktop/LiTS2017'
image_dir = os.path.join(data_dir, 'Training Batch 1')
label_dir = os.path.join(data_dir, 'Training Batch 2')
# 遍历图像文件夹,将3D图像切割成2D图像并保存到对应文件夹
for image_file in os.listdir(image_dir):
if image_file.endswith('.nii'):
image_path = os.path.join(image_dir, image_file)
label_path = os.path.join(label_dir, image_file.replace('_volume', '_segmentation'))
image_data = nib.load(image_path).get_fdata()
label_data = nib.load(label_path).get_fdata()
for z in range(image_data.shape[2]):
image_slice = image_data[:, :, z]
label_slice = label_data[:, :, z]
label_slice[label_slice == 1] = 255
label_slice[label_slice == 2] = 128
image_slice = np.stack([image_slice] * 3, axis=-1)
image_slice = Image.fromarray(image_slice.astype(np.uint8))
label_slice = Image.fromarray(label_slice.astype(np.uint8))
image_slice.save(f'C:/Users/Administrator/Desktop/2D-LiTS2017/train/images/{image_file[:-4]}_{z:03d}.png')
label_slice.save(f'C:/Users/Administrator/Desktop/2D-LiTS2017/train/labels/{image_file[:-4]}_{z:03d}.png')
```
运行完该代码后,你可以在`C:/Users/Administrator/Desktop/2D-LiTS2017/train/images`和`C:/Users/Administrator/Desktop/2D-LiTS2017/train/labels`文件夹中找到转换好的2D图像和标签。
阅读全文