将二进制值 NumPy 数组的元素打包到 uint8 数组中的位中
要将二进制值数组的元素打包到 uint8 数组中的位中,请在 Python NumPy 中使用 **numpy.packbits()** 方法。结果通过在末尾插入零位填充到完整的字节。
轴是执行位打包的维度。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 数组中的位中,请在 Python NumPy 中使用 numpy.packbits() 方法。结果通过在末尾插入零位填充到完整的字节 -
res = np.packbits(arr)
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
res = np.packbits(arr)
print("
Result...
",res)输出
python3 main.py 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... [171 28 64]
广告
数据结构
网络
关系数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP