【发布时间】:2021-01-26 14:13:13
【问题描述】:
这是 ipython3 中的一个执行
In [81]: r2
Out[81]:
array([-1.2997805, -1.4251276, -1.3047135, ..., -2.0358603, -1.9741256,
-1.6412157], dtype=float32)
In [82]: r2.astype(np.uint8)
Out[82]: array([255, 255, 255, ..., 254, 255, 255], dtype=uint8)
-1.2997805如何转换为255?
添加:来自下面的 cmets(谢谢),我是这样测试的。看起来float被转换为int,并且模255(将其读取为unsigned int8)完成。
is first convereted to int. and the it is cut using modulo(%).
In [98]: b
Out[98]: array([-1., 0., 1.])
In [99]: b.astype(np.uint8)
Out[99]: array([255, 0, 1], dtype=uint8)
【问题讨论】:
-
这能回答你的问题吗? Integer overflow in numpy arrays
-
@MykolaZotko 没有回答这个与 numpy 如何进行不安全强制转换有关的具体案例
-
uint8类型涵盖从 0 到 255 的范围。超出此范围的负值变为 255。 -
在 C 中尝试一下,看看它是否做同样的事情。我的猜测是,它首先转换为有符号整数为 -1,然后无符号为 255。
-
@MykolaZotko 没有解释为什么 -2 是 254。
标签: python numpy python-3.5