Replace all rgb values above a threshold

瘦欲@ 提交于 2020-01-15 05:26:06

问题


I have a numpy 3 d array full of RGB values like for exemple shape = (height,width,3)

  matrix = np.array( [[[0,0.5,0.6],[0.9,1.2,0]])

I have to replace the RGB value if any of the values is above a threshold, for exemple threshold = 0.8, replacement = [2,2,2] then

matrix = [[[0,0.5,0.6],[2,2,2]]

How can I do this on a efficient mannner with numpy ? Currently I am using a double for loop and checking if any rgb value is above treshold, i replace it however this is quiet slow for n = 4000 array.

How would I do this more efficient with numpy, maybe something with np.where ?


回答1:


I've expanded your matrix by another width dimension.

matrix = np.array([[[0,0.5,0.6],[0.9,1.2,0]],[[0,0.5,0.6],[0.9,1.2,0]]])

You can build a mask by using np.any on axis 2 (starts with 0, so third axis):

mask = np.any((matrix > 0.8), axis=2)

# mask:
array([[False,  True],
       [False,  True]], dtype=bool)

matrix[mask] = np.array([2,2,2])

Your resulting matrix:

array([[[ 0. ,  0.5,  0.6],
        [ 2. ,  2. ,  2. ]],

       [[ 0. ,  0.5,  0.6],
        [ 2. ,  2. ,  2. ]]])


来源:https://stackoverflow.com/questions/55836490/replace-all-rgb-values-above-a-threshold

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