Can I save a numpy array as a 16-bit image using “normal” (Enthought) python?

后端 未结 5 1723
抹茶落季
抹茶落季 2020-12-03 12:15

Is there any way to save a numpy array as a 16 bit image (tif, png) using any of the commonly available python packages? This is the only way that I could get to work in the

5条回答
  •  情歌与酒
    2020-12-03 12:56

    You can convert your 16 bit array to a two channel image (or even 24 bit array to a 3 channel image). Something like this works fine and only numpy is required:

    import numpy as np
    arr = np.random.randint(0, 2 ** 16, (128, 128), dtype=np.uint16)  # 16-bit array
    print(arr.min(), arr.max(), arr.dtype)
    img_bgr = np.zeros((*arr.shape, 3), np.int)
    img_bgr[:, :, 0] = arr // 256
    img_bgr[:, :, 1] = arr % 256
    cv2.imwrite('arr.png', img_bgr)
    # Read image and check if our array is restored without losing precision
    img_bgr_read = cv2.imread('arr.png')
    B, G, R = np.split(img_bgr_read, [1, 2], 2)
    arr_read = (B * 256 + G).astype(np.uint16).squeeze()
    print(np.allclose(arr, arr_read), np.max(np.abs(arr_read - arr)))
    

    Result:

    0 65523 uint16
    True 0
    

提交回复
热议问题