numpy convert number to byte

后端 未结 2 1506
半阙折子戏
半阙折子戏 2021-01-22 19:35

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 matr

2条回答
  •  一整个雨季
    2021-01-22 20:23

    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)
    

提交回复
热议问题