利用 Pillow 和 torchvision.transform 实现的图像剪切和复原,用于遥感图像的预测(目前对一般图像可用,遥感图像还未实际操作)
- 图像剪切
from torchvision import transforms
from PIL import Image
def imageCrop(img, iNo, croped_size, stride):
'''img: Image.open()读取的图片
iNo: 图片的编码
croped_size: 裁剪大小
stride: 步长
'''
img = transforms.Pad(stride)(img)
x_num , y_num = 0, 0
for x in range(0, img.size[1], stride):
y_num = 0
for y in range(0, img.size[0], stride):
x2, y2 = x + croped_size, y + croped_size
x2 = img.size[1] if x2 > img.size[1] else x2
y2 = img.size[0] if y2 > img.size[0] else y2
croped = img.crop((y, x, y2, x2)) # (w1, h1, w2, h2)
croped.save(f'./data/split/{iNo}/[{x_num},{y_num}].jpg')
y_num += 1
x_num += 1
- 图像复原
def imageRestoration(img, iNo, stride):
'''img: Image.open()读取的图片
iNo: 图片的编码
stride: 步长
'''
bkImage = Image.new('RGB', (img.size[0]+2*stride, img.size[1]+2*stride)) # 创建一个新图
x_num, y_num = 0, 0
for x in range(0, bkImage.size[1], stride):
y_num = 0
for y in range(0, bkImage.size[0], stride):
from_image = Image.open(f'./data/split/1/[{x_num},{y_num}].jpg')
bkImage.paste(from_image, (y, x))
y_num += 1
x_num += 1
to_image = bkImage.crop((stride, stride, bkImage.size[0]-stride, bkImage.size[1]-stride))
to_image.save(f'./data/splice/{iNo}.jpg')
- 效果预览
img = Image.open('./data/1.jfif').convert('RGB')
imageCrop(img, 1, 256, 128)
imageRestoration(img, 1, 128)