How to truncate values โ€‹โ€‹of a 2D numpy array

I have a two-dimensional numpy array (uint16), how can I truncate all values โ€‹โ€‹above a certain barrier (say 255) to this barrier? The remaining values โ€‹โ€‹should remain unchanged. Using a nested loop seems inefficient and awkward.

+6
source share
3 answers
import numpy as np my_array = np.array([[100, 200], [300, 400]],np.uint16) my_array[my_array > 255] = 255 

the conclusion will be

 array([[100, 200], [255, 255]], dtype=uint16) 
+5
source

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) 

exit:

 array([[100, 200], [255, 255]], dtype=uint16) 
+19
source

In case your question was not related to bit depth, like JBernardo's answer, a more general way to do this would be something like this: (after editing, my answer is now almost the same as hiss)

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

Here's a nice link to enter numup bool indexing.

+6
source

Source: https://habr.com/ru/post/894988/


All Articles