对于opencv 读取图片 有时候看迷糊 了,记录一下自己看吧。。。
img0 = cv2.imread(img_path)
img = img[:, :, ::-1].transpose(2, 0, 1)
对于img0 得到的是BGR格式 ;shape为(H,W,C)但是我们需要的图片往往是RGB,shape为(H,W,C),所以很自然需要转换
- img[:, :, ::-1] BGR to RGB
opencv读取的image shape为(H,W,C),其中channel 维度是BGR格式 ,变为RGB 只需要在C维度步长取-1逆着遍历就可以了(数组的基本操作)
a = np.arange(27).reshape(3,3,3)
print(a)
print(a[:,:,::-1])
output:
[[[ 0 1 2]
[ 3 4 5]
[ 6 7 8]]
[[ 9 10 11]
[12 13 14]
[15 16 17]]
[[18 19 20]
[21 22 23]
[24 25 26]]]
a[:,:,::-1]:
[[[ 2 1 0]
[ 5 4 3]
[ 8 7 6]]
[[11 10 9]
[14 13 12]
[17 16 15]]
[[20 19 18]
[23 22 21]
[26 25 24]]]
其他常见等价操作
#0
image = cv2.imread(path)
image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB) # cv内置函数转化为RGB
#1
image = cv2.imread(path)
image = image[:, :, (2, 1, 0)]
#2
image = cv2.imread(path)
image = image[:,:,::-1]
插一句:对于PIL.Image读取的图片是正常的
image = Image.open(path)
- transpose(2, 0, 1) 就是将(H,W,C)to (C,H,W)
等价
image = torch.from_numpy(image).permute(2, 0, 1)