替换阈值以上的所有rgb值 [英] Replace all rgb values above a threshold
问题描述
我有一个充满RGB值的numpy 3 d数组,例如 形状=(高度,宽度,3)
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]])
如果任何值都超过阈值,我必须替换RGB值,例如,阈值= 0.8,则替换= [2,2,2],然后
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]]
我该如何使用numpy以高效的方式做到这一点? 目前,我正在使用double for循环,并检查是否有任何rgb值高于阈值,我将其替换,但是对于n = 4000数组,这是非常缓慢的.
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.
我如何使用numpy来提高效率,也许使用np.where来做到这一点?
How would I do this more efficient with numpy, maybe something with np.where ?
推荐答案
我将矩阵扩展了另一个width
维.
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]]])
您可以通过在轴2上使用np.any
(从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])
您得到的matrix
:
array([[[ 0. , 0.5, 0.6],
[ 2. , 2. , 2. ]],
[[ 0. , 0.5, 0.6],
[ 2. , 2. , 2. ]]])
这篇关于替换阈值以上的所有rgb值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!