2012-06-07 59 views
0

我有一个图像文件是一个灰度8位无符号整数原始二进制文件,我需要将其转换为16位文件,并保持它原始二进制。从16点到8点相对比较容易,因为你只是关掉信息,但我很好奇我怎样才能走向另一条路。将原始二进制8位无符号文件转换为16位无符号的Python成像库

具体来说,我有一个图像进入用C++编写的处理器,处理器只需要16位无符号整数图像文件,所以我需要将我的8位文件转换为16位文件。我一直在用Python Imaging Library做一些处理,但一直没有找到这个特定的功能。

UPDATE

我也跟着cgohlke的建议,有下面的代码,这似乎合乎逻辑,但它不接受,因为下面的错误我的“最终”变量:

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 

我的代码:

import Image 
import numpy as np 

fileName = raw_input("Enter a file name: ") 
saveFile = raw_input("Enter a new save file name: ") 

with open(fileName, 'rb') as f: 
    im = Image.fromstring('L', (3032, 2016), f.read()) # also try 'L;16B', 'I;16', and 'I;16B' 
    changed = im.point(lambda i: i/.4)  

final = changed.tostring() 

np.arange(256).astype('uint8').tofile(final) 

u1 = np.fromfile(final, 'uint8') 
u2 = u1.astype('uint16') 
u2 *= 257 # scale to full 16 bit range 
u2.tofile(saveFile) 

回答

1
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') 
+0

当我把它放在它给我:“TypeError:file()参数1必须是编码字符串没有NULL字节,而不是str” – clifgray

0

的STR UCT模块将让你做这种转换的,尽管可能需要承担自己的阅读和写入文件照顾,但如果您把它保存在“数据”,这应该工作:

import struct 

    uint8 = 'B' 
    uint16 = 'H' 

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

添加“>”或“<”将让你控制你的16位流是否是小端还是大端,即

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

将使大端。

相关问题