我正在处理以非标准图像格式(。tsm)存储的大型图像数据集。本质上,它是一个二进制文件,在开始时带有一些头,与FITS标准非常相似,只是存储在little-endian中,而不是FITS Big-Endian中。
在读取文件头并格式化元数据之后,我可以使用以下代码读取单个图像def __read_slice(self, file, img_num, dimensions):
"""Read a single image slice from .tsm file"""
pixel_range = self.metadata["pixel range"]
bytes_to_read = self.metadata["bytes to read"]
# position file pointer to correct byte
file.seek(self.HEADER_TOTAL_LEN + (bytes_to_read * img_num), 0)
all_bytes = file.read(bytes_to_read) # read image bytes
img = np.empty(len(pixels), dtype='uint16') # preallocate image vector
byte_idx = 0
for idx, pixel in enumerate(pixel_range):
img[idx] = (all_bytes[byte_idx + 1] << 8) + all_bytes[byte_idx]
byte_idx += 2
return np.reshape(img, (dimensions[1], dimensions[0])) # reshape array to correct dimensions
问题是图像可能非常大(2048x2048),所以即使只是加载20-30帧进行处理也会花费大量时间。我是python的新手,所以我猜这里的代码效率很低,特别是循环。
有没有更有效的方法将字节数据转换成16位整数?