Numpy 中解包 uint8 陣列元素並僅解包某些位


要將 uint8 陣列的元素解包到二進位制值的輸出陣列中,請在 Python Numpy 中使用 **numpy.unpackbits()** 方法。結果為二進位制值(0 或 1)。軸是執行位解包的維度。軸使用“axis”引數設定。要設定要解包的元素數量,請使用“count”引數。非負數表示僅解包 count 位。

輸入陣列的每個元素都表示一個位欄位,應將其解包到二進位制值的輸出陣列中。輸出陣列的形狀要麼是一維的(如果 axis 為 None),要麼與輸入陣列的形狀相同,並且沿指定的軸進行解包。

軸是執行位解包的維度。None 表示解包扁平化的陣列。“count”引數是要沿軸解包的元素數量,作為撤消打包大小不為 8 的倍數的效果的一種方法。非負數表示僅解包 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() 方法。非負數表示僅解包 count 位。我們已將 count 設定為 7,這意味著我們將僅解包 7 位 -

res = np.unpackbits(arr, axis = 1, count = 7)
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 # To set the number of element to unpack, use the "count" parameter # A non-negative number means to only unpack count bits # We have set 7 for count, that means we will only unpack 7 bits res = np.unpackbits(arr, axis = 1, count = 7) 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 1 0]
[0 0 0 0 0 1 1]
[0 0 0 1 1 0 1]]

更新於: 2022-02-17

853 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.