请将我的数据集里面的3D图像变成2D、RGB三通道、的png格式的图像(调整窗宽,以突出所需区域的细节)。数据集里面的3D标签变成(要求背景灰度值0、肝脏灰度值1、肝脏肿瘤灰度值2的)2D的png格式标签。 LiTS2017数据集里面包含Training Batch 1和Training Batch 2两个文件夹。Training Batch 1文件夹里面有图像,图像的拓展名为.nii。Training Batch 2文件夹里面有标签,标签拓展名为.nii。 LiTS2017数据集的路径为C:\Users\Administrator\Desktop\LiTS2017。 保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,请帮我创建好对应文件夹,并且将转换好的数据保存到对应的文件夹。
时间: 2024-02-03 14:14:44 浏览: 26
好的,我可以帮你实现这个功能。你需要安装以下库:numpy、SimpleITK、os、cv2。
以下是代码实现:
```python
import SimpleITK as sitk
import numpy as np
import os
import cv2
# 设置路径
in_path = r'C:\Users\Administrator\Desktop\LiTS2017'
out_path = r'C:\Users\Administrator\Desktop\2D-LiTS2017'
# 创建输出文件夹
if not os.path.exists(out_path):
os.makedirs(out_path)
if not os.path.exists(os.path.join(out_path, 'images')):
os.makedirs(os.path.join(out_path, 'images'))
if not os.path.exists(os.path.join(out_path, 'labels')):
os.makedirs(os.path.join(out_path, 'labels'))
# 处理Training Batch 1中的图像
for filename in os.listdir(os.path.join(in_path, 'Training Batch 1')):
# 读取nii文件
itk_img = sitk.ReadImage(os.path.join(in_path, 'Training Batch 1', filename))
img_array = sitk.GetArrayFromImage(itk_img)
# 窗位窗宽调整
min_hu = -200.0
max_hu = 250.0
img_array[img_array < min_hu] = min_hu
img_array[img_array > max_hu] = max_hu
img_array = (img_array - min_hu) / (max_hu - min_hu) * 255.0
img_array = img_array.astype(np.uint8)
# 将3D图像转为2D图像并保存
for i in range(img_array.shape[0]):
img = img_array[i]
img = cv2.cvtColor(img, cv2.COLOR_GRAY2RGB)
cv2.imwrite(os.path.join(out_path, 'images', filename[:-4] + '-' + str(i) + '.png'), img)
# 处理Training Batch 2中的标签
for filename in os.listdir(os.path.join(in_path, 'Training Batch 2')):
# 读取nii文件
itk_img = sitk.ReadImage(os.path.join(in_path, 'Training Batch 2', filename))
img_array = sitk.GetArrayFromImage(itk_img)
# 将标签转为灰度值为0、1、2的2D图像并保存
for i in range(img_array.shape[0]):
img = img_array[i]
img[img == 1] = 255
img[img == 2] = 128
img = img.astype(np.uint8)
cv2.imwrite(os.path.join(out_path, 'labels', filename[:-4] + '-' + str(i) + '.png'), img)
```
这段代码首先创建了输出文件夹。然后对于Training Batch 1中的每个.nii文件,读取图像数据并进行窗位窗宽调整,将3D图像转为2D图像并保存到对应文件夹中。对于Training Batch 2中的每个.nii文件,读取标签数据并将标签转为灰度值为0、1、2的2D图像并保存到对应文件夹中。