How to truncate the values of a 2D numpy array

Question:

I have a two-dimensional numpy array(uint16), how can I truncate all values above a certain barrier(say 255) to that barrier? The other values must stay the same. Using a nested loop seems to be ineffecient and clumsy.

Asked By: nobody

||

Answers:

import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array[my_array > 255] = 255

the output will be

array([[100, 200],
       [255, 255]], dtype=uint16)
Answered By: JBernardo

In case your question wasn’t as related to the bit depth as JBernardo’s answer, the more general way to do it would be something like:
(after edit, my answer is now pretty much the same as his)

def trunc_to( my_array, limit ):
    too_high = my_array > limit
    my_array[too_high] = limit

Here‘s a nice intro link for numpy bool indexing.

Answered By: ImAlsoGreg

actually there is a specific method for this, ‘clip’:

import numpy as np
my_array = np.array([[100, 200], [300, 400]],np.uint16)
my_array.clip(0,255) # clip(min, max)

output:

array([[100, 200],
       [255, 255]], dtype=uint16)
Answered By: Andrea Zonca
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.