一、导入所需库
python
from PIL import Image
import torch
import numpy as np
import matplotlib.pyplot as plt
二、读取图片
python
pic = np.array(Image.open('venice-boat.jpg'))
上述代码解释:先用Image.open()方法读取jpg格式图片,再用np.array()方法将图片转成numpy数组(ndarray)格式。
三、建立张量
图片在PyTorch中以3维张量表示。以下代码将图片转换成张量形式:
python
pic_tensor = torch.from_numpy(pic)
打印张量数据内容:
python
print(pic_tensor)
输出:
python
tensor([[[ 47, 138, 221], # 每个像素点的RGB颜色值
[ 49, 138, 220],
[ 50, 139, 221],
...,
[ 89, 149, 221],
[ 87, 150, 221],
[ 86, 149, 220]],
[[ 47, 138, 221],
[ 49, 138, 220],
[ 50, 139, 221],
...,
[ 88, 148, 220],
[ 85, 148, 219],
[ 85, 148, 219]],
[[ 47, 138, 221],
[ 49, 138, 220],
[ 50, 139, 221],
...,
[ 84, 147, 218],
[ 84, 147, 218],
[ 83, 146, 217]],
...,
四、通过张量对图片进行操作
(注:在以下的各个操作下,还需要用plt.show()语句才能将图片输出到屏幕上。)
1、打印整张图片
python
plt.imshow(pic)
2、分RGB通道打印图片
输出通道1:
python
plt.imshow(pic_tensor[:, :, 0].numpy())
输出通道2:
python
plt.imshow(pic_tensor[:, :, 1].numpy())
输出通道3:
python
plt.imshow(pic_tensor[:, :, 2].numpy())
注意: 三通道并不是简单的算术叠加,例如以下代码的输出和原图大相径庭:
python
from PIL import Image
import torch
import numpy as np
import matplotlib.pyplot as plt
pic_1 = np.array(Image.open('Channel_1.jpg'))
pic_2 = np.array(Image.open('Channel_2.jpg'))
pic_3 = np.array(Image.open('Channel_3.jpg'))
pic_tensor_1 = torch.from_numpy(pic_1)
pic_tensor_2 = torch.from_numpy(pic_2)
pic_tensor_3 = torch.from_numpy(pic_3)
pic_tensor = pic_tensor_1 + pic_tensor_2 + pic_tensor_3
plt.imshow(pic_tensor.numpy())
plt.show()
输出图片:
3、裁剪图片
对图片张量的裁剪在其前2个维度上进行(第3个维度为颜色通道),示例代码如下:
python
plt.imshow(pic_tensor[50: 1050, 400: 800, :].numpy())
裁剪结果: