Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

numpy convert number to byte

I have a numpy matrix with float numbers mostly in range 0-255. However, there are some numbers that are a bit out of range (like -5.36, 270).

I want to convert the matrix to numpy.uint8 type, so the numbers in range 0-255 can round up or down to the closed int (It doesn't matter), but the numbers are smaller than 0 should be 0, and the numbers are greater than 255 should be 255.

How do you do this?

like image 224
baruchiro Avatar asked Jun 16 '26 05:06

baruchiro


1 Answers

clip will do the first step: clipping to the desired range.

After that, you can use ndarray.astype to truncate all the numbers into a uint8 array:

result = np.clip(x, 0, 255).astype(np.uint8)

A better way might be to use clip's out parameter to do the truncation all at once. In this case you'll have to explicitly pre-allocate the output buffer:

result = np.empty_like(x, dtype=np.uint8)
np.clip(x, 0, 255, out=result)
like image 133
Mad Physicist Avatar answered Jun 17 '26 19:06

Mad Physicist



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!