使用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次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始
廣告