请将LiTS2017数据集的图像和标签处理成2D的png格式,并且标签需要拆分成灰度图,背景灰度值0,肝脏灰度值1,肝脏肿瘤灰度值2,给出完整代码,我的LiTS2017数据集路径为C:\Users\Administrator\Desktop\LiTS2017,里面包含Training Batch 1,里面有图像,图像拓展名.nii。和Training Batch 2,里面有标签,标签拓展名.nii,保存路径为C:\Users\Administrator\Desktop\2D-LiTS2017,里面有image和mask两个文件夹,请将转换好的保存到对应的文件夹
时间: 2023-07-21 09:03:05 浏览: 191
mnist数据集转为png格式图片
5星 · 资源好评率100%
下面是将LiTS2017数据集的图像和标签处理成2D的png格式,并且标签拆分成灰度图的完整代码:
```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(os.path.join(save_path, 'image'))
os.makedirs(os.path.join(save_path, 'mask'))
def normalize(volume):
"""Normalize the volume"""
min_val = volume.min()
max_val = volume.max()
volume = (volume - min_val) / (max_val - min_val)
return volume
def save_image(image, save_path, name):
"""Save a single image"""
image = (image * 255).astype(np.uint8)
Image.fromarray(image).save(os.path.join(save_path, name))
def process_data(data_path, save_path):
"""Process the LiTS2017 dataset"""
image_path = os.path.join(data_path, 'Training Batch 1')
mask_path = os.path.join(data_path, 'Training Batch 2')
for i in range(131):
# Load image
image_file = os.path.join(image_path, f'volume-{i:03d}.nii')
image = nib.load(image_file).get_fdata()
image = normalize(image)
# Save image slices
for j in range(image.shape[2]):
image_slice = image[:, :, j]
save_image(image_slice, os.path.join(save_path, 'image'), f'image-{i:03d}-{j:03d}.png')
# Load mask
mask_file = os.path.join(mask_path, f'segment_liver_mask-{i:03d}.nii')
mask = nib.load(mask_file).get_fdata()
# Split mask into liver and tumor regions
liver_mask = (mask == 1).astype(np.uint8)
tumor_mask = (mask == 2).astype(np.uint8)
# Save mask slices
for j in range(mask.shape[2]):
liver_slice = liver_mask[:, :, j]
tumor_slice = tumor_mask[:, :, j]
mask_slice = np.zeros((liver_slice.shape[0], liver_slice.shape[1], 3), dtype=np.uint8)
mask_slice[:, :, 0] = 255 - liver_slice * 255
mask_slice[:, :, 1] = 255 - tumor_slice * 255
save_image(mask_slice, os.path.join(save_path, 'mask'), f'mask-{i:03d}-{j:03d}.png')
process_data(data_path, save_path)
```
这段代码中,我们首先创建了保存处理后数据的文件夹,然后定义了一个函数`normalize`,用于将体积数据归一化到0-1之间;另外定义了一个函数`save_image`,用于将单张图像保存为png格式。接下来,我们遍历每个体积数据,加载图像和标签,并将它们分别保存为png格式的2D图像。在保存标签时,我们将其拆分成灰度图,背景灰度值为0,肝脏灰度值为1,肝脏肿瘤灰度值为2,并将它们保存为RGB格式的图像,以便于后续可视化。
阅读全文