Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Truncate a big integer to a uint8 type in Python

I'm casting an array that is populated with signed 32-bit integers to an array with only uint8 values (from 0 to 255). Right now, my code looks like this:

newArray = Image.fromarray(oldArray.astype(numpy.uint8))

The thing is: I want the numbers lower than zero to become zero, and the numbers higher than 255 to become 255, and this code obviously doesn't operate like that.

Is there an easy way to do it without iterating through the whole array?

like image 313
Jonathan Lopes Florêncio Avatar asked Apr 24 '26 03:04

Jonathan Lopes Florêncio


1 Answers

For in-place thresholding, I would use numpy.clip(myArray,0,255) before casting your array into the new data type.

like image 87
cameronroytaylor Avatar answered Apr 25 '26 15:04

cameronroytaylor