# pytorch 图像预处理之减去均值,除以方差的实例

```#coding=gbk
'''
GPU上面的环境变化太复杂，这里我直接给出在笔记本CPU上面的运行时间结果

img (168, 300, 3)
sub div in numpy,time 0.0110
sub div in torch.tensor,time 0.0070
sub div in torch.tensor with torchvision.transforms,time 0.0050
tensor1=tensor2
tensor2=tensor3

img (1079, 1349, 3)
sub div in numpy,time 0.1899
sub div in torch.tensor,time 0.1469
sub div in torch.tensor with torchvision.transforms,time 0.1109
tensor1=tensor2
tensor2=tensor3

'''

import numpy as np
import time
import torch
import torchvision.transforms as transforms
import cv2
img_path='F:\\2\\00004.jpg'
PIXEL_MEANS =(0.485, 0.456, 0.406)  #RGB format mean and variances
PIXEL_STDS = (0.229, 0.224, 0.225)

#输入文件路径，输出的应该是转换成torch.tensor的标准形式

#方式一  在numpy中进行减去均值除以方差，最后转换成torch.tensor
one_start=time.time()
img=img[:,:,::-1]
img=img.astype(np.float32, copy=False)
img/=255.0
img-=np.array(PIXEL_MEANS)
img/=np.array(PIXEL_STDS)
tensor1=torch.from_numpy(img.copy())
tensor1=tensor1.permute(2,0,1)
one_end=time.time()
print('sub div in numpy,time {:.4f}'.format(one_end-one_start))

del img

#方式二 转换成torch.tensor，再减去均值除以方差
two_start=time.time()
img=img[:,:,::-1]
print('img',img.shape,np.min(img),np.min(img))
tensor2=torch.from_numpy(img.copy()).float()
tensor2/=255.0
tensor2-=torch.tensor(PIXEL_MEANS)
tensor2/=torch.tensor(PIXEL_STDS)
tensor2=tensor2.permute(2,0,1)
two_end=time.time()
print('sub div in torch.tensor,time {:.4f}'.format(two_end-two_start))

del img

#方式三 转换成torch.tensor，再放到GPU上面，最后减去均值除以方差
# three_start=time.time()
# img=img[:,:,::-1]
# tensor3=torch.from_numpy(img.copy()).cuda().float()
# tensor3-=torch.tensor(PIXEL_MEANS).cuda()
# tensor3/=torch.tensor(PIXEL_STDS).cuda()
# three_end=time.time()
# print('sub div in torch.tensor on cuda,time {:.4f}'.format(three_end-three_start))

# del img

#方式四 转换成torch.tensor，使用transform方法减去均值除以方差
four_start=time.time()
img=img[:,:,::-1]
transform=transforms.Compose(
[transforms.ToTensor(),transforms.Normalize(PIXEL_MEANS, PIXEL_STDS)]
)
tensor4=transform(img.copy())
four_end=time.time()
print('sub div in torch.tensor with torchvision.transforms,time {:.4f}'.format(four_end-four_start))

del img

if torch.sum(tensor1-tensor2)<=1e-3:
print('tensor1=tensor2')
if torch.sum(tensor2-tensor4)==0:
print('tensor2=tensor3')
# if tensor3==tensor4:
#   print('tensor3=tensor4')
```