OpenCV获得的张量的数据顺序为(HWC)
import torch
import cv2
img = cv2.imread('./example.jpg')
print('0:', img.shape[0]) # 0: 426
print('1:', img.shape[1]) # 1: 640
print('2:', img.shape[2]) # 2: 3
print(img.shape[0], img.shape[1], chanel) # 426 640 3
426表示高(H);640表示宽(W);3表示通道(C),所以在后续要送入torch中,需要先对张量的维度顺序进行变换,用函数permute(2, 0, 1)
import torch
import cv2
img = cv2.imread('./example.jpg')
img = torch.FloatTensor(img).permute(2, 0, 1)
print('0:', img.shape[0]) # 0: 3
print('1:', img.shape[1]) # 1: 426
print('2:', img.shape[2]) # 2: 640
print(img.shape[0], img.shape[1], chanel) # 3 426 640
# 变换前: np.ndarray h*w*c
# 变换后: np.ndarray c*h*w