语义分割将大图切为512小图输入网络检测后再拼回原图大小

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)

把上面几个路径改成自己的就可以

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值