这段代码在运行时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 09:56:16 浏览: 94
python导入csv文件出现SyntaxError问题分析
这个 RuntimeWarning 出现的原因是可能存在某些切片上所有像素都是 0,导致在计算 `slice.max()` 时出现了除以 0 的情况。解决这个问题的方法是在计算 `slice.max()` 之前,先判断 `slice` 是否全为 0,如果是,则将 `slice.max()` 设为 1。修改代码如下:
```python
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)
if slice.max() == 0:
max_val = 1
else:
max_val = slice.max()
slice *= 255.0/max_val
slice = slice.astype(np.uint8)
save_name = os.path.join(save_folder, name_prefix + '_' + str(i) + '.png')
sitk.WriteImage(sitk.GetImageFromArray(slice), save_name)
```
这样修改后,即使出现某些切片上所有像素都是 0 的情况,也不会出现除以 0 的错误了。
阅读全文