opencv读取图片BGR2RGB img[:,:,::-1]

对于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)
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值