请将我的LiTS2017数据集的图像和标签处理成2D的png格式,并且标签需要拆分成灰度图,背景灰度值0,肝脏灰度值1,肝脏肿瘤灰度值2,给出完整代码,我的LiTS2017数据集路径为C:\Users\Administrator\Desktop\LiTS2017,里面包含Training Batch 1文件夹和Training Batch 2文件夹,Training Batch 1文件夹里面有图像,图像的拓展名为.nii。Training Batch 2文件夹里面有标签,标签拓展名为.nii,保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,请帮我创建好对应文件夹,并且将转换好的保存到对应的文件夹
时间: 2023-11-27 22:49:41 浏览: 74
好的,以下是对应的代码:
```python
import os
import numpy as np
import nibabel as nib
from PIL import Image
# 创建保存文件夹
os.makedirs('C:/Users/Administrator/Desktop/2D-LiTS2017/images', exist_ok=True)
os.makedirs('C:/Users/Administrator/Desktop/2D-LiTS2017/labels', exist_ok=True)
# 读取数据
data_path = 'C:/Users/Administrator/Desktop/LiTS2017/'
train_batch1_path = os.path.join(data_path, 'Training Batch 1')
train_batch2_path = os.path.join(data_path, 'Training Batch 2')
# 处理图片数据
for i in range(131):
# 读取图像数据
image_file = os.path.join(train_batch1_path, f'volume-{i+1}.nii')
image_data = nib.load(image_file).get_fdata()
# 将图像数据保存为2D png格式
for j in range(image_data.shape[2]):
img = Image.fromarray(image_data[:, :, j])
img_path = os.path.join('C:/Users/Administrator/Desktop/2D-LiTS2017/images', f'image-{i+1}-{j+1}.png')
img.save(img_path)
# 处理标签数据
for i in range(131):
# 读取标签数据
label_file = os.path.join(train_batch2_path, f'segment-{i+1}.nii')
label_data = nib.load(label_file).get_fdata()
# 将标签数据拆分成灰度图
for j in range(label_data.shape[2]):
img_data = np.zeros((label_data.shape[0], label_data.shape[1]), dtype=np.uint8)
img_data[label_data[:, :, j] == 0] = 0 # 背景灰度值为0
img_data[label_data[:, :, j] == 1] = 1 # 肝脏灰度值为1
img_data[label_data[:, :, j] == 2] = 2 # 肝脏肿瘤灰度值为2
img = Image.fromarray(img_data)
img_path = os.path.join('C:/Users/Administrator/Desktop/2D-LiTS2017/labels', f'label-{i+1}-{j+1}.png')
img.save(img_path)
```
以上代码将会把你的LiTS2017数据集的图像和标签处理成2D的png格式,并且标签会被拆分成灰度图,背景灰度值0,肝脏灰度值1,肝脏肿瘤灰度值2,并保存到对应的文件夹中。
阅读全文