Unet网络实战(基于Pytorch)

replace函数用法
在这里插入图片描述
glob.glob用法

特别注意:在初始化数据集的时候,输入的路径需要输入绝对路径,TMD这就是个神坑,用相对路径用了一早上发现返回的是空列表,浪费一上午的时间找bug
在这里插入图片描述
文件结构如下
在这里插入图片描述
在这里插入图片描述
保持原通道只需令第二个参数为-1即可
在这里插入图片描述
有关if __name__ == "__main__":的解释:
name 是当前模块名,当模块被直接运行时模块名为 main 。这句话的意思就是,当模块被直接运行时,以下代码块将被运行,当模块是被导入时,代码块不被运行。

在这里插入图片描述

from model.unet_model import UNet
from utils.dataset import ISBI_Loader
from torch import optim
import torch.nn as nn
import torch

def train_net(net, device, data_path, epochs=40, batch_size=1, lr=0.00001):
    # 加载训练集
    isbi_dataset = ISBI_Loader(data_path)
    train_loader = torch.utils.data.DataLoader(dataset=isbi_dataset,
                                               batch_size=batch_size, 
                                               shuffle=True)
    # 定义RMSprop算法
    optimizer = optim.RMSprop(net.parameters(), lr=lr, weight_decay=1e-8, momentum=0.9)
    # 定义Loss算法
    criterion = nn.BCEWithLogitsLoss()
    # best_loss统计,初始化为正无穷
    best_loss = float('inf')
    # 训练epochs次
    for epoch in range(epochs):
        # 训练模式
        net.train()
        # 按照batch_size开始训练
        for image, label in train_loader:
            optimizer.zero_grad()
            # 将数据拷贝到device中
            image = image.to(device=device, dtype=torch.float32)
            label = label.to(device=device, dtype=torch.float32)
            # 使用网络参数,输出预测结果
            pred = net(image)
            # 计算loss
            loss = criterion(pred, label)
            print('Loss/train', loss.item())
            # 保存loss值最小的网络参数
            if loss < best_loss:
                best_loss = loss
                torch.save(net.state_dict(), 'best_model.pth')
            # 更新参数
            loss.backward()
            optimizer.step()

if __name__ == "__main__":
    # 选择设备,有cuda用cuda,没有就用cpu
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # 加载网络,图片单通道1,分类为1。
    net = UNet(n_channels=1, n_classes=1)
    # 将网络拷贝到deivce中
    net.to(device=device)
    # 指定训练集地址,开始训练
    data_path = "data/train/"
    train_net(net, device, data_path)
import glob
import numpy as np
import torch
import os
import cv2
from model.unet_model import UNet

if __name__ == "__main__":
    # 选择设备,有cuda用cuda,没有就用cpu
    device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
    # 加载网络,图片单通道,分类为1。
    net = UNet(n_channels=1, n_classes=1)
    # 将网络拷贝到deivce中
    net.to(device=device)
    # 加载模型参数
    net.load_state_dict(torch.load('best_model.pth', map_location=device))
    # 测试模式
    net.eval()
    # 读取所有图片路径
    tests_path = glob.glob('E:\download1\Deep-Learning-master\Deep-Learning-master\Pytorch-Seg\lesson-2\data/test/*.png')
    # 遍历素有图片
    for test_path in tests_path:
        # 保存结果地址
        save_res_path = test_path.split('.')[0] + '_res.png'
        # 读取图片
        img = cv2.imread(test_path)
        # 转为灰度图
        img = cv2.cvtColor(img, cv2.COLOR_RGB2GRAY)
        # 转为batch为1,通道为1,大小为512*512的数组
        img = img.reshape(1, 1, img.shape[0], img.shape[1])
        # 转为tensor
        img_tensor = torch.from_numpy(img)
        # 将tensor拷贝到device中,只用cpu就是拷贝到cpu中,用cuda就是拷贝到cuda中。
        img_tensor = img_tensor.to(device=device, dtype=torch.float32)
        # 预测
        pred = net(img_tensor)
        print('预测的pred是',pred)
        # 提取结果
        pred = np.array(pred.data.cpu()[0])[0]
        print('np.array(pred.data.cpu()[0])[0]的结果是',pred)
        # 处理结果
        pred[pred >= 0.5] = 255
        print()

        pred[pred < 0.5] = 0
        # 保存图片
        cv2.imwrite(save_res_path, pred)
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
好的,以下是基于PyTorch实现的简单U-Net网络。 ```python import torch.nn as nn import torch.nn.functional as F class DoubleConv(nn.Module): # 定义一个DoubleConv类,表示U-Net网络的基本结构 def __init__(self, in_channels, out_channels): super(DoubleConv, self).__init__() # 定义两个卷积层 self.conv = nn.Sequential( nn.Conv2d(in_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True), nn.Conv2d(out_channels, out_channels, kernel_size=3, padding=1), nn.BatchNorm2d(out_channels), nn.ReLU(inplace=True) ) def forward(self, x): x = self.conv(x) return x class UNet(nn.Module): # 定义一个UNet类,表示U-Net网络的整体结构 def __init__(self, in_channels=3, out_channels=1, features=[64, 128, 256, 512]): super(UNet, self).__init__() self.ups = nn.ModuleList() self.downs = nn.ModuleList() self.pool = nn.MaxPool2d(kernel_size=2, stride=2) # 定义下采样和上采样过程中的卷积层 for feature in features: self.downs.append(DoubleConv(in_channels, feature)) in_channels = feature self.ups.append(nn.ConvTranspose2d(feature*2, feature, kernel_size=2, stride=2)) self.ups.append(DoubleConv(feature*2, feature)) # 定义最后的卷积层 self.bottleneck = DoubleConv(features[-1], features[-1]*2) self.final_conv = nn.Conv2d(features[0], out_channels, kernel_size=1) def forward(self, x): skip_connections = [] for down in self.downs: x = down(x) skip_connections.append(x) x = self.pool(x) x = self.bottleneck(x) skip_connections = skip_connections[::-1] for idx in range(0, len(self.ups), 2): x = self.ups[idx](x) skip_connection = skip_connections[idx//2] if x.shape != skip_connection.shape: x = F.interpolate(x, size=skip_connection.shape[2:], mode='bilinear', align_corners=True) concat_skip = torch.cat((skip_connection, x), dim=1) x = self.ups[idx+1](concat_skip) return self.final_conv(x) ``` 该网络包含两个类,`DoubleConv` 和 `UNet`。`DoubleConv` 类表示 U-Net 网络中的基本结构,包含两个卷积层,一个 batchnorm 层和一个 ReLU 激活层。`UNet` 类表示 U-Net 网络的整体结构,包含下采样过程中的卷积层和上采样过程中的反卷积层,以及最后的卷积层。 在 `UNet` 类的 `__init__` 方法中,我们定义了下采样和上采样过程中的卷积层和反卷积层,以及最后的卷积层。其中 `features` 参数是一个列表,表示每一层的特征数,我们将使用该参数来定义网络结构。 在 `UNet` 类的 `forward` 方法中,我们首先定义了一个列表 `skip_connections`,用于存储下采样过程中的 feature maps,然后我们依次执行下采样和上采样过程,并将下采样过程中的 feature maps 存储到 `skip_connections` 中。在上采样过程中,我们将当前 feature map 和对应的下采样过程中的 feature map 进行拼接,然后执行一次卷积操作,最后使用一个 1x1 的卷积层生成最终的输出。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值