关于numpy:numpy-的-astype-是如何把-npuint8-是如何转成-npfloat32

4次阅读

共计 392 个字符,预计需要花费 1 分钟才能阅读完成。

在 NumPy 中,应用 astype 函数能够将数组的数据类型转换为指定的类型。具体地说,将 np.uint8 类型的数组转换为 np.float32 类型的数组,能够应用以下代码:


import numpy as np

uint8_array = np.array([0, 128, 255], dtype=np.uint8)
float32_array = uint8_array.astype(np.float32) / 255.0

print(float32_array)

输入后果为:


[0.         0.5019608  1.]

在这里,咱们首先创立一个 np.uint8 类型的数组 uint8_array,蕴含了三个元素:0、128 和 255。而后,咱们应用 astype 函数将其转换为 np.float32 类型的数组 float32_array。为了将数据归一化到 [0, 1] 的范畴内,咱们还须要将 float32_array 中的每个元素除以 255。

正文完
 0