pytorch图像读取(cv2&PIL,numpy&tensor相关小知识)

pytorch图像读取(cv2&PIL,numpy&tensor相关小知识),第1张

torch.tensor与numpy array转换相关问题
  1. CV2.imread(file)返回的是numpy array,且形状为[h,w,c],若要被pytorch搭建的网络处理,需先转为tensor,并且要x.permute(2,0,1)转换为[c,h,w]结构。
  2. numpy的device只能是cpu,而tensor则cpu,gpu均可,若tensor转numpy还要注意将tensor先转到cpu。
  3. numpy转tensor: torch.from_numpy()
    tensor转numpy: tensor.numpy()。
  4. require-grade的tensor无法直接转numpy数组,要先detach,即teansor.detach().numpy。
cv2/Dataloader/PIL返回图像对比
  1. 使用PIL得到的图片尺寸是[h,w,c],通道为RGB,取值范围0-255。

  2. 使用DataLoader得到的图像尺寸是[N,C, h, w],通道为RGB,适用于pytorch卷积的尺寸,取值范围0-1。tensor类型。

  3. 使用cv2得到的图像尺寸是[h, w, c],通道为BGR,取值范围0-255。numpy数组。

因此,若来源不同的图像要混合处理,一定注意转换数据类型,以及是否需255归一化或反归一化,尤其cv2最特别,其通道为BGR,若转为其他类型还要转为RGB。转换方法:

sample = cv2.cvtColor(sample, cv2.COLOR_BGR2RGB)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/915739.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-16
下一篇2022-05-16

发表评论

登录后才能评论

评论列表(0条)

    保存