使用python映像库将原始二进制8位无符号文件转换为16位无符号文件

2024-10-01 11:37:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个图像文件,是一个灰度8位无符号整数原始二进制文件,我需要把它转换成一个16位文件,并保持原始二进制。从16岁变为8岁相对容易,因为你只是切断了信息,但我很好奇我怎么才能走相反的路。在

具体地说,我有一个图像,它是用C++编写的处理器,处理器只需要16位无符号整数图像文件,所以我需要把我的8位文件转换成16位的文件。我一直在使用Python图像库进行一些处理,但是没有找到这个特定的函数。在

更新

我遵循了cgohlke的建议,得到了以下看似合乎逻辑的代码,但由于以下错误,它不接受我的“final”变量:

Traceback (most recent call last):
  File "C:\Users\Patrick\workspace\colorCorrect\src\editGrayscale.py", line 36, in <module>
    u1 = np.fromfile(final, 'uint8')
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

我的代码:

^{pr2}$

Tags: 文件函数代码图像信息错误图像文件二进制
2条回答
import numpy as np

# create example file
np.arange(256).astype('uint8').tofile('uint8_file.bin')

# read example file and convert to uint16
u1 = np.fromfile('uint8_file.bin', 'uint8')
u2 = u1.astype('uint16')
u2 *= 257  # scale to full 16 bit range
u2.tofile('uint16_file.bin')

struct模块允许您进行这种转换,尽管您需要自行处理对文件的读写操作,但如果您将其存储在“data”中,则应该可以:

    import struct

    uint8 = 'B'
    uint16 = 'H'

    data = struct.pack(uint16 * len(data),
                       *struct.unpack(uint8 * len(data), data))

添加“>;”或“<;”将允许您控制16位流是小端还是大端,即

^{pr2}$

会使它成为大端。在

相关问题 更多 >