Unpackbits() function of numpy

Overview:

  • The numpy.unpackbits() unpacks an ndarray of numpy.uint8 integers into an ndarray of zeros and ones.

  • Note that the data type of the ndarray is not numpy.bool. It remains as numpy.uint8.

  • The numpy.unpackbits() does the reverse of numpy.packbits().

unpackbits() function of numpy

Example 1:

# Example Python program that unpacks an ndarray of numpy.uint8 instances 
# into an ndarray of bits
import numpy

# Create an ndarray. Elements are of type numpy.uint8
intArray = numpy.ndarray(shape = (2, 2), 
                           dtype = numpy.uint8)

# Fill the ndarray with values
intArray[0][0] = 10
intArray[0][1] = 15
intArray[1][0] = 20
intArray[1][1] = 25

# Get the binary bits of the integer as an ndarray 
bitArray = numpy.unpackbits(intArray, axis = 1)
print("Input array:")
print(intArray)

print("Bit array when axis=1:")
print(bitArray)
print(bitArray.dtype)
bitArray = numpy.unpackbits(intArray, axis = 0)
print("Bit array when axis=0:")
print(bitArray)

Output:

Input array:

[[10 15]

 [20 25]]

Bit array when axis=1:

[[0 0 0 0 1 0 1 0 0 0 0 0 1 1 1 1]

 [0 0 0 1 0 1 0 0 0 0 0 1 1 0 0 1]]

uint8

Bit array when axis=0:

[[0 0]

 [0 0]

 [0 0]

 [0 0]

 [1 1]

 [0 1]

 [1 1]

 [0 1]

 [0 0]

 [0 0]

 [0 0]

 [1 1]

 [0 1]

 [1 0]

 [0 0]

 [0 1]]

Example 2:

# Example Python program that unpacks an ndarray
# of numpy.uint8 types in little endian bit order
import numpy

intVals = numpy.ndarray(shape = (2, 2), 
                         dtype = numpy.uint8)
intVals[0][0] = 1
intVals[0][1] = 120
intVals[1][0] = 128
intVals[1][1] = 255

unpacked = numpy.unpackbits(intVals, bitorder = 'little')
print("An ndarray of numpy.uint8 elements:")
print(intVals)
print("Unpacked ndarray - least significant bits are placed first:")
print(unpacked)

Output:

An ndarray of numpy.uint8 elements:

[[  1 120]

 [128 255]]

Unpacked ndarray - least significant bits are placed first:

[1 0 0 0 0 0 0 0 0 0 0 1 1 1 1 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1]

 


Copyright 2024 © pythontic.com