Search code examples
pythonimage-processingmatrixthresholdimage-thresholding

Changing the values of a matrix above a threshold in python


I have a matrix :

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

I want to replace all the values 0.55 < x < 0.95 by 0.55.

PS : My question is similar to this question. But the answer does not work in my case.


Solution

  • You can use np.where:

    matrix = np.array([[[0,0.5,0.6],[0.9,1.2,0]],[[0,0.5,0.6],[0.9,1.2,0]]])
    matrix[np.where((matrix > 0.55) & (matrix < 0.95))] = 0.55
    # Or
    # matrix[(matrix > 0.55) & (matrix < 0.95)] = 0.55
    

    Output:

    >>> matrix
    array([[[0.  , 0.5 , 0.55],
            [0.55, 1.2 , 0.  ]],
    
           [[0.  , 0.5 , 0.55],
            [0.55, 1.2 , 0.  ]]])