目录
2. 用transforms.ToTensor图片转为张量,并(自动)归一化
1. 用mping载入图片
import matplotlib.pyplot as plt
import torch
import matplotlib.image as maping
import torchvision.transforms as transforms
#import the underlying picture by apply maping
myimg = maping.imread('C:/Users/liyzc/Desktop/胖胖/和胖胖在宁波/IMG_20201007_122412.jpg')
#show the picture
plt.imshow(myimg)
plt.axis('off')
plt.show()
print(myimg.shape)
2. 用transforms.ToTensor图片转为张量,并(自动)归一化
pil2tensor = transforms.ToTensor()
rgb_image = pil2tensor(myimg)
print(rgb_image)
print(rgb_image[0][0])
print(rgb_image.shape)
3. 定义卷积核(方法参考)
sobelfilter = torch.tensor([[-1., 0, 1.],
[-2., 0, 2.],
[-1., 0, 1.]]*3).reshape([1,3,3,3])
print(sobelfilter)
#note: *3 means tripling this ARRAY. compare:
# tensor([[-1., 0, 1.],
[-2., 0, 2.],
[-1., 0, 1.]])*3
4. 图片卷积函数处理
op = torch.nn.functional.conv2d(rgb_image.unsqueeze(0),soberfilter, stride=3,padding=(1,1))
#tensor转化为图片数据
ret = (op - op.min())/(op.max()-op.min())
ret = (ret.clamp(0.,1.)*255).int()#逆归一化搞回去,并转化乘整数
plt.imshow(ret.squeeze(), cmap='ocean_r')
plt.axis('off')
plt.show()