问题描述
我有一个图像文件,该文件是灰度8位无符号整数原始二进制文件,我需要将其转换为16位文件并将其保存在原始二进制文件中.从16跳到8相对容易,因为您只是在切断信息,但是我很好奇我该如何去做.
I have an image file that is a grayscale 8 bit unsigned integer raw binary file and I need to convert it to a 16 bit file and keep it in raw binary. It is relatively easy to go from 16 to 8 because you are just cutting off information but I am curious how I can go the other way.
具体来说,我有一个要进入用C ++编写的处理器的图像,并且该处理器只接受16位无符号整数图像文件,因此我需要将8位文件转换为16位.我已经使用Python Imaging Library进行了一些处理,但是找不到该特定功能.
To be specific I have an image that is going into a processor written in C++ and the processor only takes 16 bit unsigned integer image files so I need to convert my 8 bit file into a 16 bit one. I have been doing some processing with the Python Imaging Library but haven't been able to find this specific function.
更新:
我遵循了cgohlke的建议,并使用了以下代码,这些代码似乎合乎逻辑,但是由于以下错误,它不接受我的"final"变量:
I followed cgohlke's advice and have the following code that seems logical but it is not accepting my 'final' variable because of the following error:
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)
推荐答案
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')
这篇关于使用python映像库将原始二进制8位无符号文件转换为16位无符号文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!