views:

968

answers:

2

I wish to implement a 2d bit map class in Python. The class would have the following requirements:

  1. Allow the creating of arbitrarily sized 2d bitmaps. i.e. to create an 8 x 8 bitmap (8 bytes), something like:

    bitmap = Bitmap(8,8)
    
  2. provide an API to access the bits in this 2d map as boolean or even integer values, i.e.:

    if bitmap[1, 2] or bitmap.get(0, 1)
    
  3. Able to retrieve the data as packed Binary data. Essentially it would be each row of the bit map concatenated and returned as Binary data. It may be padded to the nearest byte or something similar.

    bitmap.data()
    
  4. Be able to create new maps from the binary data retrieved:

    new_bitmap = Bitmap(8, 8, bitmap.data())
    

I know Python is able to perform binary operations, but I'd like some suggestions as how best to use them to implement this class.

+3  A: 

No need to create this yourself.

Use the very good Python Imaging Library (PIL)

Ber
+4  A: 

Bit-Packing numpy ( SciPY ) arrays does what you are looking for. The example shows 4x3 bit (Boolean) array packed into 4 8-bit bytes. unpackbits unpacks uint8 arrays into a Boolean output array that you can use in computations.

>>> a = np.array([[[1,0,1],
...                [0,1,0]],
...               [[1,1,0],
...                [0,0,1]]])
>>> b = np.packbits(a,axis=-1)
>>> b
array([[[160],[64]],[[192],[32]]], dtype=uint8)

If you need 1-bit pixel images, PIL is the place to look.

gimel