Skip to content Skip to sidebar Skip to footer

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 fr

Solution 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')

Solution 2:

The struct module would let you do that kind of conversion, although you would need to take care on your own of the reading and writing to file, but if you had it stored in 'data', this should work:

    import struct

    uint8 = 'B'
    uint16 = 'H'

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

Adding a '>' or '<' will let you control whether your 16 bit stream is little-endian or big-endian, i.e.

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

would make it big-endian.


Post a Comment for "Convert Raw Binary 8 Bit Unsigned File To 16 Bit Unsigned With The Python Imaging Library"