绘画程序在生成图片的时候报错,生成了黑图,cmd窗口里提示报错信息:RuntimeWarning: invalid value encountered in cast out = np.clip(out * 255, 0, 255).astype(np.uint8) # 0~1 -> 0~255
通常是因为 NumPy 数组中存在无效的或 NaN
值,这些值在转换为 uint8
类型时会出现问题。
我原来代码:
out = np.transpose(out.data.cpu().numpy(), [0, 2, 3, 1]) # 1x3xHxW -> 1xHxWx3
out = np.clip(out, 0, 1) # clip to 0~1
out = np.clip(out * 255, 0, 255).astype(np.uint8) # 0~1 -> 0~255
在转换为 uint8
之前,使用 np.nan_to_num()
处理无效值。这样可以确保数组中不会有 NaN
或 inf
影响类型转换。
修改后的代码:
out = np.transpose(out.data.cpu().numpy(), [0, 2, 3, 1]) # 1x3xHxW -> 1xHxWx3
out = np.nan_to_num(out, nan=0.0, posinf=1.0, neginf=0.0) # 处理无效值
out = np.clip(out, 0, 1) # clip to 0~1
out = np.clip(out * 255, 0, 255).astype(np.uint8) # 0~1 -> 0~255
注:
这里的 np.nan_to_num
函数会将数组中的 NaN 替换为 0,正无穷大替换为 1,负无穷大替换为 0,从而避免在后续的裁剪和转换过程中出现无效值。