首页 > 解决方案 > numpy ndarray dtype 转换失败

问题描述

我有一段代码进行了一些 ndarray 转换,我想将最终输出转换为 np.int8 类型并将其输出到文件。但是,转换不起作用。这是一段代码:

print("origin dtype:", image[0].dtype)
print(type(image[0]))
image[0] = image[0].astype(np.uint8)
print(image[0])
print("image datatype1:",image[0].dtype)
image[0].tofile(f'{image_name}_{org_h}_{org_w}_{dst_h}_{dst_w}.bin')
print("image datatype2:",image[0].dtype)

这是我得到的:

origin dtype: float32
<class 'numpy.ndarray'>
[[[ 71.  73.  73. ... 167. 170. 173.]
  [ 62.  63.  64. ... 164. 168. 170.]
  [ 54.  56.  57. ... 157. 163. 165.]
  ...
 [142. 154. 138. ... 115.  91. 111.]
  [158. 127. 123. ... 128. 130. 113.]
  [133. 114. 106. ... 114. 110. 106.]]]
image datatype1: float32
image datatype2: float32

有人可以帮我解决哪里出错了吗?

标签: python-3.xnumpymultidimensional-arraywritetofiledtype

解决方案


二维数组的行不能有不同的 dtypes:当您将数组分配给uint8数组的行时float32,它被强制转换为float32; 例如:

image = np.ones((4, 4), dtype='float32')
print(image[0].dtype)
# float32

image[0] = image[0].astype('uint8')
print(image[0].dtype)
# float32

您的选择是一次转换整个数组的 dtype:

image = image.astype('uint8')
print(image[0].dtype)
# uint8

或者将您的二维数组转换为一维数组的列表,然后每个数组都可以有自己的 dtype:

image = list(image)
print(image[0].dtype)
# float32

image[0] = image[0].astype('uint8')
print(image[0].dtype)
# uint8

推荐阅读