pillow与transform的使用
1 pillow基本用法
具体实现见代码
import matplotlib.pyplot as plt
from PIL import Image
img = Image.open('1.jpg').convert('RGB') # 读取图像
plt.imshow(img) # 显示图像
print(img.size) # 输出(宽,高)
pillow读取返回的是Image的实例,包含很多的方法:
new_img = img.save(save_path) # 保存图片
new_img = img.resize((224,400)) # 缩放图片,不保持原图的长宽比,注意224为宽,400为高
new_img = img.thumbnail((400,400)) # 保持原图的长宽比,输入为最大值
new_img = img.rotate(90) # 逆时针旋转90度
new_img = img.transpose(Image.FLIP_LEFT_RIGHT) # 左右对称
img_draw = ImageDraw.Draw(img) # 在图片上写字
img_draw.text((10,100), 'A bird', fill='green')
2 transforms
样例代码
https://blog.csdn.net/u011995719/article/details/85107009
将PIL Image或者 ndarray 转换为tensor,并且归一化至[0-1]
transform = transforms.Compose([
transforms.ToTensor() # 将[0-255] -> [0.0, 1.0]
])
new_img = transform(img)
print(new_img)
new_img = transforms.ToPILImage()(new_img).convert('RGB')
plt.imshow(new_img)
channel = (channel - mean)/std
transform = transforms.Compose([
transforms.ToTensor(),
transforms.Normalize(mean = (0.5, 0.5, 0.5), std = (0.5, 0.5, 0.5))
]
)