记录本人跑图片分割unet模型把无人机采集的大图裁剪为小图识别,把小图放到模型识别完之后,再将小图拼接成大图。分为三步,依次执行的。
1、因为unet输入是512x512,我先把大图修改成512x512的倍数,保证能裁剪
# 以下这段代码是修改图像分辨率
from PIL import Image
def add_white_edge(inImgPath, outImgPath, width, height):
inImg = Image.open(inImgPath)
bgWidth, bgHeight = inImg.size
ratio = min(width / bgWidth, height / bgHeight)
newWidth = int(bgWidth * ratio)
newHeight = int(bgHeight * ratio)
bgImg = Image.new("RGB", (width, height), (255, 255, 255))
bgImg.paste(inImg.resize((newWidth, newHeight), Image.LANCZOS), ((width - newWidth) // 2, (height - newHeight) // 2))
bgImg.save(outImgPath)
if __name__ == "__main__":
add_white_edge('D:/数据集/自选数据集/无人机大图/水平.png', #原大图路径
'D:/数据集/自选数据集/无人机大图/水平1.png', 24064, 4096) #原本图片是23818x4027,改成了24064x4096
第二
# 以下这段代码是将大图裁成小图
from PIL import Image
import os
Image.MAX_IMAGE_PIXELS = 2300000000
def cut_image(image, tile_size):
width, height = image.size
num_tiles_x = width // tile_size[0]
num_tiles_y = height // tile_size[1]
image_list = []
for y in range(num_tiles_y):
for x in range(num_tiles_x):
box = (x * tile_size[0], y * tile_size[1], (x + 1) * tile_size[0], (y + 1) * tile_size[1])
tile = image.crop(box)
image_list.append(tile)
return image_list
def save_images(image_list, out_dir):
if not os.path.exists(out_dir):
os.makedirs(out_dir)
for i, image in enumerate(image_list):
image.save(os.path.join(out_dir, f"{i + 1}.png"), "PNG")
def image_compose(image_list, out_path, rows, cols, tile_size):
canvas = Image.new("RGB", (cols * tile_size[0], rows * tile_size[1]))
for i, tile in enumerate(image_list):
x = i % cols
y = i // cols
canvas.paste(tile, (x * tile_size[0], y * tile_size[1]))
canvas.save(out_path)
if __name__ == "__main__":
file_path = "D:/数据集/自选数据集/无人机大图/水平1.png" #原文件
image = Image.open(file_path)
image_list = cut_image(image, (512, 512))
save_images(image_list, 'D:/数据集/自选数据集/无人机大图/img_小图') #裁成小图的文件名
image_compose(image_list, '最终整图.png', 47, 8, (512, 512)) #47列8行
#训练完之后以下这段代码是将图片再拼接起来
from PIL import Image
import os
def read_images(image_dir):
image_list = []
for filename in sorted(os.listdir(image_dir), key=lambda x: int(os.path.splitext(x)[0])):
image_path = os.path.join(image_dir, filename)
image = Image.open(image_path)
image_list.append(image)
return image_list
def image_compose(image_list, out_path, cols):
num_images = len(image_list)
rows = (num_images + cols - 1) // cols
tile_size = image_list[0].size
canvas_width = tile_size[0] * cols
canvas_height = tile_size[1] * rows
canvas = Image.new("RGB", (canvas_width, canvas_height))
for i, image in enumerate(image_list):
x = i % cols
y = i // cols
canvas.paste(image, (x * tile_size[0], y * tile_size[1]))
canvas.save(out_path)
if __name__ == "__main__":
image_dir = 'H:\wyh\无人机\img_out' #训练完的文件夹名
image_list = read_images(image_dir)
image_compose(image_list, 'H:\wyh\无人机\最终整图.png', 47) #最终图片,47是列