当前位置: 代码网 > it编程>前端脚本>Python > 计算机视觉智能中医(三):基于Unet模型的舌头舌体图片分割

计算机视觉智能中医(三):基于Unet模型的舌头舌体图片分割

2024年07月28日 Python 我要评论
python。舌象数据集包含舌象原图以及分割完成的二元图,共979*2张,示例图片如下:U-Net是一个优秀的语义分割模型,在中e诊中U-Net共三部分,分别是主干特征提取部分、加强特征提取部分、预测部分。利用主干特征提取部分获得5个初步有效的特征层,之后通过加强特征提取部分对上述获取到的5个有效特征层进行上采样并进行特征融合。最终获得了一个结合所有特征的有效特征层,并利用最终有效特征层对像素点进行预测,找到属于舌体的像素点。机器学习&人工智能

返回至系列文章导航博客


在这里插入图片描述

1 简介

舌体分割是舌诊检测的基础,唯有做到准确分割舌体才能保证后续训练以及预测的准确性。此部分真正的任务是在用户上传的图像中准确寻找到属于舌头的像素点。舌体分割属于生物医学图像分割领域。分割效果如下:

在这里插入图片描述

2 数据集介绍

舌象数据集包含舌象原图以及分割完成的二元图,共979*2张,示例图片如下:

在这里插入图片描述

3 模型介绍

u-net是一个优秀的语义分割模型,在中e诊中u-net共三部分,分别是主干特征提取部分、加强特征提取部分、预测部分。利用主干特征提取部分获得5个初步有效的特征层,之后通过加强特征提取部分对上述获取到的5个有效特征层进行上采样并进行特征融合。最终获得了一个结合所有特征的有效特征层,并利用最终有效特征层对像素点进行预测,找到属于舌体的像素点。具体操作详情如下图所示:

在这里插入图片描述

进行标注后利用pytorch框架构建u-net模型抓取舌象图像特征,预测舌象图像标签。为对模型进行评价,在训练中计算每次循环的平均损失率。最终每张图的损失了约为2%左右。具体的平均损失率变化如下图:

在这里插入图片描述

训练共历时4天,共979张标记图像,最终平均预测损失率约为2%。模型预测,即舌体分割的效果非常理想,在此展示当损失率为40%与损失率为2%时的分割结果示例,示例如下图所示:
(1)损失率为40%时分割结果图

在这里插入图片描述

(2)损失率为2%时分割结果图

在这里插入图片描述

根据模型预测结果对属于舌体的像素点进行匹配提取,将不属于舌体的部分以墨绿色进行填充,最终的舌体分割效果图如下:

在这里插入图片描述

4 代码实现细节

4.1 相关文件介绍

在这里插入图片描述

notedata文件夹中有分割标注图片、ordata文件夹中有原始图片、params文件夹中有训练模型文件、result文件夹中有测试样例图片、train_image文件夹中有训练过程图片。

4.2 utils.py

工具类:由于数据集中各个图片的大小是不一样的,为了保障后续工作可以顺利进行,这里应该定义一个工具类将图片可以等比例缩放至256*256(可以改看自己需求)。

from pil import image

def keep_image_size_open(path, size=(256, 256)):
    img = image.open(path)
    temp = max(img.size)
    mask = image.new('rgb', (temp, temp), (0,0,0))
    mask.paste(img, (0,0))
    mask = mask.resize(size)
    return mask

4.3 data.py

这里主要是将数据集中标签图片与原图进行匹配合并~具体步骤代码注释中有详解!

import os
from torch.utils.data import dataset
from utils import *
from torchvision import transforms
transform = transforms.compose([
    transforms.totensor()
    ])

class mydataset(dataset):
    def __init__(self, path):   #拿到标签文件夹中图片的名字
        self.path = path
        self.name = os.listdir(os.path.join(path, 'notedata'))
        
    def __len__(self):          #计算标签文件中文件名的数量
        return len(self.name)
    
    def __getitem__(self, index):   #将标签文件夹中的文件名在原图文件夹中进行匹配(由于标签是png的格式而原图是jpg所以需要进行一个转化)
        segment_name = self.name[index] #xx.png
        segment_path = os.path.join(self.path, 'notedata', segment_name)
        image_path = os.path.join(self.path, 'ordata', segment_name.replace('png', 'jpg')) #png与jpg进行转化
        
        segment_image = keep_image_size_open(segment_path)  #等比例缩放
        image = keep_image_size_open(image_path)            #等比例缩放
        
        return transform(image), transform(segment_image)

if __name__ == "__main__":
    data = mydataset("e:/item_time/project/unet/")
    print(data[0][0].shape)
    print(data[0][1].shape)

在这里插入图片描述

可见数据集已经规整!

4.4 net.py

unet网络的编写!

在这里插入图片描述

from torch import nn
import torch
from torch.nn import functional as f


class conv_block(nn.module):   #卷积
    def __init__(self, in_channel, out_channel):
        super(conv_block, self).__init__()
        self.layer = nn.sequential(
            nn.conv2d(in_channel, out_channel, 3, 1, 1, padding_mode='reflect', 
                      bias=false),
            nn.batchnorm2d(out_channel),
            nn.dropout2d(0.3),
            nn.leakyrelu(),
            nn.conv2d(out_channel, out_channel, 3, 1, 1, padding_mode='reflect', 
                      bias=false),
            nn.batchnorm2d(out_channel),
            nn.dropout2d(0.3),
            nn.leakyrelu()
            )
        
    def forward(self, x):
        return self.layer(x)
    
    
class downsample(nn.module):    #下采样
    def __init__(self, channel):
        super(downsample, self).__init__()
        self.layer = nn.sequential(
            nn.conv2d(channel, channel,3,2,1,padding_mode='reflect',
                      bias=false),
            nn.batchnorm2d(channel),
            nn.leakyrelu()
            
            )
        
    def forward(self,x):
        return self.layer(x)
    
    
class upsample(nn.module):   #上采样(最邻近插值法)
    def __init__(self, channel):
        super(upsample, self).__init__()
        self.layer = nn.conv2d(channel, channel//2,1,1)
        
    def forward(self,x, feature_map):
        up = f.interpolate(x, scale_factor=2, mode='nearest')
        out = self.layer(up)
        return torch.cat((out,feature_map),dim=1)
    
    
class unet(nn.module):
    def __init__(self):
        super(unet, self).__init__()
        self.c1=conv_block(3,64)
        self.d1=downsample(64)
        self.c2=conv_block(64, 128)
        self.d2=downsample(128)
        self.c3=conv_block(128,256)
        self.d3=downsample(256)
        self.c4=conv_block(256,512)
        self.d4=downsample(512)
        self.c5=conv_block(512,1024)
        self.u1=upsample(1024)
        self.c6=conv_block(1024,512)
        self.u2=upsample(512)
        self.c7=conv_block(512,256)
        self.u3=upsample(256)
        self.c8=conv_block(256,128)
        self.u4=upsample(128)
        self.c9=conv_block(128,64)
        
        self.out = nn.conv2d(64,3,3,1,1)
        self.th = nn.sigmoid()

       
        
    def forward(self,x):
        r1 = self.c1(x)
        r2 = self.c2(self.d1(r1))
        r3 = self.c3(self.d2(r2))
        r4 = self.c4(self.d3(r3))
        r5 = self.c5(self.d4(r4))
        
        o1 = self.c6(self.u1(r5,r4))
        o2 = self.c7(self.u2(o1,r3))
        o3 = self.c8(self.u3(o2,r2))
        o4 = self.c9(self.u4(o3,r1))
        
        return self.th(self.out(o4))
    
if __name__ == "__main__":
    x = torch.randn(2, 3, 256, 256)
    net  = unet()
    print(net(x).shape)
         

在这里插入图片描述

结果匹配说明没问题~

4.5 train.py

训练代码~

from torch import nn
from torch import optim
import torch
from data import *
from net import *
from torchvision.utils import save_image
from torch.utils.data import dataloader

device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
weight_path = 'params/unet.pth'
data_path = 'e:/item_time/project/unet/'
save_path = 'train_image'

if __name__ == "__main__":
    
    dic = []###
    
    data_loader = dataloader(mydataset(data_path),batch_size=3,shuffle=true)  #batch_size用3/4都可以看电脑性能
    net = unet().to(device)
    if os.path.exists(weight_path):
        net.load_state_dict(torch.load(weight_path))
        print('success load weight')
    else:
        print('not success load weight')
        
    opt = optim.adam(net.parameters())
    loss_fun = nn.bceloss()
    
    epoch = 1
    while true:
        avg = []###
        for i, (image,segment_image) in enumerate(data_loader):
            image,segment_image = image.to(device),segment_image.to(device)
            
            out_image = net(image)
            train_loss = loss_fun(out_image, segment_image)
            
            opt.zero_grad()
            train_loss.backward()
            opt.step()
            
            if i%5 == 0:
                print('{}-{}-train_loss===>>{}'.format(epoch,i,train_loss.item()))
                
            if i%50 == 0:
                torch.save(net.state_dict(), weight_path)
            #为方便看效果将原图、标签图、训练图进行拼接
            _image = image[0]
            _segment_image = segment_image[0]
            _out_image = out_image[0]
            
            img = torch.stack([_image,_segment_image,_out_image],dim=0)
            save_image(img, f'{save_path}/{i}.jpg')
            
            avg.append(float(train_loss.item()))###
            
        
        
        loss_avg = sum(avg)/len(avg)
        
        dic.append(loss_avg)
        
        epoch += 1
    print(dic)
    

在这里插入图片描述

可见代码成功运行~上面的损失率是在训练4天后的效果,刚开始肯定很大很差,需要有耐心!

4.6 test.py

测试代码,对图片进行智能分割~

from net import *
from utils import keep_image_size_open
import os
import torch
from data import *
from torchvision.utils import save_image
from pil import image
import numpy as np

net = unet().cpu()  #或者放在cuda上

weights = 'params/unet.pth'  #导入网络

if os.path.exists(weights):
    net.load_state_dict(torch.load(weights))
    print('success')
else:
    print('no loading')
    
_input = 'xxxx.jpg'  #导入测试图片

img = keep_image_size_open(_input)


img_data = transform(img)
print(img_data.shape)

img_data = torch.unsqueeze(img_data, dim=0)

print(img_data)
out = net(img_data)

save_image(out, 'result/result.jpg')
save_image(img_data, 'result/orininal.jpg')

print(out)

#e:\item_time\unet\ordata\4292.jpg

img_after = image.open(r"result\result.jpg")
img_before = image.open(r"result\orininal.jpg")
#img.show()
img_after_array = np.array(img_after)#把图像转成数组格式img = np.asarray(image)
img_before_array = np.array(img_before)

shape_after = img_after_array.shape
shape_before = img_before_array.shape

print(shape_after,shape_before)

#将分隔好的图片进行对应像素点还原,即将黑白分隔图转化为有颜色的提取图

if shape_after == shape_before:
    height = shape_after[0]
    width = shape_after[1]
    dst = np.zeros((height,width,3))
    for h in range(0,height):
        for w in range (0,width):
            (b1,g1,r1) = img_after_array[h,w]
            (b2,g2,r2) = img_before_array[h,w]
            
            if (b1, g1, r1) <= (90, 90, 90): 
                img_before_array[h, w] = (144,238,144) 
            dst[h,w] = img_before_array[h,w]
    img2 = image.fromarray(np.uint8(dst))
    img2.save(r"result\blend.png","png")

else:
    print("失败!")

结果展示:
(1)原图(orininal.jpg):

在这里插入图片描述

(2)模型分割图(result.jpg):

在这里插入图片描述

(3)对应像素点还原图(blend.png):就是将(2)中的图白色的部分用原图像素点填充,黑色的部分用绿色填充

在这里插入图片描述

在这里插入图片描述

(0)

相关文章:

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

发表评论

验证码:
Copyright © 2017-2025  代码网 保留所有权利. 粤ICP备2024248653号
站长QQ:2386932994 | 联系邮箱:2386932994@qq.com