请将LiTS2017数据集的图像和标签处理成2D的png格式,并且标签需要拆分成灰度图,背景灰度值0,肝脏灰度值1,肝脏肿瘤灰度值2,给出完整代码,我的LiTS2017数据集路径为C:\Users\Administrator\Desktop\LiTS2017,里面包含Training Batch 1,其中里面有图像,图像格式为volume-0.nii。和Training Batch 2,其中里面有标签,标签格式为segmentation-0.nii,保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,里面有image和mask两个文件夹,请将转换好的保存到对应的文件夹
时间: 2023-09-13 18:10:41 浏览: 94
以下是将LiTS2017数据集的图像和标签处理成2D的png格式,并且标签拆分成灰度图的完整代码:
```python
import os
import numpy as np
import nibabel as nib
from PIL import Image
# 读取nii文件
def read_nii_file(file_path):
nii_file = nib.load(file_path)
nii_data = nii_file.get_fdata()
return nii_data
# 将3D图像转换成2D图像并保存为png格式
def convert_image_to_png(image_array, save_path):
if not os.path.exists(save_path):
os.makedirs(save_path)
for i in range(image_array.shape[2]):
image = image_array[:, :, i]
image = Image.fromarray(image).convert('L')
image.save(os.path.join(save_path, f'{i+1:03d}.png'))
# 将3D标签拆分成3个二值灰度图,并保存为png格式
def convert_label_to_png(label_array, save_path):
if not os.path.exists(save_path):
os.makedirs(save_path)
for i in range(label_array.shape[2]):
label = label_array[:, :, i]
liver = np.zeros(label.shape)
tumor = np.zeros(label.shape)
liver[label == 1] = 1
tumor[label == 2] = 1
combined_label = np.stack([liver, tumor], axis=-1)
combined_label = (combined_label * 255).astype(np.uint8)
Image.fromarray(combined_label).save(os.path.join(save_path, f'{i+1:03d}.png'))
# LiTS2017数据集路径
data_path = r'C:\Users\Administrator\Desktop\LiTS2017'
# Training Batch 1的图像路径
image_path = os.path.join(data_path, 'Training Batch 1', 'volume-0.nii')
image_array = read_nii_file(image_path)
image_save_path = r'C:\Users\Administrator\Desktop\2D-LiTS2017\image'
convert_image_to_png(image_array, image_save_path)
# Training Batch 2的标签路径
label_path = os.path.join(data_path, 'Training Batch 2', 'segmentation-0.nii')
label_array = read_nii_file(label_path)
label_save_path = r'C:\Users\Administrator\Desktop\2D-LiTS2017\mask'
convert_label_to_png(label_array, label_save_path)
```
执行上述代码后,将会在C:\Users\Administrator\Desktop\2D-LiTS2017目录下生成image和mask两个文件夹,分别包含转换好的2D图像和标签。其中,图像的文件名为001.png、002.png、003.png,依次类推;标签的文件名也是一样的。
阅读全文