Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to truncate the values of a 2D numpy array

Tags:

python

numpy

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.

like image 375
nobody Avatar asked Aug 13 '11 19:08

nobody


2 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)
like image 85
JBernardo Avatar answered Oct 22 '22 23:10

JBernardo


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)
like image 29
Andrea Zonca Avatar answered Oct 22 '22 23:10

Andrea Zonca