u net网络,-使用U-Net网络结构实现分割、分类、目标检测任务 - boundingRect(cnt)
U-Net实现分割、分类、目标检测任务的区别点主要在于解码器与输出头的不同结构,优先以分割任务为例,解释实现分割任务代码,以此对比其余任务的不同处。
分割任务的实现:
一.先加载必要库
import os
import numpy as np
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.optim as optim
from torch.utils.data import DataLoader
from torchvision import transforms, datasets
from tqdm import tqdm
import multiprocessing
# 配置matplotlib中文字体,防止中文乱码
plt.rcParams['font.sans-serif'] = ['SimHei', 'Microsoft YaHei'] # 设置字体
plt.rcParams['axes.unicode_minus'] = False # 正确显示负号
# 设置随机种子,保证结果可复现(每次运行结果一致)
torch.manual_seed(42) # PyTorch随机种子
np.random.seed(42) # Numpy随机种子
二.进行数据准备
# 图像预处理:缩放到128x128并转为张量
image_transform = transforms.Compose([
transforms.Resize((128, 128)), # 缩放图片到128x128
transforms.ToTensor() # 转为张量,像素值归一化到0~1
])
# 标签预处理:缩放、转为张量,并将标签值从1/2/3修正为0/1/2
mask_transform = transforms.Compose([
transforms.Resize((128, 128)), # 缩放标签到128x128
transforms.ToTensor(), # 转为张量(像素值变为0~1小数)
transforms.Lambda(lambda x: (x * 255 - 1).long().squeeze()) # 还原标签并减1,得到0/1/2
])
# 加载Oxford-IIIT Pet分割数据集(训练集和测试集)
train_dataset = datasets.OxfordIIITPet(
root='./data', # 数据存放路径
split='trainval', # 训练集划分
target_types='segmentation', # 只要分割标签
download=True, # 自动下载数据
transform=image_transform, # 图像预处理
target_transform=mask_transform # 标签预处理
)
test_dataset = datasets.OxfordIIITPet(
root='./data', # 数据存放路径
split='test', # 测试集划分
target_types='segmentation', # 只要分割标签
download=True, # 自动下载数据
transform=image_transform, # 图像预处理
target_transform=mask_transform # 标签预处理
)
# 类别数和类别名称(0:背景,1:宠物,2:边界)
num_classes = 3
class_names = ['背景', '宠物', '边界']
# 数据加载器:每批16张图片,训练集打乱,测试集不打乱
batch_size = 16
train_loader = DataLoader(
train_dataset, # 训练数据集
batch_size=batch_size, # 批量大小
shuffle=True, # 打乱数据
num_workers=0 # 单进程加载(Windows推荐)
)
test_loader = DataLoader(
test_dataset, # 测试数据集
batch_size=batch_size, # 批量大小
shuffle=False, # 不打乱
num_workers=0 # 单进程加载
)
数据集采用Oxford-IIIT Pet分割数据集,以下是原始数据与标注图片
三.U-Net模型定义
class UNet(nn.Module):
def __init__(self, num_classes=3):
super(UNet, self).__init__()
# 编码器
self.enc1 = nn.Sequential(
nn.Conv2d(3, 64, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 3, padding=1),
nn.ReLU(inplace=True)
)
self.pool1 = nn.MaxPool2d(2, 2)
self.enc2 = nn.Sequential(
nn.Conv2d(64, 128, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, 3, padding=1),
nn.ReLU(inplace=True)
)
self.pool2 = nn.MaxPool2d(2, 2)
self.enc3 = nn.Sequential(
nn.Conv2d(128, 256, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, 3, padding=1),
nn.ReLU(inplace=True)
)
self.pool3 = nn.MaxPool2d(2, 2)
self.enc4 = nn.Sequential(
nn.Conv2d(256, 512, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, padding=1),
nn.ReLU(inplace=True)
)
self.pool4 = nn.MaxPool2d(2, 2)
# 瓶颈层
self.bottleneck = nn.Sequential(
nn.Conv2d(512, 1024, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(1024, 1024, 3, padding=1),
nn.ReLU(inplace=True)
)
# 解码器
self.upconv4 = nn.ConvTranspose2d(1024, 512, 2, 2)
self.dec4 = nn.Sequential(
nn.Conv2d(1024, 512, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, 3, padding=1),
nn.ReLU(inplace=True)
)
self.upconv3 = nn.ConvTranspose2d(512, 256, 2, 2)
self.dec3 = nn.Sequential(
nn.Conv2d(512, 256, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, 3, padding=1),
nn.ReLU(inplace=True)
)
self.upconv2 = nn.ConvTranspose2d(256, 128, 2, 2)
self.dec2 = nn.Sequential(
nn.Conv2d(256, 128, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, 3, padding=1),
nn.ReLU(inplace=True)
)
self.upconv1 = nn.ConvTranspose2d(128, 64, 2, 2)
self.dec1 = nn.Sequential(
nn.Conv2d(128, 64, 3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, 3, padding=1),
nn.ReLU(inplace=True)
)
# 输出层
self.out_conv = nn.Conv2d(64, num_classes, 1)
def forward(self, x):
enc1 = self.enc1(x)
enc2 = self.enc2(self.pool1(enc1))
enc3 = self.enc3(self.pool2(enc2))
enc4 = self.enc4(self.pool3(enc3))
bottleneck = self.bottleneck(self.pool4(enc4))
dec4 = self.upconv4(bottleneck)
dec4 = torch.cat([dec4, enc4], dim=1)
dec4 = self.dec4(dec4)
dec3 = self.upconv3(dec4)
dec3 = torch.cat([dec3, enc3], dim=1)
dec3 = self.dec3(dec3)
dec2 = self.upconv2(dec3)
dec2 = torch.cat([dec2, enc2], dim=1)
dec2 = self.dec2(dec2) 拼多多帮助力入口
dec1 = self.upconv1(dec2)
dec1 = torch.cat([dec1, enc1], dim=1)
dec1 = self.dec1(dec1)
out = self.out_conv(dec1)
return out
分割任务与其余任务的区别,在解码器上差别较小,均采样卷积+下采样提取图像特征。而在解码器方面,分割任务采用与解码器对应的4层上采样,通过跳跃连接直接拼接编码器同尺度特征,达到全尺度特征融合,精准恢复每个像素的类别信息。在输出头方面为1×1卷积层,将解码器最终输出映射到num_class通道(类别数),每个像素对应num_class个类别概率,直接实现像素级分类。
四.训练与可视化函数
save_dir = "./segmentation_weights"
os.makedirs(save_dir, exist_ok=True)
best_weight_path = os.path.join(save_dir, "best_unet_segmentation.pt")
best_loss = float('inf')
# 设备选择(优先用GPU,否则用CPU)
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu') # 设备
print(f'使用设备:{device}') # 打印设备信息
# 初始化模型、损失函数和优化器
model = UNet(num_classes=num_classes).to(device) # 实例化U-Net模型并放到设备上
criterion = nn.CrossEntropyLoss() # 交叉熵损失(多分类)
optimizer = optim.Adam(model.parameters(), lr=0.001) # Adam优化器
# 权重保存路径设置
save_dir = "./segmentation_weights" # 权重保存文件夹
os.makedirs(save_dir, exist_ok=True) # 如果不存在则创建
best_weight_path = os.path.join(save_dir, "best_unet_segmentation.pt") # 最优权重文件路径
best_loss = float('inf') # 初始化最优损失为无穷大
def train_model(num_epochs=10):
global best_loss
train_losses = []
# 训练主循环
for epoch in range(num_epochs):
model.train() # 设置为训练模式
running_loss = 0.0 # 累计损失
train_pbar = tqdm(train_loader, desc=f'训练轮次 {epoch+1}/{num_epochs}') # 进度条
for images, masks in train_pbar:
images = images.to(device) # 图像放到设备
masks = masks.to(device) # 标签放到设备
outputs = model(images) # 前向传播,得到输出
loss = criterion(outputs, masks) # 计算损失
optimizer.zero_grad() # 梯度清零
loss.backward() # 反向传播
optimizer.step() # 更新参数
running_loss += loss.item() # 累加损失
train_pbar.set_postfix({'当前损失': f'{loss.item():.4f}'}) # 显示当前损失
epoch_loss = running_loss / len(train_loader) # 计算平均损失
train_losses.append(epoch_loss) # 记录损失
print(f'轮次 {epoch+1}/{num_epochs} - 平均损失: {epoch_loss:.4f}') # 打印本轮损失
# 保存最优模型
if epoch_loss < best_loss:
best_loss = epoch_loss
torch.save(model.state_dict(), best_weight_path) # 保存权重
print(f'✅ 保存最优模型到 {best_weight_path}')
# 绘制损失曲线
plt.figure(figsize=(8, 4))
plt.plot(range(1, num_epochs+1), train_losses, 'b-') # 损失曲线
plt.xlabel('训练轮次')
plt.ylabel('损失值')
plt.title('训练损失曲线')
plt.grid(True)
plt.show()
return model # 返回训练好的模型
def visualize_segmentation(model, num_samples=4):
model.eval() # 设置为评估模式
images, masks = next(iter(test_loader)) # 取一批测试数据
images = images[:num_samples].to(device) # 只取前num_samples张图片
masks = masks[:num_samples].numpy() # 真实标签
with torch.no_grad():
outputs = model(images) # 得到模型预测
preds = torch.argmax(outputs, dim=1).cpu().numpy() # 取最大概率类别
plt.figure(figsize=(15, 10)) # 创建画布
cmap = plt.cm.colors.ListedColormap(['black', 'red', 'yellow']) # 定义颜色
for i in range(num_samples):
plt.subplot(num_samples, 3, i*3 + 1) # 原图
plt.imshow(images[i].cpu().permute(1, 2, 0))
plt.title('原图')
plt.axis('off')
plt.subplot(num_samples, 3, i*3 + 2) # 真实标签
plt.imshow(masks[i], cmap=cmap, vmin=0, vmax=2)
plt.title('真实标注')
plt.axis('off')
plt.subplot(num_samples, 3, i*3 + 3) # 预测结果
plt.imshow(preds[i], cmap=cmap, vmin=0, vmax=2)
plt.title('预测结果')
plt.axis('off')
plt.tight_layout() # 自动调整子图间距
plt.show() # 显示图片
进行环境配置,并且初始化U-Net分割模型、损失函数和优化器
绘制训练损失函数,展现模型训练效果
对比展示了测试图像原图、真实分割标签与模型预测结果
损失函数:
模型预测结果:
四.主程序运行
if __name__ == '__main__':
multiprocessing.freeze_support() # 支持Windows系统多进程
# 训练模型(10轮,可根据需要调整)
trained_model = train_model(num_epochs=10) # 训练U-Net模型
# 加载最优模型权重
trained_model.load_state_dict(torch.load(best_weight_path, map_location=device,weights_only=True)) # 加载权重
# 可视化分割结果
visualize_segmentation(trained_model) # 显示分割效果
以上代码可直接使用复现,下面对其余两种任务的不同处进行对比
目标检测任务
编码器采用与分割任务高度相似的纯卷积+4层下采样,用于提取目标空间位置特征
# 编码器(下采样:提取高层特征,尺寸减半,通道数翻倍)
# --------------------------
# 第1层编码器:3→64通道
self.enc1 = nn.Sequential(
nn.Conv2d(in_channels, 64, kernel_size=3, padding=1), # 卷积:保持尺寸
nn.ReLU(inplace=True), # 激活函数(加速计算)
nn.Conv2d(64, 64, kernel_size=3, padding=1), # 再次卷积
nn.ReLU(inplace=True)
)
self.pool1 = nn.MaxPool2d(kernel_size=2, stride=2) # 下采样:256→128
# 第2层编码器:64→128通道
self.enc2 = nn.Sequential(
nn.Conv2d(64, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
self.pool2 = nn.MaxPool2d(2, 2) # 下采样:128→64
# 第3层编码器:128→256通道
self.enc3 = nn.Sequential(
nn.Conv2d(128, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
self.pool3 = nn.MaxPool2d(2, 2) # 下采样:64→32
# 第4层编码器:256→512通道
self.enc4 = nn.Sequential(
nn.Conv2d(256, 512, kernel_size=3, padding=1),
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
self.pool4 = nn.MaxPool2d(2, 2) # 下采样:32→16
解码器结构同样与分割任务对称(4层上采样)恢复目标的空间位置细节,通过全尺度融合确保掩码能精准包围目标
# 解码器(上采样:恢复尺寸,融合编码器特征)
# --------------------------
# 第1层解码器:1024→512通道(对应编码器第4层)
self.upconv4 = nn.ConvTranspose2d(1024, 512, kernel_size=2, stride=2) # 上采样:16→32
self.dec4 = nn.Sequential(
nn.Conv2d(512 + 512, 512, kernel_size=3, padding=1), # 融合编码器特征(512+512)
nn.ReLU(inplace=True),
nn.Conv2d(512, 512, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
# 第2层解码器:512→256通道(对应编码器第3层)
self.upconv3 = nn.ConvTranspose2d(512, 256, kernel_size=2, stride=2) # 上采样:32→64
self.dec3 = nn.Sequential(
nn.Conv2d(256 + 256, 256, kernel_size=3, padding=1), # 融合编码器特征(256+256)
nn.ReLU(inplace=True),
nn.Conv2d(256, 256, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
# 第3层解码器:256→128通道(对应编码器第2层)
self.upconv2 = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2) # 上采样:64→128
self.dec2 = nn.Sequential(
nn.Conv2d(128 + 128, 128, kernel_size=3, padding=1), # 融合编码器特征(128+128)
nn.ReLU(inplace=True),
nn.Conv2d(128, 128, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
# 第4层解码器:128→64通道(对应编码器第1层)
self.upconv1 = nn.ConvTranspose2d(128, 64, kernel_size=2, stride=2) # 上采样:128→256
self.dec1 = nn.Sequential(
nn.Conv2d(64 + 64, 64, kernel_size=3, padding=1), # 融合编码器特征(64+64)
nn.ReLU(inplace=True),
nn.Conv2d(64, 64, kernel_size=3, padding=1),
nn.ReLU(inplace=True)
)
输出头为1×1卷积+sigmoid将解码器最终输出(64 通道,256×256)映射到 1 通道,Sigmoid 将输出压缩至 [0,1] 范围,每个像素表示 “是否为目标” 的概率(二值掩码),需后续处理后(如阈值分割、轮廓提取)将掩码转换为检测框,实现目标位置定位。
U-Net实现目标检测任务主要在于通过后续的处理将模型输出的概率掩码转换为目标检测框
def mask_to_boxes(mask_pred, threshold=0.5, img_size=(256, 256)):
# 1. 阈值化:将概率掩码转为二值掩码(0=背景,1=目标)
# 先将tensor转为numpy数组,再应用阈值
mask_bin = (mask_pred.squeeze().cpu().detach().numpy() > threshold).astype(np.uint8)
# 过滤微小噪声(目标像素少于10个则视为无目标)
if np.sum(mask_bin) < 10:
return np.zeros((0, 4), dtype=np.int32) # 返回空检测框
# 2. 轮廓提取:找到目标的边界轮廓(使用OpenCV)
# RETR_EXTERNAL:只提取最外层轮廓;CHAIN_APPROX_SIMPLE:简化轮廓
contours, _ = cv2.findContours(mask_bin, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
boxes = [] # 存储检测框
# 遍历每个轮廓,计算最小外接矩形(检测框)
for cnt in contours:
# 过滤小轮廓(面积<50像素,避免噪声)
if cv2.contourArea(cnt) < 50:
continue
# 计算轮廓的最小外接矩形(x,y为左上角坐标,w,h为宽高)
x, y, w, h = cv2.boundingRect(cnt)
x1, y1, x2, y2 = x, y, x + w, y + h # 转换为[x1,y1,x2,y2]格式
# 修正检测框,避免超出图像范围
x1 = max(0, min(x1, img_size[1] - 1)) # x1限制在[0, 宽-1]
y1 = max(0, min(y1, img_size[0] - 1)) # y1限制在[0, 高-1]
x2 = max(x1 + 1, min(x2, img_size[1] - 1)) # x2必须>x1
y2 = max(y1 + 1, min(y2, img_size[0] - 1)) # y2必须>y1
boxes.append([x1, y1, x2, y2]) # 添加到检测框列表
# 转换为numpy数组(无目标则返回空数组)
return np.array(boxes, dtype=np.int32) if boxes else np.zeros((0, 4), dtype=np.int32)
def calculate_iou(box1, box2):
"""
计算两个检测框的交并比(IOU),评估检测框重合度
输入:
- box1, box2: 检测框(格式:[x1,y1,x2,y2],像素坐标)
输出:
- iou: IOU值(0~1,值越大表示重合度越高)
"""
# 计算交集区域的坐标
inter_x1 = max(box1[0], box2[0]) # 交集左上角x
inter_y1 = max(box1[1], box2[1]) # 交集左上角y
inter_x2 = min(box1[2], box2[2]) # 交集右下角x
inter_y2 = min(box1[3], box2[3]) # 交集右下角y
# 计算交集面积(若无交集则为0)
inter_area = max(0, inter_x2 - inter_x1) * max(0, inter_y2 - inter_y1)
# 计算两个检测框的面积
box1_area = (box1[2] - box1[0]) * (box1[3] - box1[1]) # 框1面积
box2_area = (box2[2] - box2[0]) * (box2[3] - box2[1]) # 框2面积
# 计算IOU(交并比 = 交集面积 / (框1面积 + 框2面积 - 交集面积))
# 加1e-6避免分母为0
iou = inter_area / (box1_area + box2_area - inter_area + 1e-6)
return iou
def mixed_loss(mask_pred, mask_gt, gt_boxes_list, img_size=(256, 256)):
# 1. 分割损失:二分类交叉熵(评估掩码预测精度)
bce_criterion = nn.BCELoss() # 二分类交叉熵损失函数
seg_loss = bce_criterion(mask_pred, mask_gt) # 计算分割损失
# 2. 检测框损失:IOU损失(评估检测框重合度)
iou_loss = torch.tensor(0.0, device=mask_pred.device) # 初始化IOU损失
valid_count = 0 # 统计有目标的样本数量(用于平均损失)
# 遍历批量中的每个样本
for i in range(len(gt_boxes_list)):
gt_boxes = gt_boxes_list[i] # 当前样本的真实检测框
if gt_boxes.shape[0] == 0:
continue # 无目标的样本跳过
# 从预测掩码生成检测框
pred_boxes = mask_to_boxes(mask_pred[i], img_size=img_size)
if pred_boxes.shape[0] == 0:
# 无预测框时,IOU损失为1(因为IOU=0)
iou_loss += 1.0
valid_count += 1
continue
# 计算最佳匹配的IOU(一个真实框对应一个预测框)
max_iou = 0.0 # 记录最大IOU
for gt in gt_boxes:
# 将真实框从归一化坐标转为像素坐标
gt_pixel = (gt * np.array([img_size[1], img_size[0], img_size[1], img_size[0]])).astype(np.int32)
# 遍历所有预测框,找与当前真实框重合度最高的
for pred in pred_boxes:
iou = calculate_iou(pred, gt_pixel) # 计算IOU
max_iou = max(max_iou, iou) # 更新最大IOU
# IOU损失 = 1 - 最大IOU(值越小表示预测越好)
iou_loss += (1 - max_iou)
valid_count += 1 # 计数+1
# 计算平均IOU损失(避免无目标样本影响)
if valid_count > 0:
iou_loss = iou_loss / valid_count # 平均到每个有目标的样本
else:
iou_loss = torch.tensor(0.0, device=mask_pred.device) # 全是无目标样本时损失为0
# 总损失:分割损失和IOU损失各占50%权重
total_loss = 0.5 * seg_loss + 0.5 * iou_loss
return total_loss, seg_loss, iou_loss
先按阈值(如 0.5)把概率掩码转成二值掩码(概率超阈值的像素算目标,否则是背景);用轮廓提取算法(OpenCV)找到目标区域的轮廓,过滤掉面积过小的噪声轮廓;对每个有效轮廓,计算能框住它的最小矩形,再修正矩形位置避免超出图像范围,最终得到 [x1,y1,x2,y2] 格式的检测框。
分类任务
分类任务的编码器也可与其余任务采用同样结构,但分类任务的解码器仅一层上采样从而到达融合中层与高层特征(而非全尺度)的目的,保留足够的类别判别信息即可,无需恢复到原始尺寸(分类不依赖像素级位置)。
这里编码器采用基于预训练 ResNet18(迁移学习),复用其卷积层(conv1、bn1、layer1→layer3),下采样通过 ResNet 的 maxpool 和残差块的步长实现(32→16→8→4→2)(如下图)
self.conv1 = self.resnet.conv1 # 第1卷积层:3→64通道,输出16x16特征图
self.bn1 = self.resnet.bn1 # 批归一化层:稳定数据分布,加速训练
self.relu = self.resnet.relu # ReLU激活:引入非线性,增强模型表达能力
self.maxpool = self.resnet.maxpool # 最大池化:16x16→8x8(下采样,保留关键特征)
self.layer1 = self.resnet.layer1 # 残差块1:64→64通道,8x8(浅层特征)
self.layer2 = self.resnet.layer2 # 残差块2:64→128通道,4x4(中层特征,用于跳跃连接)
self.layer3 = self.resnet.layer3 # 残差块3:128→256通道,2x2(高层抽象特征)
解码器(如下图)
self.decoder_up = nn.ConvTranspose2d(256, 128, kernel_size=2, stride=2)
# 4.2 卷积块:融合跳跃连接的特征(layer2的128通道+上采样的128通道=256通道→128通道)
self.decoder_conv = nn.Sequential(
nn.Conv2d(256, 128, kernel_size=3, padding=1), # 3x3卷积:保持尺寸,提取局部特征
nn.ReLU(inplace=True) # ReLU激活:增强非线性,覆盖更多特征模式
)
分类器,分类任务的核心模块,实现以下内容以实现分类任务
自适应池化:不管输入特征图尺寸多大,统一压缩成 1×1 大小的特征图(保留通道信息,如 128 通道);展平:把 1×1 的特征图转成 1 维向量(如 128 维),适配全连接层输入格式;全连接与激活:通过两层全连接层(128→64、64→10)压缩特征维度,中间用 ReLU 激活引入非线性,提升分类能力;防过拟合:用 Dropout 随机 “关闭” 50% 神经元,避免模型过度依赖部分特征;输出分类结果:最后一层输出 10 维向量,对应 10 个类别的预测分数(后续可转概率)。
self.classifier = nn.Sequential(
nn.AdaptiveAvgPool2d((1, 1)),
nn.Flatten(),
nn.Linear(128, 64),
nn.ReLU(inplace=True),
nn.Dropout(0.5),
nn.Linear(64, num_classes)