繁体   English   中英

在 Python 中将字节数组转换为 16 位灰度图像

[英]Converting byte array to 16 bit grayscale image in Python

我正在处理以非标准图像格式 (.Tsm) 存储的大型图像数据集。 本质上它是一个二进制文件,开头有一些头文件,与 FITS 标准非常相似,只是存储在 little-endian 而不是 FITS big-endian。

读取文件 header 并格式化元数据后,我可以使用以下代码读取单个图像

    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 位整数?

你可以试试:

img= np.frombuffer(all_bytes, dtype='uint16')

例子:

>>> np.frombuffer(b'\x01\x02\x03\x04', dtype='uint16')
array([ 513, 1027], dtype=uint16)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM