实现Python时,有的时候同一个功能,有的代码写得很难看,有的写得又很优雅。
列举工作中遇到的codesnap:
API 的方法的选择
- numpy.astype 实现类型转换
- np.minimum(np.maximum(0), 1) 实现最大最小值截断,
而不是通过 data[data < 0] = 0 与 data[data > 255] = 255 - np.repeat() 方法 numpy 维度的扩展
代码示例
不优雅的代码:
begin_time = time.time()
# 将 HU值 通过 WWWL 变成 uint8 类型
gray_image_data = (hu_image_data- (self.window_level - self.window_width / 2)) / self.window_width * 255
gray_image_data [gray_image_data < 0] = 0
gray_image_data [gray_image_data > 255] = 255
gray_image_data_uint8 = gray_image_data.astype(np.uint8)
print(r'WWWL cost time {}'.format(time.time() - begin_time))
# 将numpy 的shape 从 [width, height] 变成 shape [width*height, 3]
gray_image_data_flattened = gray_image_data_uint8 .reshape(-1)
gray_image_data_flattened = gray_image_data_flattened [:, np.newaxis]
image_data_rgb = np.zeros(([gray_image_data_flattened .shape[0], 3]))
image_data_rgb [:, 0] = gray_image_data_flattened [:, 0]
image_data_rgb [:, 1] = gray_image_data_flattened [:, 0]
image_data_rgb [:, 2] = gray_image_data_flattened [:, 0]
print(r'convert cost time {}'.format(time.time() - begin_time))
优雅的代码:
# 将 HU值 通过 WWWL 变成 uint8 类型
gray_image_data = (hu_image_data- (self.window_level - self.window_width / 2)) / self.window_width
gray_image_data = np.minimum(np.maximum(gray_image_data, 0), 1) * 255
gray_image_data_uint8 = gray_image_data .astype(np.uint8)
print(r'WWWL cost time {}'.format(time.time() - begin_time))
# 将numpy 的shape 从 [width, height] 变成 shape [width*height, 3]
gray_image_data_flattened = gray_image_data_uint8 .reshape(-1)
mage_data_rgb = gray_image_data_flattened [:, None].repeat(3, axis=1)
print(r'convert cost time {}'.format(time.time() - begin_time))
可以看到,优雅的代码更简洁,同时减少拷贝。