LiTS2017数据集的路径为C:\Users\Administrator\Desktop\LiTS2017,将数据集的图像和标签都变成2D的png格式,其中标签灰度图设置成背景灰度值0,肝脏灰度值1,肝脏肿瘤灰度值2,LiTS2017数据集里面包含Training Batch 1和Training Batch 2两个文件夹,Training Batch 1文件夹里面有图像,图像的拓展名为.nii。Training Batch 2文件夹里面有标签,标签拓展名为.nii,保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,请帮我创建好对应文件夹,并且将转换好的保存到对应的文件夹
时间: 2023-11-27 14:49:56 浏览: 232
好的,以下是Python代码实现:
```python
import os
import numpy as np
import nibabel as nib
from PIL import Image
# 设置数据集路径
data_path = "C:/Users/Administrator/Desktop/LiTS2017"
save_path = "C:/Users/Administrator/Desktop/2D-LiTS2017"
# 创建保存转换后数据的文件夹
if not os.path.exists(save_path):
os.makedirs(save_path)
# 循环遍历Training Batch 1文件夹中的所有图像
for file_name in os.listdir(os.path.join(data_path, "Training Batch 1")):
if file_name.endswith(".nii"):
# 加载nii格式的图像
img = nib.load(os.path.join(data_path, "Training Batch 1", file_name)).get_fdata()
# 将三维图像转换为二维图像
img_2d = np.squeeze(np.max(img, axis=0))
# 将图像转换为灰度图并保存为png格式
img_png = Image.fromarray(img_2d).convert('L')
img_png.save(os.path.join(save_path, os.path.splitext(file_name)[0] + ".png"))
# 循环遍历Training Batch 2文件夹中的所有标签
for file_name in os.listdir(os.path.join(data_path, "Training Batch 2")):
if file_name.endswith(".nii"):
# 加载nii格式的标签
label = nib.load(os.path.join(data_path, "Training Batch 2", file_name)).get_fdata()
# 将三维标签转换为二维标签
label_2d = np.squeeze(np.max(label, axis=0))
# 将标签中肝脏和肝脏肿瘤区域的像素值设置为1和2,背景像素值设置为0
label_2d[label_2d == 1] = 255
label_2d[label_2d == 2] = 127
# 将标签转换为灰度图并保存为png格式
label_png = Image.fromarray(label_2d.astype('uint8')).convert('L')
label_png.save(os.path.join(save_path, os.path.splitext(file_name)[0] + ".png"))
```
上述代码将在指定路径下创建名为2D-LiTS2017的文件夹,并将转换好的2D图像和标签保存到该文件夹中。其中,图像和标签的文件名与原始的.nii文件名相同,只是拓展名从.nii变为.png。在标签转换的过程中,将标签中肝脏和肝脏肿瘤区域的像素值设置为1和2,背景像素值设置为0,以便在后续的训练中使用。
相关推荐
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![txt](https://img-home.csdnimg.cn/images/20210720083642.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)