将二值 NumPy 数组的元素打包到沿负轴的 uint8 数组中的位中


要在 Python NumPy 中将二值数组的元素打包到 uint8 数组中的位中,请使用 **numpy.packbits()** 方法。结果通过在末尾插入零位来填充到完整的字节。轴使用 axis 参数设置。轴是进行位打包的维度。我们设置了负轴。

轴是进行位打包的维度。None 表示打包扁平化数组。bitorder 是输入位的顺序。“big”将模拟 bin(val),[0, 0, 0, 0, 0, 0, 1, 1] ⇒ 3 = 0b00000011,“little”将反转顺序,因此 [1, 1, 0, 0, 0, 0, 0, 0] ⇒ 3。默认为“big”。

packbits() 函数返回 uint8 类型的数组,其元素表示与输入元素的逻辑值 (0 或非零值) 对应的位。packed 的形状与输入具有相同数量的维度。

步骤

首先,导入所需的库:

import numpy as np

创建一个 3D 数组:

arr = np.array([[ [1,0,1], [0,1,0]], [ [1,1,0], [0,0,1]], [ [1, 1, 0],[0, 0, 1] ]])

显示我们的数组:

print("Array...
",arr)

获取数据类型:

print("
Array datatype...
",arr.dtype)

获取数组的维度:

print("
Array Dimensions...
",arr.ndim)

获取数组的形状:

print("
Our Array Shape...
",arr.shape)

获取数组的元素个数:

print("
Elements in the Array...
",arr.size)

要将二值数组的元素打包到 uint8 数组中的位中,请使用 numpy.packbits() 方法。结果通过在末尾插入零位来填充到完整的字节:

res = np.packbits(arr, axis = -1)
print("
Result...
",res)

示例

import numpy as np

# Create a 3d array
arr = np.array([[ [1,0,1], [0,1,0]],[ [1,1,0], [0,0,1]],[[1, 1, 0],[0, 0, 1] ]])

# Displaying our array
print("Array...
",arr) # Get the datatype print("
Array datatype...
",arr.dtype) # Get the dimensions of the Array print("
Array Dimensions...
",arr.ndim) # Get the shape of the Array print("
Our Array Shape...
",arr.shape) # Get the number of elements of the Array print("
Elements in the Array...
",arr.size) # To pack the elements of a binary-valued array into bits in a uint8 array, use the numpy.packbits() method in Python Numpy # The result is padded to full bytes by inserting zero bits at the end # The axis is set using the axis parameter # The axis is the dimension over which bit-packing is done. res = np.packbits(arr, axis = -1) print("
Result...
",res)

输出

Array...
[[[1 0 1]
[0 1 0]]

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

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

Array datatype...
int64

Array Dimensions...
3

Our Array Shape...
(3, 2, 3)

Elements in the Array...
18

Result...
[[[160]
[ 64]]

[[192]
[ 32]]

[[192]
[ 32]]]

更新于:2022年2月18日

249 次浏览

启动您的职业生涯

完成课程获得认证

开始学习
广告
© . All rights reserved.