from PIL import Image
import time
# 引入自己的网络
from segformer import SegFormer_Segmentation
segformer = SegFormer_Segmentation()
# 待预测大图路径
input_path = './img/1.jpg'
# 训练好的权重路径
pth_path = './model_data/best_epoch_weights.pth'
# 预测结果小图保存路径
output_path = './img/predict_output/'
# 预测结果拼接大图保存路径
output_path_big = './img/result.jpg'
# 类别
name_classes = ["_background_",]
def cut_to_512(pic_path,output_path):
#要分割后的尺寸
cut_width = 512
cut_length = 512
# 读取要分割的图片,以及其尺寸等数据
picture = Image.open(pic_path)
(width, length) = picture.size
# 计算可以划分的横纵的个数
num_width = int(width / cut_width)
num_length = int(length / cut_length)
if(width % cut_width != 0):
num_width = num_width + 1
if(length % cut_length != 0):
num_length = num_length + 1
for i in range(0, num_width):
for j in range(0, num_length):
new_image = picture.crop((i*cut_width, j*cut_length, (i+1)*cut_width, (j+1)*cut_length))
predict_img = segformer.detect_image(new_image, count=False, name_classes=name_classes)
result_path = output_path + '{}_{}.jpg'.format(j+1,i+1)
predict_img.save(result_path)
print("预测完成")
def tran512_to1(img512_path,result_path,bigimg_path):
#要分割后的尺寸
cut_width = 512
cut_length = 512
# 读取要分割的图片,以及其尺寸等数据
picture = Image.open(bigimg_path)
(width, length) = picture.size
# 计算可以划分的横纵的个数
num_width = int(width / cut_width)
num_length = int(length / cut_length)
if(width % cut_width != 0):
num_width = num_width + 1
if(length % cut_length != 0):
num_length = num_length + 1
for i in range(0, num_width):
for j in range(0, num_length):
img512 = Image.open(img512_path + '{}_{}.jpg'.format(j+1,i+1))
picture.paste(img512, (i*cut_width, j*cut_length))
picture.save(result_path)
print("成功")
cut_to_512(input_path,output_path)
tran512_to1(output_path,output_path_big,input_path)
把上面几个路径改成自己的就可以