从行向量和列向量numpy生成矩阵

时间:2017-08-24 09:42:33

标签: python numpy

我有两个numpy数组:

    a = [ (0,0,255), (0,0,0), (0,255,0), (255,0,0) ]

    b = [
         (0,0,255),
         (0,0,0),
         (0,255,0),
         (255,0,0)
        ]

如何使用numpy获取以下矩阵:

    [
     [ (0,0,255), (0,0,255), (0,0,0), (0,255,0), (255,0,0) ],
     [ (0,0,0), (0,0,255), (0,0,0), (0,255,0), (255,0,0) ],
     [ (0,255,0), (0,0,255), (0,0,0), (0,255,0), (255,0,0) ],
     [ (255,0,0), (0,0,255), (0,0,0), (0,255,0), (255,0,0) ]
    ]

我试图在图像中的所有像素之间进行成对的像素比较。

2 个答案:

答案 0 :(得分:0)

简单的pythonic方式:

z = [[i] + a for i in b]

答案 1 :(得分:0)

以下是使用numpy

获取上述矩阵的一种方法
In []: a = np.asarray([ (0,0,255), (0,0,0), (0,255,0), (255,0,0) ])
In []: b= np.asarray([(0,0,255), (0,0,0), (0,255,0), (255,0,0)])
In []: np.array([np.vstack((a[i],b)) for i,v in enumerate(a)])
Out[]: 
array([[[  0,   0, 255],
        [  0,   0, 255],
        [  0,   0,   0],
        [  0, 255,   0],
        [255,   0,   0]],

       [[  0,   0,   0],
        [  0,   0, 255],
        [  0,   0,   0],
        [  0, 255,   0],
        [255,   0,   0]],

       [[  0, 255,   0],
        [  0,   0, 255],
        [  0,   0,   0],
        [  0, 255,   0],
        [255,   0,   0]],

       [[255,   0,   0],
        [  0,   0, 255],
        [  0,   0,   0],
        [  0, 255,   0],
        [255,   0,   0]]])