如何从3-D Numpy数组创建二维数组?

时间:2017-02-15 05:22:02

标签: python-3.x numpy

我有一个与RGB图像对应的3维Numpy数组。我需要从中创建一个二维Numpy数组,这样如果R,G或B通道中的任何像素为1,则二维数组中的相应像素为255.

我知道如何在Numpy数组上使用类似列表推导的东西,但结果与原始数组的形状相同。我需要新的形状为2-D。

3 个答案:

答案 0 :(得分:2)

好的,假设你想要输出像素为0,它不应该是255而你的输入是MxNx3。

RGB = RGB == 1 # you can skip this if your original (RGB) contains only 0's and 1's anyway
out = np.where(np.logical_or.reduce(RGB, axis=-1), 255, 0)

答案 1 :(得分:2)

一种方法可能是在第三个昏暗中使用any()然后乘以255,以便将布尔值自动放大到int类型,就像这样 -

(img==1).any(axis=2)*255

示例运行 -

In [19]: img
Out[19]: 
array([[[1, 8, 1],
        [2, 4, 7]],

       [[4, 0, 6],
        [4, 3, 1]]])

In [20]: (img==1).any(axis=2)*255
Out[20]: 
array([[255,   0],
       [  0, 255]])

运行时测试 -

In [45]: img = np.random.randint(0,5,(1024,1024,3))

# @Paul Panzer's soln
In [46]: %timeit np.where(np.logical_or.reduce(img==1, axis=-1), 255, 0)
10 loops, best of 3: 22.3 ms per loop

# @nanoix9's soln    
In [47]: %timeit np.apply_along_axis(lambda a: 255 if 1 in a else 0, 0, img)
10 loops, best of 3: 40.1 ms per loop

# Posted soln here    
In [48]: %timeit (img==1).any(axis=2)*255
10 loops, best of 3: 19.1 ms per loop

此外,我们可以转换为np.uint8,然后将其与255相乘,以进一步提升效果 -

In [49]: %timeit (img==1).any(axis=2).astype(np.uint8)*255
100 loops, best of 3: 18.5 ms per loop

而且,如果我们使用第三个暗淡的单个切片 -

In [68]: %timeit ((img[...,0]==1) | (img[...,1]==1) | (img[...,2]==1))*255
100 loops, best of 3: 7.3 ms per loop

In [69]: %timeit ((img[...,0]==1) | (img[...,1]==1) | (img[...,2]==1)).astype(np.uint8)*255
100 loops, best of 3: 5.96 ms per loop

答案 2 :(得分:1)

使用apply_along_axis。 e.g。

In [28]: import numpy as np
In [29]: np.random.seed(10)
In [30]: img = np.random.randint(2, size=12).reshape(3, 2, 2)
In [31]: img
Out[31]: 
array([[[1, 1],
        [0, 1]],
       [[0, 1],
        [1, 0]],
       [[1, 1],
        [0, 1]]])
In [32]: np.apply_along_axis(lambda a: 255 if 1 in a else 0, 0, img)
Out[32]: 
array([[255, 255],
       [255, 255]])

请参阅doc of numpy了解详情。

相关问题