w3resource

NumPy Binary operations: packbits() function

numpy.packbits() function

The packbits() function is used to pack the elements of a binary-valued array into bits in a uint8 array. The result is padded to full bytes by inserting zero bits at the end.

Some common applications of numpy.packbits() include:
Data Compression: Packing binary data into bytes for more efficient storage or transmission, especially in scenarios where data is primarily composed of binary values or sparse arrays.
Image Processing: Converting binary images or masks into compact byte arrays for more efficient storage, manipulation, or transmission.
Cryptography: Converting bit-level representations of encrypted data or keys into byte arrays for storage or transmission.
Network Communication: Packing binary data or bit fields into byte arrays for efficient transmission over network protocols that require byte-aligned data.

Syntax:

numpy.packbits(myarray, axis=None)

Parameters:

Name Description Required /
Optional
myarray An array of integers or booleans whose elements should be packed to bits. Required
axis The dimension over which bit-packing is done. None implies packing the flattened array. Optional

Return value:

packed [ndarray]
Array of type uint8 whose elements represent bits corresponding to the logical (0 or nonzero) value of the input elements. The shape of packed has the same number of dimensions as the input (unless axis is None, in which case the output is 1-D).

Example: Packing binary arrays into byte arrays with NumPy

>>> import numpy as np
>>> x = np.array([[[1,1,0], [0,1,0]], [[1,0,1], [0,0,1]]])
>>> y = np.packbits(x, axis=-1)
>>> y
array([[[192],
        [ 64]],

       [[160],
        [ 32]]], dtype=uint8)

In the above code, a 3-dimensional NumPy array x with the shape (2, 2, 3) is created. The numpy.packbits() function is used to pack the binary values in x along the last axis (axis=-1) into byte arrays. The resulting y array has the shape (2, 2, 1) and contains the packed byte representation of the input binary data.

Python Code Editor:

Previous: right_shift()
Next: unpackbits()



Follow us on Facebook and Twitter for latest update.