將二進位制值 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]
廣告