【问题标题】:numpy ndarray dtype convertion failednumpy ndarray dtype 转换失败
【发布时间】:2021-01-08 07:39:32
【问题描述】:

我有一段代码进行了一些 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

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

【问题讨论】:

  • 什么是image?

标签: python-3.x numpy multidimensional-array writetofile dtype


【解决方案1】:

2D 数组的行不能有不同的 dtype:当您将 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

【讨论】:

    猜你喜欢
    • 2023-03-19
    • 1970-01-01
    • 2019-06-27
    • 2021-11-26
    • 2017-12-25
    • 1970-01-01
    • 2017-12-14
    • 2015-08-07
    • 1970-01-01
    相关资源
    最近更新 更多