python-3.xnumpymultidimensional-arraywritetofiledtype

numpy ndarray dtype convertion failed


I have a piece of code that did some ndarray transformation, and I'd like to convert the final output to be np.int8 type and output it to file. However, the conversion did not work. Here is the piece of code:

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)

Here is what I got:

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

Can somebody help me with where it went wrong?


Solution

  • Rows of a 2D array cannot have a different dtypes: when you assign a uint8 array to the row of a float32 array, it is cast to float32; for example:

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

    Your options are either to convert the dtype of the entire array at once:

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

    Or to convert your 2D array to a list of 1D arrays, each of which can then have its own dtype:

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