如何使用numpy

时间:2018-06-22 04:45:54

标签: python numpy colormap

我正在尝试使用RGB三元组创建一个非常简单的色彩图。那有多种颜色。

以下是我要使其遵循的形状:

enter image description here

我知道这可能不是真正的RGB光谱,但是我希望它尽可能容易计算。

我希望能够生成沿着行均匀间隔的N个8位RGB元组的数组。

对于上面图像中所有点都带有颜色的简单实例,很容易使用numpy.linspace()使用以下代码生成:

import numpy as np

# number of discrete colours
N = 9

# generate R array
R = np.zeros(N).astype(np.uint8)
R[:int(N/4)] = 255
R[int(N/4):int(2*N/4)+1] = np.linspace(255,0,num=(N/4)+1,endpoint=True)

# generate G array
G = 255*np.ones(N).astype(np.uint8)
G[0:int(N/4)+1] = np.linspace(0,255,num=(N/4)+1,endpoint=True)
G[int(3*N/4):] = np.linspace(255,0,num=(N/4)+1,endpoint=True)

# generate B array
B = np.zeros(N).astype(np.uint8)
B[int(2*N/4):int(3*N/4)+1] = np.linspace(0,255,num=(N/4)+1,endpoint=True)
B[int(3*N/4)+1:] = 255

# stack arrays
RGB = np.dstack((R,G,B))[0]

此代码适用于5种颜色:

r   255 255 0   0   0
g   0   255 255 255 0
b   0   0   0   255 255

enter image description here

9种颜色:

r   255 255 255 127 0   0   0   0   0
g   0   127 255 255 255 255 255 127 0
b   0   0   0   0   0   127 255 255 255

enter image description here

13种颜色:

r   255 255 255 255 170 85  0   0   0   0   0   0   0
g   0   85  170 255 255 255 255 255 255 255 170 85  0
b   0   0   0   0   0   0   0   85  170 255 255 255 255

enter image description here

等。但是我在解决如何使其适用于任意N种颜色方面遇到了麻烦,因为linspace技巧仅在从一个端点到另一个端点时才起作用。

有人可以帮我解决该怎么做吗?任何有关如何使我的代码更高效的想法也都很好,我只是在学习了一段时间之后才开始使用numpy。

2 个答案:

答案 0 :(得分:2)

这是使用np.clip的一种相当方便的方法:

def spec(N):                                             
    t = np.linspace(-510, 510, N)                                              
    return np.round(np.clip(np.stack([-t, 510-np.abs(t), t], axis=1), 0, 255)).astype(np.uint8)

通过仅依赖保证在网格上的任意两个点(第一个点和最后一个点),仅依靠保证在网格上的两个点来避免出现您描述的问题。

示例:

>>> spec(5)
array([[255,   0,   0],
       [255, 255,   0],
       [  0, 255,   0],
       [  0, 255, 255],
       [  0,   0, 255]], dtype=uint8)
>>> spec(10)
array([[255,   0,   0],
       [255, 113,   0],
       [255, 227,   0],
       [170, 255,   0],
       [ 57, 255,   0],
       [  0, 255,  57],
       [  0, 255, 170],
       [  0, 227, 255],
       [  0, 113, 255],
       [  0,   0, 255]], dtype=uint8)

答案 1 :(得分:0)

如果您只想要给定级别的RGB,则您自己发布的图将作为答案-

R = [255] * 256
R.extend(list(reversed(range(256))))
R.extend([0] * 256)
R.extend([0] * 256)

G = list(range(256))
G.extend([255] * 256)
G.extend([255] * 256)
G.extend(list(reversed(range(256))))

B = [0] * 256
B.extend([0] * 256)
B.extend(list(range(256)))
B.extend([255] * 256)

level = 5
step = 1024 // (level -1)

print(R[::step])
print(G[::step])
print(B[::step])