我有一个 2D np.array,我必须将其可视化。我已经有了一个颜色图函数,所以我要做的最后一件事就是用另外 3 个值替换数组的每个值,这些值代表 RGB。
颜色图功能:
def colormapHLS(a: float):
h, l, s = 0, 0, 0
if a < 0:
h = 2 / 3
l = 0
s = 1
elif 0 < a <= 1 / 3:
h = 2 / 3
l = 0.5 * (a * 3)
s = 1
elif 1 / 3 < a <= 2 / 3:
h = 2 / 3 - ((2 / 3) * ((a - 1 / 3) * 3))
l = 0.5
s = 1
elif 2 / 3 < a <= 1:
h = 0
l = 0.5 + 0.5 * ((a - 2 / 3) * 3)
s = 1
elif a > 1:
h = 0
l = 1
s = 1
return h, l, s
和主要代码:
# ...
trans_func = lambda x: colorsys.hls_to_rgb(*colormapHLS(x))
draw_buff -= numpy.min(draw_buff)
draw_buff /= numpy.max(draw_buff)
print(draw_buff.shape)
colored_draw_buff = numpy.zeros((*draw_buff.shape, 3))
print(colored_draw_buff.shape)
for y in range(draw_buff.shape[0]):
for x in range(draw_buff.shape[1]):
cur = trans_func(draw_buff[y][x])
for z in range(3):
colored_draw_buff[y][x][z] = cur[z]
colored_draw_buff *= 255
# ...
绘制buff形状为(x,y)
所以,它确实有效,但是太慢了。我认为有一个更快的方法
self.draw_buff = self.draw_buff.reshape(x*y)
self.draw_buff -= numpy.min(self.draw_buff)
self.draw_buff /= numpy.max(self.draw_buff)
self.draw_buff = numpy.array(trans_func(self.draw_buff))
self.draw_buff *= 255
self.draw_buff = self.draw_buff.swapaxes(0,1)
self.draw_buff = self.draw_buff.reshape((y,x,3))
交换轴+重塑正在完成这项工作