numpy将数字转换为字节 [英] numpy convert number to byte

查看:450
本文介绍了numpy将数字转换为字节的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个numpy矩阵,其浮点数大多在0-255的范围内.但是,有些数字有些超出范围(例如-5.36,270).

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).

我想将矩阵转换为numpy.uint8类型,因此0-255范围内的数字可以向上或向下舍入为封闭的int(没关系),但是小于0的数字应为0 ,并且大于255的数字应为255.

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.

您如何做到的?

推荐答案

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

此后,您可以使用 ndarray.astype 将所有数字截断为uint8数组:

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)

一种更好的方法可能是使用clipout参数一次完成所有截断.在这种情况下,您必须显式预分配输出缓冲区:

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)

这篇关于numpy将数字转换为字节的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆