Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #41125

Re: Reversing bits in a byte

References <20130311153254.078484489A7@nhs-pd1e-esg101.ad1.nhs.net> <20130312124931.C08D44482E5@nhs-pd1e-esg001.ad1.nhs.net> <20130312132840.B5A8D44863A@nhs-pd1e-esg102.ad1.nhs.net>
From Oscar Benjamin <oscar.j.benjamin@gmail.com>
Date 2013-03-12 14:59 +0000
Subject Re: Reversing bits in a byte
Newsgroups comp.lang.python
Message-ID <mailman.3232.1363100379.2939.python-list@python.org> (permalink)

Show all headers | View raw


On 12 March 2013 13:28, Robert Flintham <Robert.Flintham@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

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Re: Reversing bits in a byte Oscar Benjamin <oscar.j.benjamin@gmail.com> - 2013-03-12 14:59 +0000

csiph-web