将二值 NumPy 数组的元素打包到 uint8 数组中的位中,打包轴为 1
要将二值数组的元素打包到 uint8 数组中的位中,请使用 Python NumPy 中的 **numpy.packbits()** 方法。结果通过在末尾插入零位来填充为完整的字节。轴使用 axis 参数设置。轴是进行位打包的维度。我们已将轴设置为 1。
轴是进行位打包的维度。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() 方法。轴使用 axis 参数设置。轴是进行位打包的维度:
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... [[[128 64 128]] [[128 128 64]] [[128 128 64]]]
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP