这段代码在运行时import SimpleITK as sitkimport numpy as npimport os# 设置文件路径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)# 定义函数将3D图像保存为2D的.png格式def save_image_as_png(image, save_folder, name_prefix): for i in range(image.shape[2]): slice = np.squeeze(image[:, :, i]) slice = slice.astype(np.float32) slice *= 255.0/slice.max() slice = slice.astype(np.uint8) save_name = os.path.join(save_folder, name_prefix + '_' + str(i) + '.png') sitk.WriteImage(sitk.GetImageFromArray(slice), save_name)# 读取Training Batch 1中的图像image_path = os.path.join(data_path, 'Training Batch 1/volume-0.nii')image = sitk.ReadImage(image_path)image_array = sitk.GetArrayFromImage(image)save_folder = os.path.join(save_path, 'image')if not os.path.exists(save_folder): os.makedirs(save_folder)save_image_as_png(image_array, save_folder, 'img')# 读取Training Batch 2中的标签label_path = os.path.join(data_path, 'Training Batch 2/segmentation-0.nii')label = sitk.ReadImage(label_path)label_array = sitk.GetArrayFromImage(label)# 将标签转换为灰度图并保存label_array[label_array == 1] = 128label_array[label_array == 2] = 255save_folder = os.path.join(save_path, 'mask')if not os.path.exists(save_folder): os.makedirs(save_folder)save_image_as_png(label_array, save_folder, 'mask')会出现RuntimeWarning: divide by zero encountered in true_divide slice *= 255.0/slice.max()这种情况,修复它,并给出完整代码
时间: 2023-11-22 14:56:18 浏览: 152
出现这个警告是因为slice中存在值为0的像素,导致计算slice.max()时除数为0。可以在计算slice.max()之前先将0值像素赋为一个较小的非零值,比如1。以下是修改后的完整代码:
```python
import SimpleITK as sitk
import numpy as np
import os
# 设置文件路径
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)
# 定义函数将3D图像保存为2D的.png格式
def save_image_as_png(image, save_folder, name_prefix):
for i in range(image.shape[2]):
slice = np.squeeze(image[:, :, i])
slice = slice.astype(np.float32)
# 将0值像素赋为1
slice[slice == 0] = 1
slice *= 255.0/slice.max()
slice = slice.astype(np.uint8)
save_name = os.path.join(save_folder, name_prefix + '_' + str(i) + '.png')
sitk.WriteImage(sitk.GetImageFromArray(slice), save_name)
# 读取Training Batch 1中的图像
image_path = os.path.join(data_path, 'Training Batch 1/volume-0.nii')
image = sitk.ReadImage(image_path)
image_array = sitk.GetArrayFromImage(image)
save_folder = os.path.join(save_path, 'image')
if not os.path.exists(save_folder):
os.makedirs(save_folder)
save_image_as_png(image_array, save_folder, 'img')
# 读取Training Batch 2中的标签
label_path = os.path.join(data_path, 'Training Batch 2/segmentation-0.nii')
label = sitk.ReadImage(label_path)
label_array = sitk.GetArrayFromImage(label)
# 将标签转换为灰度图并保存
label_array[label_array == 1] = 128
label_array[label_array == 2] = 255
save_folder = os.path.join(save_path, 'mask')
if not os.path.exists(save_folder):
os.makedirs(save_folder)
save_image_as_png(label_array, save_folder, 'mask')
```
阅读全文