使用NumPy将uint8数组的元素解包到沿0轴的二值输出数组中


要将uint8数组的元素解包到二值输出数组中,可以使用Python NumPy中的**numpy.unpackbits()**方法。结果为二值(0或1)。轴是进行位解包的维度。轴使用“axis”参数设置。

输入数组的每个元素都表示一个位字段,应将其解包到二值输出数组中。输出数组的形状可以是一维(如果axis为None)或与输入数组相同,并且沿指定的轴进行解包。

轴是进行位解包的维度。None表示解包扁平化数组。“count”参数是沿轴解包的元素数量,作为取消打包非八的倍数大小的效果的一种方式。非负数表示仅解包count位。负数表示从末尾修剪掉这么多位。None表示解包整个数组(默认值)。大于可用位数的计数将向输出添加零填充。负计数不得超过可用位数。

顺序是返回位的顺序。“big”将模拟bin(val),3 = 0b00000011 ⇒ [0, 0, 0, 0, 0, 0, 1, 1],“little”将反转顺序为[1, 1, 0, 0, 0, 0, 0, 0]。默认为“big”。

步骤

首先,导入所需的库:

import numpy as np

创建一个二维数组。我们使用“dtype”参数设置uint8类型:

arr = np.array([[4, 8], [6, 19], [27, 35]], dtype=np.uint8)

显示我们的数组:

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.unpackbits()方法。结果为二值(0或1)。轴是进行位解包的维度。轴使用“axis”参数设置:

res = np.unpackbits(arr, axis = 0)
print("
Result...
",res)

示例

import numpy as np

# Create a 2d array
# We have set uint8 type using the "dtype" parameter
arr = np.array([[4, 8], [6, 19], [27, 35]], dtype=np.uint8)

# 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 unpack elements of a uint8 array into a binary-valued output array, use the numpy.unpackbits() method in Python Numpy # The result is binary-valued (0 or 1). # The axis is the dimension over which bit-unpacking is done. # The axis is set using the "axis" parameter res = np.unpackbits(arr, axis = 0) print("
Result...
",res)

输出

Array...
[[ 4 8]
[ 6 19]
[27 35]]

Array datatype...
uint8

Array Dimensions...
2

Our Array Shape...
(3, 2)

Elements in the Array...
6

Result...
[[0 0]
[0 0]
[0 0]
[0 0]
[0 1]
[1 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 0]
[0 1]
[0 0]
[1 0]
[1 1]
[0 1]
[0 0]
[0 0]
[0 1]
[1 0]
[1 0]
[0 0]
[1 1]
[1 1]]

更新于:2022年2月17日

88次浏览

启动您的职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.