我有一個包含 X 行 Y 十六進制代碼的檔案,如下所示:
FFFFFF 123456 453623 ....
354352 5AB12A 123789 ....
...... ...... ...... ....
我的最終目標是在 Python 中將其轉換為 OpenCV 影像,即 NumPy 陣列。我也在使用 Pandas,read_table因為它比通過 python 檔案讀取更快。所以現在我有了 Pandas DB 的十六進制,并對其應用了一些轉換:
data = pd.read_table('ИРС/sample/0', sep=' ', header=None, dtype=str)
data = data.iloc[:,:-1]
data = data.applymap(lambda x: int(x, 16))
data = data.applymap(lambda x: np.array([x>>16, x>>8, x]).astype(np.uint8))
現在,當我將其轉換為 NumPU 陣列時,通過data.to_numpy()和 run cv2.cvtColor(img, cv2.COLOR_BGR2HSV),出現以下錯誤:
> - src data type = 17 is not supported
這表明我在陣列中使用了帶符號的整數,但事實并非如此。
我的問題是,我如何轉換它,我是否正在做 Pandas 到 cv2 的轉換?
uj5u.com熱心網友回復:
建議你把資料轉換成整數后,再把DataFrame轉換成NumPy陣列,再用NumPy繼續轉換。
您可以使用以下階段:
從十六進制轉換為整數。
data = data.applymap(lambda x: int(x, 16))轉換為 NumPy 型別的陣列
np.uint32并使其連續(因為下一個操作“.view(np.uint8)”需要連續資料)。data = np.ascontiguousarray(data.to_numpy(np.uint32))使用
.view(np.uint8)- 每個 uint32 元素被視為 4 個 uint8 元素。
資料格式采用類似 RGBA 的格式(第 4 個 0 元素可以被認為是 alpha 通道 - 應該洗掉第 4 個元素)。data = data.view(np.uint8).reshape((data.shape[0], data.shape[1], 4))使用 OpenCV 從 RGBA 轉換為 BGR(假設輸入代表的是 RGB)。
img = cv2.cvtColor(data, cv2.COLOR_RGBA2BGR)
完整的代碼示例:
import pandas as pd
import numpy as np
import cv2
data = pd.read_table('0.txt', sep=' ', header=None, dtype=str)
# data:
# 0 1 2
# 0 FFFFFF 123456 453623
# 1 354352 5AB12A 123789
#data = data.iloc[:,:-1]
data = data.applymap(lambda x: int(x, 16)) # Convert from hex to int
# data:
# 0 1 2
# 0 16777215 1193046 4535843
# 1 3490642 5943594 1193865
# data = data.applymap(lambda x: np.array([x>>16, x>>8, x]).astype(np.uint8))
# Convert to NumPy array of type np.uint32, make it contiguous, because the next operation ".view(np.uint8)" requires contiguous data.
data = np.ascontiguousarray(data.to_numpy(np.uint32))
# data:
# array([[16777215, 1193046, 4535843],
# [ 3490642, 5943594, 1193865]], dtype=uint32)
# Use .view(np.uint8) - each uint32 element is viewed as 4 uint8 elements.
# The data format applies RGBA-like format (the 4'th 0 element may be considered to be alpha).
data = data.view(np.uint8).reshape((data.shape[0], data.shape[1], 4))
# data:
# array([[[255, 255, 255, 0], [ 86, 52, 18, 0], [ 35, 54, 69, 0]],
# [[ 82, 67, 53, 0], [ 42, 177, 90, 0], [137, 55, 18, 0]]], dtype=uint8)
# Convert from RGBA to BGR
img = cv2.cvtColor(data, cv2.COLOR_RGBA2BGR)
# img:
# array([[[255, 255, 255], [ 18, 52, 86], [ 69, 54, 35]],
# [[ 53, 67, 82], [ 90, 177, 42], [ 18, 55, 137]]], dtype=uint8)
# Show image for testing
#cv2.imshow('img', img)
#cv2.waitKey()
#cv2.destroyAllWindows()
筆記:
- 使用技巧
data.view(np.uint8).reshape可能不直觀。使用移位操作
將每個uint32元素轉換為三個uint8元素也很好。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/374021.html
