Read HiPic img file

# Python script to read HiPic img file
# K.Tamasaku 6/24/2020

# # Sample program for read_img
# import matplotlib.pyplot as plt
#
# data=(read_img('test.img'))[700:1500, 500:1500] # ROI
# fig=plt.subplots()
# plt.imshow(data)
# plt.show()
#

import numpy as np
import struct

def read_img(fn: str) -> list:
    try:
        f=open(fn, "rb")
    except OSError as e:
        print(e)
    else:
        imgdata=f.read()
        fid, cmtlen, xsize, ysize=struct.unpack_from("<2shhh", imgdata, 0) # little endian
        #print(fid, cmtlen, xsize, ysize)
        if fid != b'IM':
            print(f'{fn} is not HiPic img format.')
            return None
        comment=struct.unpack_from(f'<{cmtlen}s', imgdata, 64)
        #print(comment)
        data=(np.array(struct.unpack_from(f'<{xsize*ysize}h', imgdata, 64+cmtlen))).reshape([xsize, ysize])
        f.close()

        return data

BACK