采用UNet完成磁瓦图片分割

本文基于中科院自动所磁瓦缺陷公开数据集,采用PaddlePaddle框架构建UNet模型进行分割实验。数据集含1568组图像,分训练、验证、测试集。模型经60轮训练,评价指标为:P=0.955、R=0.737、F1=0.832、ACC=0.973、IOU=0.713,为后续迁移学习至红外热成像无损检测奠定基础。

☞☞☞AI 智能聊天, 问答助手, AI 智能搜索, 免费无限量使用 DeepSeek R1 模型☜☜☜

采用unet完成磁瓦图片分割 - 创想鸟

Unet模型分割磁瓦缺陷

数据集采用中科院自动所公开数据集,具体内容见:https://aistudio.baidu.com/aistudio/datasetdetail/224907/0本文主要参考:图像分割的打怪升级之路——UNet、PSPNet、Deeplab:https://aistudio.baidu.com/aistudio/projectdetail/2148971?channelType=0&channel=0&sUid=1019401&ts=1687278761304背景:本人为初级炼丹师,目前炼丹领域主要集中在图像分割与生成式模型。目前:正在构建红外热成像的无损检测数据集,该数据集能够为后续无损检测的后处理研究提供一定的帮助。但目前为止正在构建实验设备阶段,所以欲先从磁瓦缺陷分割然后通过迁移学习,完成后续的组合模型的构建。结果: unet评价指标为: P:0.955250726851333, R:0.7372399981794183, F1:0.8322043172342575, ACC:0.973421630859375, IOU:0.7126283557268431

1. 数据集预处理以及参数设置

1.1 导入必要的库函数

值得注意的是paddlepaddle-gpu版本为:2.0.2

In [1]

import osimport shutilimport numpy as npfrom paddle.io import Dataset,DataLoaderfrom paddle.vision import transforms as Tfrom paddle.nn import functional as Fimport cv2import paddleimport matplotlib.pyplot as pltimport paddle.nn as nnfrom tqdm import tqdmfrom PIL import Imagefrom visualdl import LogWriterfrom paddle import nn

       

/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/__init__.py:107: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import MutableMapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/rcsetup.py:20: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import Iterable, Mapping/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/colors.py:53: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  from collections import Sized

       

1.2 定义超参数

训练历史loss与val-loss的数据导出

log_path路径为训练中的val-loss,train-loss,val-acc,train-acc储存位置,可以通过左侧的可视化打开,然后通过下载数据为csv,完成后续绘图

其余注释已经写得很清楚,不多作介绍

In [2]

# 训练迭代次数epochs = 60#批量大小batch_size=100#验证集的数量eval_num=150# 测试集的数量test_num=150# 所有图像的大小image_size=(128,128)# 标签图片路径label_images_path="/home/aistudio/data/expansion_annotations"# 输入图像路径input_images_path="/home/aistudio/data/expansion_images"# 保存文件的路径放在work中,每重启项目,都会清空# 存放图片路径filepath = "/home/aistudio/data/"# 模型权重等保存路径modle_and_weight_path = '/home/aistudio/data/modle_weight'# 验证训练效果路径datatest_path = '/home/aistudio/data/pre_test_label'# 训练日志保存log_path = '/home/aistudio/data/train_log'

   

1.3 解压数据集

将数据从/home/aistudio/data/data224907/解压到data/,这样能够减轻加载时间,因为data文件夹每次启动会重置

In [3]

!unzip -oq /home/aistudio/data/data224907/expansion_annotations.zip -d data/!unzip -oq /home/aistudio/data/data224907/expansion_images.zip -d data/

   

1.4 获取图片路径+图片名 组成的数组

函数:def get_img_files(directory):将path=directory文件夹下的所有后缀名为png或jpg的文件 获取文件夹下所有文件名称,返回完整路径

输入:

  directory: 存放图片的文件夹

           输出:

  sorted(img_files):  排序后的(地址+名称)

           In [4]

def get_img_files(directory):    # 获取指定目录下的所有文件名    file_list = os.listdir(directory)      # 使用列表推导式筛选出所有后缀名为.png的文件名    img_files = [os.path.join(directory, file) for file in file_list if file.endswith('.png') or file.endswith('.jpg')]        # 不排序的话文件名会与标签名混乱    return sorted(img_files)# 获取输入图片(1568,1)images = np.expand_dims(np.array(get_img_files(input_images_path)),axis=1)# 获取输入图片对应得标签(1568,1)labels = np.expand_dims(np.array(get_img_files(label_images_path)),axis=1)# 拼接np ----》(1568,2)data = np.array(np.concatenate((images,labels),axis=1))# 打乱数据集 不影响images与labels的关系np.random.shuffle(data)# 分割数据集train_data=data[:-(eval_num + test_num),:]eval_data=data[-(eval_num + test_num):-test_num,:]test_data=data[-test_num:,:]#打印数据格式,以及图片与对应标签print(train_data.shape, train_data[0])print(eval_data.shape, eval_data[0])print(test_data.shape, test_data[0])

       

(1268, 2) ['/home/aistudio/data/expansion_images/Imgs-exp6_num_352572.jpg' '/home/aistudio/data/expansion_annotations/Imgs-exp6_num_352572.png'](150, 2) ['/home/aistudio/data/expansion_images/Imgs-exp3_num_322643.jpg' '/home/aistudio/data/expansion_annotations/Imgs-exp3_num_322643.png'](150, 2) ['/home/aistudio/data/expansion_images/Imgs-exp3_num_186885_ud.jpg' '/home/aistudio/data/expansion_annotations/Imgs-exp3_num_186885_ud.png']

       

2. 数据增强处理与数据提取器的构建

2.1 对图片完成增强处理

In [5]

train_transform=T.Compose([            T.Resize(image_size),  #裁剪            T.ColorJitter(0.1,0.1,0.1,0.1), #亮度,对比度,饱和度和色调            T.Transpose(), #CHW            T.Normalize(mean=0.,std=255.) #归一化        ])eval_transform=T.Compose([            T.Resize(image_size),            T.Transpose(),            T.Normalize(mean=0.,std=255.)        ])

   

2.2 定义数据提取器

In [6]

class ImageDataset(Dataset):    def __init__(self,path,transform):        super(ImageDataset, self).__init__()        self.path=path        self.transform=transform    def _load_image(self,path):        '''        该方法作用为通过路径获取图像        '''        img=cv2.imread(path)        img=cv2.resize(img,image_size)        return img    def __getitem__(self,index):        '''        这里之所以不对label使用transform,因为观察数据集发现label的图像矩阵主要为0或1        但偶尔也有0-255的值,所以要对label分情况处理        而对data都进行transform是因为data都是彩色图片,图像矩阵皆为0-255,所以可以统一处理        '''        path=self.path[index]        if len(path)==2:            data_path,label_path=path            # 获取图片数组            data,label=self._load_image(data_path),self._load_image(label_path)            # 对图片数组归一化            data,label=self.transform(data),label            # 参数 (2,0,1) 表示将第三维度(channel)作为第一维度,第一维度(height)作为第二维度,            # 第二维度(width)作为第三维度            label = label.transpose((2, 0, 1))            # 提取这个数组的第一行,保留该行所有列,也就是将其尺寸从(1, height, width)变为了            # (height, width),即去掉了第一维的维数,并将其赋值给了变量 label。            label = label[0, :, :]            label = np.expand_dims(label, axis=0)            if True in (label>1):                label=label/255.            label = label.astype("int64")            return data,label         # 获取的路径只有一个,那么就是输入图片(用于没有标签的测试集)        if len(path)==1:            data=self._load_image(path[0])            data=self.transform(data)            return data    def __len__(self):        return len(self.path)# 获取数据读取器train_dataset=ImageDataset(train_data,train_transform)eval_dataset=ImageDataset(eval_data,eval_transform)test_dataset=ImageDataset(test_data,eval_transform)train_dataloader=DataLoader(train_dataset,batch_size=batch_size,shuffle=True,drop_last=True)eval_dataloader=DataLoader(eval_dataset,batch_size=batch_size,shuffle=True,drop_last=True)

   

2.3 观察训练集

In [7]

def show_images(imgs):    #imgs是一个列表,列表里是多个tensor对象    #定义总的方框的大小    plt.figure(figsize=(3*len(imgs),3), dpi=80)    for i in range(len(imgs)):        #定义小方框        plt.subplot(1, len(imgs), i + 1)        #matplotlib库只能识别numpy类型的数据,tensor无法识别        imgs[i]=imgs[i].numpy()        #展示取出的数据        plt.imshow(imgs[i][0],cmap="gray",aspect="auto")        #设置坐标轴        plt.xticks([])        plt.yticks([])data,label=next(train_dataloader())show_images([data[0],label[0]])

       

/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:2349: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  if isinstance(obj, collections.Iterator):/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/cbook/__init__.py:2366: DeprecationWarning: Using or importing the ABCs from 'collections' instead of from 'collections.abc' is deprecated, and in 3.8 it will stop working  return list(data) if isinstance(data, collections.MappingView) else data/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/image.py:425: DeprecationWarning: np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead  a_min = np.asscalar(a_min.astype(scaled_dtype))/opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/matplotlib/image.py:426: DeprecationWarning: np.asscalar(a) is deprecated since NumPy v1.16, use a.item() instead  a_max = np.asscalar(a_max.astype(scaled_dtype))

       

               

3. 搭建模型

3.1 unet 结构图

采用UNet完成磁瓦图片分割 - 创想鸟        In [8]

import paddlefrom paddle import nnclass Encoder(nn.Layer):# 下采样    def __init__(self, num_channels, num_filters):        super(Encoder,self).__init__()#继承父类的初始化        # 图像通道数变为num_filters,长宽不变        self.conv1 = nn.Conv2D(in_channels=num_channels,                                out_channels=num_filters,                                kernel_size=3,                                stride=1,                                padding=1)        self.bn1 = nn.BatchNorm(num_filters,act='relu')        self.conv2 = nn.Conv2D(in_channels=num_filters,                                out_channels=num_filters,                                kernel_size=3,                                stride=1,                                padding=1)        self.bn2 = nn.BatchNorm(num_filters,act='relu')        self.pool = nn.MaxPool2D(kernel_size=2,stride=2,padding='SAME')# 图像长宽缩小一半,通道数不变        def forward(self, inputs):            x = self.conv1(inputs)        x = self.bn1(x)        x = self.conv2(x)        x = self.bn2(x)        # 输出1用于拼接        x_conv = x        # 输出2用于下采样        x_pool =self.pool(x)        return x_conv, x_poolclass Decoder(nn.Layer):    def __init__(self, num_channels,num_filters):        super(Decoder,self).__init__()        self.up = nn.Conv2DTranspose(in_channels=num_channels,                                    out_channels=num_filters,                                    kernel_size=2,                                    stride=2,                                    padding=0)# 图片分辨率变大一倍,通道数不变        self.conv1 = nn.Conv2D(in_channels=num_filters*2,                                out_channels=num_filters,                                kernel_size=3,                                stride=1,                                padding=1)# 因为拼接的缘故所以是2倍的关系        self.bn1 = nn.BatchNorm(num_filters,act='relu')        self.conv2 = nn.Conv2D(in_channels=num_filters,                                out_channels=num_filters,                                kernel_size=3,                                stride=1,                                padding=1)        self.bn2 = nn.BatchNorm(num_filters,act='relu')    def forward(self, input_conv, input_pool):                x = self.up(input_pool)        # 计算上采样后,与input_conv的分辨率差值,然后进行填充        h_diff = (input_conv.shape[2]-x.shape[2])        w_diff = (input_conv.shape[3]-x.shape[3])        # 对上下左右表示填充0        pad = nn.Pad2D(padding=[h_diff//2,h_diff-h_diff//2,w_diff//2,w_diff-w_diff//2])        x = pad(x)        x = paddle.concat([input_conv,x],axis=1)        x = self.conv1(x)        x = self.bn1(x)        x = self.conv2(x)        x = self.bn2(x)        return xclass UNet(nn.Layer):    def __init__(self, num_classes=2):        super(UNet,self).__init__()        self.down1 = Encoder(num_channels=3, num_filters=64)        self.down2 = Encoder(num_channels=64, num_filters=128)        self.down3 = Encoder(num_channels=128, num_filters=256)        self.down4 = Encoder(num_channels= 256, num_filters=512)        self.mid_conv1 = nn.Conv2D(512,1024,1)        self.mid_bn1 = nn.BatchNorm(1024,act='relu')        self.mid_conv2 = nn.Conv2D(1024,1024,1)        self.mid_bn2 = nn.BatchNorm(1024,act='relu')        self.up4 = Decoder(1024,512)        self.up3 = Decoder(512,256)        self.up2 = Decoder(256,128)        self.up1 = Decoder(128,64)        # 使用1*1卷积,softmax做分类        self.last_conv = nn.Conv2D(64,num_classes,1)        def forward(self, inputs):        x1, x = self.down1(inputs)        x2, x = self.down2(x)        x3, x = self.down3(x)        x4, x = self.down4(x)        x = self.mid_conv1(x)        x = self.mid_bn1(x)        x = self.mid_conv2(x)        x = self.mid_bn2(x)        x = self.up4(x4, x)        x = self.up3(x3, x)        x = self.up2(x2, x)        x = self.up1(x1, x)                x = self.last_conv(x)        return  x    # 打印模型结构,需要不打印模型结构注释下一行即可paddle.summary(UNet(2), (1, 3, 128, 128))

       

--------------------------------------------------------------------------------------------------------------  Layer (type)                 Input Shape                          Output Shape                 Param #    ==============================================================================================================    Conv2D-1               [[1, 3, 128, 128]]                    [1, 64, 128, 128]                1,792        BatchNorm-1             [[1, 64, 128, 128]]                   [1, 64, 128, 128]                 256          Conv2D-2               [[1, 64, 128, 128]]                   [1, 64, 128, 128]               36,928        BatchNorm-2             [[1, 64, 128, 128]]                   [1, 64, 128, 128]                 256         MaxPool2D-1             [[1, 64, 128, 128]]                    [1, 64, 64, 64]                   0           Encoder-1              [[1, 3, 128, 128]]           [[1, 64, 128, 128], [1, 64, 64, 64]]        0           Conv2D-3                [[1, 64, 64, 64]]                     [1, 128, 64, 64]               73,856        BatchNorm-3             [[1, 128, 64, 64]]                     [1, 128, 64, 64]                 512          Conv2D-4               [[1, 128, 64, 64]]                     [1, 128, 64, 64]               147,584       BatchNorm-4             [[1, 128, 64, 64]]                     [1, 128, 64, 64]                 512         MaxPool2D-2             [[1, 128, 64, 64]]                     [1, 128, 32, 32]                  0           Encoder-2               [[1, 64, 64, 64]]           [[1, 128, 64, 64], [1, 128, 32, 32]]        0           Conv2D-5               [[1, 128, 32, 32]]                     [1, 256, 32, 32]               295,168       BatchNorm-5             [[1, 256, 32, 32]]                     [1, 256, 32, 32]                1,024         Conv2D-6               [[1, 256, 32, 32]]                     [1, 256, 32, 32]               590,080       BatchNorm-6             [[1, 256, 32, 32]]                     [1, 256, 32, 32]                1,024        MaxPool2D-3             [[1, 256, 32, 32]]                     [1, 256, 16, 16]                  0           Encoder-3              [[1, 128, 32, 32]]           [[1, 256, 32, 32], [1, 256, 16, 16]]        0           Conv2D-7               [[1, 256, 16, 16]]                     [1, 512, 16, 16]              1,180,160      BatchNorm-7             [[1, 512, 16, 16]]                     [1, 512, 16, 16]                2,048         Conv2D-8               [[1, 512, 16, 16]]                     [1, 512, 16, 16]              2,359,808      BatchNorm-8             [[1, 512, 16, 16]]                     [1, 512, 16, 16]                2,048        MaxPool2D-4             [[1, 512, 16, 16]]                      [1, 512, 8, 8]                   0           Encoder-4              [[1, 256, 16, 16]]            [[1, 512, 16, 16], [1, 512, 8, 8]]         0           Conv2D-9                [[1, 512, 8, 8]]                      [1, 1024, 8, 8]                525,312       BatchNorm-9              [[1, 1024, 8, 8]]                     [1, 1024, 8, 8]                 4,096         Conv2D-10               [[1, 1024, 8, 8]]                     [1, 1024, 8, 8]               1,049,600     BatchNorm-10              [[1, 1024, 8, 8]]                     [1, 1024, 8, 8]                 4,096     Conv2DTranspose-1           [[1, 1024, 8, 8]]                     [1, 512, 16, 16]              2,097,664       Conv2D-11              [[1, 1024, 16, 16]]                    [1, 512, 16, 16]              4,719,104     BatchNorm-11             [[1, 512, 16, 16]]                     [1, 512, 16, 16]                2,048         Conv2D-12              [[1, 512, 16, 16]]                     [1, 512, 16, 16]              2,359,808     BatchNorm-12             [[1, 512, 16, 16]]                     [1, 512, 16, 16]                2,048         Decoder-1      [[1, 512, 16, 16], [1, 1024, 8, 8]]            [1, 512, 16, 16]                  0       Conv2DTranspose-2          [[1, 512, 16, 16]]                     [1, 256, 32, 32]               524,544        Conv2D-13              [[1, 512, 32, 32]]                     [1, 256, 32, 32]              1,179,904     BatchNorm-13             [[1, 256, 32, 32]]                     [1, 256, 32, 32]                1,024         Conv2D-14              [[1, 256, 32, 32]]                     [1, 256, 32, 32]               590,080      BatchNorm-14             [[1, 256, 32, 32]]                     [1, 256, 32, 32]                1,024         Decoder-2     [[1, 256, 32, 32], [1, 512, 16, 16]]            [1, 256, 32, 32]                  0       Conv2DTranspose-3          [[1, 256, 32, 32]]                     [1, 128, 64, 64]               131,200        Conv2D-15              [[1, 256, 64, 64]]                     [1, 128, 64, 64]               295,040      BatchNorm-15             [[1, 128, 64, 64]]                     [1, 128, 64, 64]                 512          Conv2D-16              [[1, 128, 64, 64]]                     [1, 128, 64, 64]               147,584      BatchNorm-16             [[1, 128, 64, 64]]                     [1, 128, 64, 64]                 512          Decoder-3     [[1, 128, 64, 64], [1, 256, 32, 32]]            [1, 128, 64, 64]                  0       Conv2DTranspose-4          [[1, 128, 64, 64]]                    [1, 64, 128, 128]               32,832         Conv2D-17             [[1, 128, 128, 128]]                   [1, 64, 128, 128]               73,792       BatchNorm-17             [[1, 64, 128, 128]]                   [1, 64, 128, 128]                 256          Conv2D-18              [[1, 64, 128, 128]]                   [1, 64, 128, 128]               36,928       BatchNorm-18             [[1, 64, 128, 128]]                   [1, 64, 128, 128]                 256          Decoder-4     [[1, 64, 128, 128], [1, 128, 64, 64]]          [1, 64, 128, 128]                  0           Conv2D-19              [[1, 64, 128, 128]]                    [1, 2, 128, 128]                 130      ==============================================================================================================Total params: 18,472,450Trainable params: 18,460,674Non-trainable params: 11,776--------------------------------------------------------------------------------------------------------------Input size (MB): 0.19Forward/backward pass size (MB): 174.75Params size (MB): 70.47Estimated Total Size (MB): 245.40--------------------------------------------------------------------------------------------------------------

       

{'total_params': 18472450, 'trainable_params': 18460674}

               

3.2 采用高层API训练模型

注意:本段落的运行会清空之前的所有数据文件,并重新创建空的文件夹!同时该段落的训练时长与epochs的大小高度相关,请耐心等待训练完成!
若需要查看的loss,acc需要,打开左侧的可视化,路径设置为/home/aistudio/data/train_log,即可
采用UNet完成磁瓦图片分割 - 创想鸟 采用UNet完成磁瓦图片分割 - 创想鸟        

In [9]

# 判断日志文件是否存在,存在就删除,然后创建空的文件夹用于存log文件def del_file(path):    if os.path.exists(path):        shutil.rmtree(path)    os.mkdir(path)del_file(log_path)del_file(modle_and_weight_path)del_file(test_path)print(paddle.device.get_device())paddle.device.set_device('gpu:0')# 创建调用模型modle = paddle.Model(UNet(2))# opt = paddle.optimizer.Momentum(learning_rate=1e-3,parameters=modle.parameters(),weight_decay=1e-2)opt = paddle.optimizer.AdamW(learning_rate=1e-3,parameters=modle.parameters(),weight_decay=1e-2)modle.prepare(opt, paddle.nn.CrossEntropyLoss(axis=1),metrics=paddle.metric.Accuracy())# 创建回调,将训练过程中的val_loss,train_loss,val_acc,train_acc,保存到文件夹/home/aistudio/data/train_log中callback = paddle.callbacks.VisualDL(log_dir = log_path)# 请耐心等待它训练完成,若需要观察每次训练的acc与loss,可以将verbose设置为1,(申请精品项目输出不能太长,所以就默认为0,也就是不打印)# save_freq=5,每训练5次,保存一次模型# 模型的权重文件保存在/home/aistudio/data/modle_weight# 训练log_freq次打印一次结果modle.fit(train_dataloader,        eval_dataloader,        epochs=epochs,        verbose=0,        save_dir = modle_and_weight_path,        save_freq=5,        log_freq=1,        callbacks=callback)

       

cpu

       —————————————————————————ValueError Traceback (most recent call last)/tmp/ipykernel_1308/2477755552.py in  12 13 print(paddle.device.get_device()) —> 14paddle.device.set_device(‘gpu:0’) 15 16 /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/device/__init__.py in set_device(device) 314 data = paddle.stack([x1,x2], axis=1) 315 “”” –> 316  place =_convert_to_place(device) 317 framework._set_expected_place(place) 318 return place /opt/conda/envs/python35-paddle120-env/lib/python3.7/site-packages/paddle/device/__init__.py in _convert_to_place(device) 257 raise ValueError( 258  “The device should not be {}, since PaddlePaddle is ” –> 259 “not compiled with CUDA”.format(avaliable_gpu_device)) 260 device_info_list = device.split(‘:’, 1) 261 device_id = device_info_list[1] ValueError: The device should not be , since PaddlePaddle is not compiled with CUDA

3.3 预测图象

将测试集预测后的数据放入地址为:test——path中。
预测图片为: 采用UNet完成磁瓦图片分割 - 创想鸟            In [ ]

# 预测图像保存绝对路径if os.path.exists(test_path):    shutil.rmtree(test_path)os.mkdir(test_path)#读取模型参数文件路径save_dir = test_pathcheckpoint_path = modle_and_weight_path + "/final"#实例化,U-Netmodel = paddle.Model(UNet(2))       # 加载最后训练的模型model.load(checkpoint_path)# 生成预测图片到文件夹/home/aistudio/data/pre_test_label# img格式为:【3,128,128】for i,img in tqdm(enumerate(test_dataset)):    #print(paddle.to_tensor(img[0]).shape)    img=paddle.to_tensor(img[0]).unsqueeze(0)    predict=np.array(model.predict_batch(img)).squeeze(0).squeeze(0)    predict=predict.argmax(axis=0)    image_path=test_dataset.path[i]    path_lst=image_path[0].split("/")    save_path=os.path.join(save_dir,path_lst[-1][:-5])+"p.jpg"    cv2.imwrite(save_path,predict*255)

   

3.4 评估指标计算

包含常用指标:

precision: 预测结果的平均精度recall: 预测结果的平均召回率f1score: 预测结果的平均 F1 值accuracy: 预测结果的整体准确率IOU:预测结果的平均交并比**In [ ]

# # 评价网络模型结果#########################################################################def evaluate_segmentation_performance(pred_masks, true_masks):    """    计算图像分割性能评估指标    参数:        - pred_masks: numpy 数组,表示预测的掩码图像,形状为 (N, H, W, 1),取值为 0 或 1        - true_masks: numpy 数组,表示真实的掩码图像,形状为 (N, H, W, 1),取值为 0 或 1    返回值:        - precision: 预测结果的平均精度        - recall: 预测结果的平均召回率        - f1score: 预测结果的平均 F1 值        - accuracy: 预测结果的整体准确率        - IOU:预测结果的平均交并比    """    # 将预测结果和真实结果转换为 int 类型,以避免出现数据类型错误    pred_masks = np.round(pred_masks).astype(np.int32)    true_masks = np.round(true_masks).astype(np.int32)    # 计算 TP,FP 和 FN    TP = np.sum((pred_masks == 1) & (true_masks == 1))    FP = np.sum((pred_masks == 1) & (true_masks == 0))    FN = np.sum((pred_masks == 0) & (true_masks == 1))    print(TP, FP, FN)    # 计算准确率、召回率和 F1 值    precision = TP / (TP + FP)    recall = TP / (TP + FN)    f1score = 2 * precision * recall / (precision + recall)    # 计算整体准确率    accuracy = np.mean(pred_masks == true_masks)    # 计算 IOU    intersection = np.sum(pred_masks & true_masks)    union = np.sum(pred_masks | true_masks)    iou = intersection / union    return precision, recall, f1score, accuracy, iou

   In [ ]

# 提取经过(resize,标签二值化)处理的图片列表eval_img_list = [test_dataset.__getitem__(i)[0] for i in range(len(test_dataset))]eval_label_list = [test_dataset.__getitem__(i)[1] for i in range(len(test_dataset))]# img灰度--->[150,3,128,128]img = paddle.to_tensor(eval_img_list)# label二值--->[150,1,128,128]label = np.array(paddle.to_tensor(eval_label_list))# predict其中2代表两通道预测各类别的概率--->[150,2,128,128]predict = np.array(model.predict_batch(img)).squeeze(0)# pre_img_list-->[150,128,128,1]pre_img_list = paddle.to_tensor([predict[i].argmax(axis=0) for i in range(len(predict))]).unsqueeze(-1)# pre_img_list-->[150,1,128,128]pre_img_list = np.array(pre_img_list.transpose((0, 3, 1, 2)))# 计算指标precision, recall, f1score, accuracy, iou = evaluate_segmentation_performance(pre_img_list, label)print('unet评价指标为:nP:{},nR:{},nF1:{},nACC:{},nIOU:{}'.format(precision, recall, f1score, accuracy, iou))

   In [ ]


   

以上就是采用UNet完成磁瓦图片分割的详细内容,更多请关注创想鸟其它相关文章!

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。
如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至 chuangxiangniao@163.com 举报,一经查实,本站将立刻删除。
发布者:程序猿,转转请注明出处:https://www.chuangxiangniao.com/p/52932.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2025年11月9日 07:04:05
下一篇 2025年11月9日 07:07:21

相关推荐

  • Uniapp 中如何不拉伸不裁剪地展示图片?

    灵活展示图片:如何不拉伸不裁剪 在界面设计中,常常需要以原尺寸展示用户上传的图片。本文将介绍一种在 uniapp 框架中实现该功能的简单方法。 对于不同尺寸的图片,可以采用以下处理方式: 极端宽高比:撑满屏幕宽度或高度,再等比缩放居中。非极端宽高比:居中显示,若能撑满则撑满。 然而,如果需要不拉伸不…

    2025年12月24日
    400
  • 如何让小说网站控制台显示乱码,同时网页内容正常显示?

    如何在不影响用户界面的情况下实现控制台乱码? 当在小说网站上下载小说时,大家可能会遇到一个问题:网站上的文本在网页内正常显示,但是在控制台中却是乱码。如何实现此类操作,从而在不影响用户界面(UI)的情况下保持控制台乱码呢? 答案在于使用自定义字体。网站可以通过在服务器端配置自定义字体,并通过在客户端…

    2025年12月24日
    800
  • 如何在地图上轻松创建气泡信息框?

    地图上气泡信息框的巧妙生成 地图上气泡信息框是一种常用的交互功能,它简便易用,能够为用户提供额外信息。本文将探讨如何借助地图库的功能轻松创建这一功能。 利用地图库的原生功能 大多数地图库,如高德地图,都提供了现成的信息窗体和右键菜单功能。这些功能可以通过以下途径实现: 高德地图 JS API 参考文…

    2025年12月24日
    400
  • 如何使用 scroll-behavior 属性实现元素scrollLeft变化时的平滑动画?

    如何实现元素scrollleft变化时的平滑动画效果? 在许多网页应用中,滚动容器的水平滚动条(scrollleft)需要频繁使用。为了让滚动动作更加自然,你希望给scrollleft的变化添加动画效果。 解决方案:scroll-behavior 属性 要实现scrollleft变化时的平滑动画效果…

    2025年12月24日
    000
  • 如何为滚动元素添加平滑过渡,使滚动条滑动时更自然流畅?

    给滚动元素平滑过渡 如何在滚动条属性(scrollleft)发生改变时为元素添加平滑的过渡效果? 解决方案:scroll-behavior 属性 为滚动容器设置 scroll-behavior 属性可以实现平滑滚动。 html 代码: click the button to slide right!…

    2025年12月24日
    500
  • 如何选择元素个数不固定的指定类名子元素?

    灵活选择元素个数不固定的指定类名子元素 在网页布局中,有时需要选择特定类名的子元素,但这些元素的数量并不固定。例如,下面这段 html 代码中,activebar 和 item 元素的数量均不固定: *n *n 如果需要选择第一个 item元素,可以使用 css 选择器 :nth-child()。该…

    2025年12月24日
    200
  • 使用 SVG 如何实现自定义宽度、间距和半径的虚线边框?

    使用 svg 实现自定义虚线边框 如何实现一个具有自定义宽度、间距和半径的虚线边框是一个常见的前端开发问题。传统的解决方案通常涉及使用 border-image 引入切片图片,但是这种方法存在引入外部资源、性能低下的缺点。 为了避免上述问题,可以使用 svg(可缩放矢量图形)来创建纯代码实现。一种方…

    2025年12月24日
    100
  • 如何解决本地图片在使用 mask JS 库时出现的跨域错误?

    如何跨越localhost使用本地图片? 问题: 在本地使用mask js库时,引入本地图片会报跨域错误。 解决方案: 要解决此问题,需要使用本地服务器启动文件,以http或https协议访问图片,而不是使用file://协议。例如: python -m http.server 8000 然后,可以…

    2025年12月24日
    200
  • 如何让“元素跟随文本高度,而不是撑高父容器?

    如何让 元素跟随文本高度,而不是撑高父容器 在页面布局中,经常遇到父容器高度被子元素撑开的问题。在图例所示的案例中,父容器被较高的图片撑开,而文本的高度没有被考虑。本问答将提供纯css解决方案,让图片跟随文本高度,确保父容器的高度不会被图片影响。 解决方法 为了解决这个问题,需要将图片从文档流中脱离…

    2025年12月24日
    000
  • 为什么 CSS mask 属性未请求指定图片?

    解决 css mask 属性未请求图片的问题 在使用 css mask 属性时,指定了图片地址,但网络面板显示未请求获取该图片,这可能是由于浏览器兼容性问题造成的。 问题 如下代码所示: 立即学习“前端免费学习笔记(深入)”; icon [data-icon=”cloud”] { –icon-cl…

    2025年12月24日
    200
  • 如何利用 CSS 选中激活标签并影响相邻元素的样式?

    如何利用 css 选中激活标签并影响相邻元素? 为了实现激活标签影响相邻元素的样式需求,可以通过 :has 选择器来实现。以下是如何具体操作: 对于激活标签相邻后的元素,可以在 css 中使用以下代码进行设置: li:has(+li.active) { border-radius: 0 0 10px…

    2025年12月24日
    100
  • 如何模拟Windows 10 设置界面中的鼠标悬浮放大效果?

    win10设置界面的鼠标移动显示周边的样式(探照灯效果)的实现方式 在windows设置界面的鼠标悬浮效果中,光标周围会显示一个放大区域。在前端开发中,可以通过多种方式实现类似的效果。 使用css 使用css的transform和box-shadow属性。通过将transform: scale(1.…

    2025年12月24日
    200
  • 为什么我的 Safari 自定义样式表在百度页面上失效了?

    为什么在 Safari 中自定义样式表未能正常工作? 在 Safari 的偏好设置中设置自定义样式表后,您对其进行测试却发现效果不同。在您自己的网页中,样式有效,而在百度页面中却失效。 造成这种情况的原因是,第一个访问的项目使用了文件协议,可以访问本地目录中的图片文件。而第二个访问的百度使用了 ht…

    2025年12月24日
    000
  • 如何用前端实现 Windows 10 设置界面的鼠标移动探照灯效果?

    如何在前端实现 Windows 10 设置界面中的鼠标移动探照灯效果 想要在前端开发中实现 Windows 10 设置界面中类似的鼠标移动探照灯效果,可以通过以下途径: CSS 解决方案 DEMO 1: Windows 10 网格悬停效果:https://codepen.io/tr4553r7/pe…

    2025年12月24日
    000
  • 使用CSS mask属性指定图片URL时,为什么浏览器无法加载图片?

    css mask属性未能加载图片的解决方法 使用css mask属性指定图片url时,如示例中所示: mask: url(“https://api.iconify.design/mdi:apple-icloud.svg”) center / contain no-repeat; 但是,在网络面板中却…

    2025年12月24日
    000
  • 如何用CSS Paint API为网页元素添加时尚的斑马线边框?

    为元素添加时尚的斑马线边框 在网页设计中,有时我们需要添加时尚的边框来提升元素的视觉效果。其中,斑马线边框是一种既醒目又别致的设计元素。 实现斜向斑马线边框 要实现斜向斑马线间隔圆环,我们可以使用css paint api。该api提供了强大的功能,可以让我们在元素上绘制复杂的图形。 立即学习“前端…

    2025年12月24日
    000
  • 图片如何不撑高父容器?

    如何让图片不撑高父容器? 当父容器包含不同高度的子元素时,父容器的高度通常会被最高元素撑开。如果你希望父容器的高度由文本内容撑开,避免图片对其产生影响,可以通过以下 css 解决方法: 绝对定位元素: .child-image { position: absolute; top: 0; left: …

    2025年12月24日
    000
  • 使用 Mask 导入本地图片时,如何解决跨域问题?

    跨域疑难:如何解决 mask 引入本地图片产生的跨域问题? 在使用 mask 导入本地图片时,你可能会遇到令人沮丧的跨域错误。为什么会出现跨域问题呢?让我们深入了解一下: mask 框架假设你以 http(s) 协议加载你的 html 文件,而当使用 file:// 协议打开本地文件时,就会产生跨域…

    2025年12月24日
    200
  • CSS 帮助

    我正在尝试将文本附加到棕色框的左侧。我不能。我不知道代码有什么问题。请帮助我。 css .hero { position: relative; bottom: 80px; display: flex; justify-content: left; align-items: start; color:…

    2025年12月24日 好文分享
    200
  • 前端代码辅助工具:如何选择最可靠的AI工具?

    前端代码辅助工具:可靠性探讨 对于前端工程师来说,在HTML、CSS和JavaScript开发中借助AI工具是司空见惯的事情。然而,并非所有工具都能提供同等的可靠性。 个性化需求 关于哪个AI工具最可靠,这个问题没有一刀切的答案。每个人的使用习惯和项目需求各不相同。以下是一些影响选择的重要因素: 立…

    2025年12月24日
    000

发表回复

登录后才能评论
关注微信