Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
204 views
in Technique[技术] by (71.8m points)

grayscale - convert raw binary 8 bit unsigned file to 16 bit unsigned with the python imaging library

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.

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.

UPDATE:

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:UsersPatrickworkspacecolorCorrectsrceditGrayscale.py", line 36, in <module>
    u1 = np.fromfile(final, 'uint8')
TypeError: file() argument 1 must be encoded string without NULL bytes, not str

My code:

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)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
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')

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...