Read HiPic img file

# Python script to read HiPic img file
# K.Tamasaku 6/24/2020, 2/7/2025

# # Sample program for read_img
# import matplotlib.pyplot as plt
#
# data=(read_img('test.img'))[700:1500, 500:1500] # ROI
# 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 a HiPic img file.')
            return None
        comment=struct.unpack_from(f'<{cmtlen}s', imgdata, 64)
        #print(comment)
        bpp=int(re.findall('[0-9]', re.findall('BytesPerPixel=[0-9]', comment[0].decode())[0])[0])
        if bpp == 2:
            data=(np.array(struct.unpack_from(f'<{xsize*ysize}H', imgdata, 64+cmtlen))).reshape([ysize, xsize]) # H unsigned short
        else:
            data=(np.array(struct.unpack_from(f'<{xsize*ysize}I', imgdata, 64+cmtlen))).reshape([ysize, xsize]) # I unsigned int

        f.close()

        return data

BACK