Subtract 2 Numpy arrays with condition

﹥>﹥吖頭↗ 提交于 2019-12-11 18:53:50

问题


I have two Numpy arrays which look like this:

a = [[ [1,2,3], [4,5,6] ], 
    [  [7,8,9], [10,11,12] ]]

b = [[ [1,1,1], [0,0,0] ], 
     [ [3,3,3], [4,4,4] ]]

I want to perform c = a - b with condition that c = 255 if b>0 else a

So c should be like this:

c = [[ [255,255,255], [4,5,6] ], 
     [ [255,255,255], [255,255,255] ]]

How to do it efficiently without any loop?


回答1:


Use np.where

>>> c = np.where(np.array(b)>0, 255, a)
>>> c
array([[[255, 255, 255],
        [  4,   5,   6]],

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

Btw. there is no subtracting happpening here; maybe change the title of your question.



来源:https://stackoverflow.com/questions/48354259/subtract-2-numpy-arrays-with-condition

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!