简体   繁体   English

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

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

I'm working with large image datasets stored in a non-standard image format (.Tsm).我正在处理以非标准图像格式 (.Tsm) 存储的大型图像数据集。 Essentially it's a binary file with some headers at the start, very similar to FITS standard except stored in little-endian as opposed to FITS big-endian.本质上它是一个二进制文件,开头有一些头文件,与 FITS 标准非常相似,只是存储在 little-endian 而不是 FITS big-endian。

After reading the file header and formatting the metadata, I can read a single image using the following code读取文件 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 

the trouble is the images can be very large (2048x2048) so even just loading in 20-30 frames for processing can take a significant amount of time.问题是图像可能非常大(2048x2048),因此即使只是加载 20-30 帧进行处理也可能需要大量时间。 I'm new to python so i'm guessing the code here is pretty inefficient, especially the loop.我是 python 的新手,所以我猜这里的代码效率很低,尤其是循环。

Is there a more efficient way to convert the byte data into 16bit integers?有没有更有效的方法将字节数据转换为 16 位整数?

You can try:你可以试试:

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

Example:例子:

>>> 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