Reversing bits in a byte

Oscar Benjamin oscar.j.benjamin at gmail.com
Tue Mar 12 10:59:09 EDT 2013


On 12 March 2013 13:28, Robert Flintham <Robert.Flintham at uhb.nhs.uk> wrote:
> Sorry, the subject line was for a related question that I decided not to ask, I forgot to change it when I changed my email.  I've changed it now!
>
> I'm using Python 3.3 on Windows with the pydicom module (http://code.google.com/p/pydicom/).  Using pydicom, I've ended up with a "bytes" object of length (512*512/8 = 32768) containing a 512x512 1-bit bitmap (i.e. each byte represents 8 pixels of either 1 or 0).  When I print this to screen I get:
> 'b\x00\x00\x00.....'
>
> I can unpack this to a tuple of the integer representations of binary data, but that doesn't really help as presume I need the binary (8 digit) representation to be able to translate that into an image.
>
> I wasn't sure which GUI library to use, so haven't specified one.  As it's Python 3, Tkinter is available.  I also have matplotlib and numpy installed, and PIL.
>
> Ideally, I'd like to be able to access the pixel data in the form of a numpy array so that I can perform image-processing tasks on the data.
>
> So now that I've explained myself slightly more fully, does anyone have any thoughts on how to do this?

Numpy and matplotlib will do what you want:

import numpy as np
import matplotlib.pyplot as plt

def bits_to_ndarray(bits, shape):
    abytes = np.frombuffer(bits, dtype=np.uint8)
    abits = np.zeros(8 * len(abytes), np.uint8)
    for n in range(8):
        abits[n::8] = (abytes % (2 ** (n+1))) != 0
    return abits.reshape(shape)

# 8x8 image = 64 bits bytes object
bits = b'\x00\xff' * 4

img = bits_to_ndarray(bits, shape=(8, 8))
plt.imshow(img)
plt.show()


Oscar



More information about the Python-list mailing list