Skip to content

第三章 图像分割与 OCR


课程导航

项目内容
课时2 小时
类型理论 + 代码实战
前置知识CNN、PyTorch、第二章目标检测基础

一、学习目标

  1. 理解语义分割与实例分割的区别
  2. 掌握 FCN / U-Net 的全卷积结构与跳跃连接原理
  3. 理解 Mask R-CNN 的多任务联合训练机制
  4. 能使用 PaddleOCR 完成图像文本检测与识别
  5. 掌握文档结构化提取(版面分析 + 表格识别)

二、核心知识点

2.1 语义分割:FCN 与 U-Net

2.1.1 定义

图像分割是将图像划分为多个有意义的区域(像素级别分类):

类型说明代表模型
语义分割对每个像素分类,同类物体不加区分FCN、U-Net、DeepLab
实例分割对每个像素分类 + 区分不同实例Mask R-CNN、YOLACT
全景分割语义 + 实例分割的统一Panoptic FPN

FCN(Fully Convolutional Network)

  • 用卷积层替换全连接层,保留空间信息
  • 通过转置卷积(反卷积)上采样恢复分辨率
  • 跳跃连接(Skip Connection)融合浅层细节与深层语义

2.1.2 FCN 架构示意

输入图像

VGG16 卷积(去掉 FC)

Conv7 (4096) → Conv1x1 → 上采样 32x → FCN-32s

Conv4 (Pool4) 跳跃连接 → 上采样 16x → FCN-16s

Conv3 (Pool3) 跳跃连接 → 上采样 8x  → FCN-8s  (最佳)

2.1.3 U-Net 架构

U-Net 专为医学图像分割设计,对称的编码-解码结构 + 跳跃连接。

编码路径(收缩)         解码路径(扩展)
Input ─┐                    ┌── Output
 Conv3→ReLU→Pool2           Conv3→ReLU→UpConv2
   │                          ↑
 Conv3→ReLU→Pool2           Conv3→ReLU→UpConv2
   │                          ↑
 Conv3→ReLU→Pool2           Conv3→ReLU→UpConv2
   │                          ↑
 Conv3→ReLU→Pool2           Conv3→ReLU→UpConv2
   │                          ↑
         Conv3→ReLU→Conv3 (Bottleneck)

跳跃连接:将编码器每层的特征图直接拼接到对应的解码器层,保留空间细节。

2.1.4 代码示例(U-Net 核心模块)

python
import torch
import torch.nn as nn
import torch.nn.functional as F

class DoubleConv(nn.Module):
    """双卷积 + BN + ReLU"""
    def __init__(self, in_ch, out_ch):
        super().__init__()
        self.conv = nn.Sequential(
            nn.Conv2d(in_ch, out_ch, 3, padding=1),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True),
            nn.Conv2d(out_ch, out_ch, 3, padding=1),
            nn.BatchNorm2d(out_ch),
            nn.ReLU(inplace=True),
        )

    def forward(self, x):
        return self.conv(x)

class Down(nn.Module):
    """下采样:最大池化 + 双卷积"""
    def __init__(self, in_ch, out_ch):
        super().__init__()
        self.mpconv = nn.Sequential(
            nn.MaxPool2d(2),
            DoubleConv(in_ch, out_ch),
        )
    def forward(self, x):
        return self.mpconv(x)

class Up(nn.Module):
    """上采样:转置卷积 + 跳跃连接拼接 + 双卷积"""
    def __init__(self, in_ch, out_ch):
        super().__init__()
        self.up = nn.ConvTranspose2d(in_ch, in_ch//2, 2, stride=2)
        self.conv = DoubleConv(in_ch, out_ch)

    def forward(self, x1, x2):
        x1 = self.up(x1)
        # 处理尺寸对不齐(padding)
        diffY = x2.size()[2] - x1.size()[2]
        diffX = x2.size()[3] - x1.size()[3]
        x1 = F.pad(x1, [diffX//2, diffX - diffX//2,
                        diffY//2, diffY - diffY//2])
        x = torch.cat([x2, x1], dim=1)   # 跳跃连接
        return self.conv(x)

class UNet(nn.Module):
    def __init__(self, n_channels=3, n_classes=2):
        super().__init__()
        self.inc = DoubleConv(n_channels, 64)
        self.down1 = Down(64, 128)
        self.down2 = Down(128, 256)
        self.down3 = Down(256, 512)
        self.down4 = Down(512, 512)
        self.up1 = Up(1024, 256)
        self.up2 = Up(512, 128)
        self.up3 = Up(256, 64)
        self.up4 = Up(128, 64)
        self.outc = nn.Conv2d(64, n_classes, 1)

    def forward(self, x):
        x1 = self.inc(x)
        x2 = self.down1(x1)
        x3 = self.down2(x2)
        x4 = self.down3(x3)
        x5 = self.down4(x4)
        x = self.up1(x5, x4)
        x = self.up2(x, x3)
        x = self.up3(x, x2)
        x = self.up4(x, x1)
        logits = self.outc(x)
        return logits

# 训练循环示意
model = UNet(n_channels=3, n_classes=2)
criterion = nn.CrossEntropyLoss()  # 像素级交叉熵
optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)

for images, masks in dataloader:
    outputs = model(images)                      # (B, C, H, W)
    loss = criterion(outputs, masks)             # masks: (B, H, W)
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()

2.2 实例分割:Mask R-CNN

2.2.1 定义

Mask R-CNN 在 Faster R-CNN 基础上增加分割分支,实现检测 + 分割多任务联合训练。

输入图像 → Backbone → FPN → RPN
                               ├── ROI Align → 分类 + 回归(检测头)
                               └── ROI Align → 分割掩码(Mask 头)

关键创新

创新说明
ROI Align用双线性插值代替 ROI Pooling 的取整,保留亚像素精度
Mask 分支每个 ROI 预测 K 个二值掩码(每个类别一个),避免类别间竞争
多任务 LossL = L_cls + L_box + L_mask(逐像素 Sigmoid + Binary CE)

2.2.2 代码示例(使用 Detectron2)

python
# ---------- 安装 ----------
# pip install detectron2 -f https://dl.fbaipublicfiles.com/detectron2/wheels/cu118/torch2.0/index.html

from detectron2 import model_zoo
from detectron2.engine import DefaultPredictor
from detectron2.config import get_cfg
from detectron2.utils.visualizer import Visualizer
import cv2

# ---------- 配置 ----------
cfg = get_cfg()
cfg.merge_from_file(model_zoo.get_config_file(
    "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml"))
cfg.MODEL.ROI_HEADS.SCORE_THRESH_TEST = 0.5
cfg.MODEL.WEIGHTS = model_zoo.get_checkpoint_url(
    "COCO-InstanceSegmentation/mask_rcnn_R_50_FPN_3x.yaml")
cfg.MODEL.DEVICE = "cuda"

# ---------- 推理 ----------
predictor = DefaultPredictor(cfg)
img = cv2.imread("test.jpg")
outputs = predictor(img)

# ---------- 可视化 ----------
v = Visualizer(img[:, :, ::-1], scale=1.2)
out = v.draw_instance_predictions(outputs["instances"].to("cpu"))
cv2.imwrite("output/mask_rcnn_result.jpg", out.get_image()[:, :, ::-1])

# ---------- 提取掩码 ----------
instances = outputs["instances"].to("cpu")
masks = instances.pred_masks.numpy()   # (N, H, W) 二值掩码
boxes = instances.pred_boxes.tensor.numpy()
classes = instances.pred_classes.numpy()
print(f"检测到 {len(masks)} 个实例")

2.3 PaddleOCR 使用

2.3.1 定义

PaddleOCR 是百度开源的 OCR 工具包,集成文本检测 + 识别 + 表格识别 + 文档分析。

OCR 基础流程

输入图像 → 文本检测(DB / EAST)→ 文本识别(CRNN / SVTR)→ 结构化输出
模块模型说明
文本检测DBNet可微分二值化检测文本区域
文本识别SVTR / CRNN端到端文字识别
方向分类器MobileNetV3判断文字方向(0°/90°/180°/270°)

2.3.2 代码示例

python
# ---------- 安装 ----------
# pip install paddlepaddle-gpu  # 或 paddlepaddle(CPU)
# pip install paddleocr

from paddleocr import PaddleOCR, draw_ocr
from PIL import Image

# ---------- 初始化(自动下载模型)----------
ocr = PaddleOCR(
    use_angle_cls=True,     # 启用方向分类
    lang='ch',              # 中文模型
    use_gpu=True,
    det_db_thresh=0.3,      # 检测阈值
    rec_batch_num=6,        # 识别批大小
)

# ---------- 检测 + 识别 ----------
img_path = 'invoice.jpg'
result = ocr.ocr(img_path, cls=True)

# result 格式:[[[x1,y1],[x2,y2],[x3,y3],[x4,y4]], (text, confidence)]
for line in result[0]:
    box = line[0]           # 四边形四点坐标
    text, score = line[1]   # 识别文本与置信度
    print(f"{text:20s}  | 置信度: {score:.4f}")

# ---------- 可视化 ----------
image = Image.open(img_path).convert('RGB')
boxes = [line[0] for line in result[0]]
txts = [line[1][0] for line in result[0]]
scores = [line[1][1] for line in result[0]]

im_show = draw_ocr(image, boxes, txts, scores, font_path='simfang.ttf')
im_show = Image.fromarray(im_show)
im_show.save('output/ocr_result.jpg')

# ---------- 直接返回结构化文本 ----------
full_text = '\n'.join([line[1][0] for line in result[0]])
print(full_text)

2.3.3 参数调优

python
# 高精度模式
ocr = PaddleOCR(
    det_model_dir=None,         # 可指定本地模型路径
    rec_model_dir=None,
    cls_model_dir=None,
    use_angle_cls=True,
    lang='ch',
    det_db_thresh=0.3,           # 降低阈值检测更多文本
    det_db_box_thresh=0.5,       # 检测框阈值
    det_db_unclip_ratio=1.6,     # 文本框扩展比例
    max_batch_size=10,
    use_space_char=True,
    rec_char_dict_path=None      # 可自定义字典
)

2.4 文档结构化提取

2.4.1 定义

文档结构化提取从扫描文档/PDF 中提取结构化信息(标题、段落、表格、图片),是 RAG 和文档数字化的重要步骤。

流程

扫描文档 → 版面分析 → 文字检测+识别
                       ├── 段落结构
                       ├── 表格识别 → HTML/Excel
                       └── 标题层级

2.4.2 版面分析(PaddleOCR PP-Structure)

python
# ---------- PP-Structure 版面分析 ----------
from paddleocr import PPStructure,draw_structure_result,save_structure_res

table_engine = PPStructure(
    show_log=True,
    lang='ch',            # 中文版面
    layout_model_dir=None, # 可指定版面分析模型
    table_model_dir=None,  # 可指定表格识别模型
)

result = table_engine('document.jpg')

# result 结构
for item in result:
    type = item['type']           # text / table / figure / title
    bbox = item['bbox']           # [x1,y1,x2,y2]
    res = item['res']
    if type == 'table':
        html = res['html']        # 表格 HTML 代码
        print(f"[表格] {html[:200]}...")
    elif type == 'text':
        text = res['text'][0][0]  # 识别文本
        print(f"[文本] {text}")

# ---------- 保存结构化结果 ----------
save_structure_res(result, 'output/')

2.4.3 表格识别与导出

python
import pandas as pd
from bs4 import BeautifulSoup

def table_html_to_dataframe(html_str):
    """将表格 HTML 转换为 DataFrame"""
    soup = BeautifulSoup(html_str, 'html.parser')
    rows = soup.find_all('tr')
    data = []
    for row in rows:
        cells = row.find_all(['td', 'th'])
        data.append([cell.get_text(strip=True) for cell in cells])
    return pd.DataFrame(data)

# 示例
html = result[0]['res']['html']
df = table_html_to_dataframe(html)
df.to_excel('output/table.xlsx', index=False)
print(df.head())

2.4.4 完整的文档提取管线

python
from paddleocr import PaddleOCR, PPStructure
import json

class DocumentExtractor:
    def __init__(self, lang='ch'):
        self.ocr = PaddleOCR(use_angle_cls=True, lang=lang)
        self.structure = PPStructure(lang=lang)

    def extract(self, img_path):
        # 1. 版面分析
        layout = self.structure(img_path)

        # 2. 逐块处理
        result = {
            'title': '',
            'paragraphs': [],
            'tables': [],
            'figures': [],
        }

        for block in layout:
            bbox = block['bbox']
            if block['type'] == 'title':
                # 用高分辨率 OCR 识别标题
                text = self._ocr_crop(img_path, bbox)
                result['title'] = text
            elif block['type'] == 'text':
                text = self._ocr_crop(img_path, bbox)
                result['paragraphs'].append(text)
            elif block['type'] == 'table':
                result['tables'].append(block['res']['html'])
            elif block['type'] == 'figure':
                result['figures'].append(bbox)

        return result

    def _ocr_crop(self, img_path, bbox):
        import cv2
        img = cv2.imread(img_path)
        x1, y1, x2, y2 = map(int, bbox)
        crop = img[y1:y2, x1:x2]
        cv2.imwrite('_temp_crop.jpg', crop)
        res = self.ocr.ocr('_temp_crop.jpg')
        if res[0]:
            return ' '.join([line[1][0] for line in res[0]])
        return ''

# 使用
extractor = DocumentExtractor()
doc = extractor.extract('report.pdf')
print(json.dumps(doc, ensure_ascii=False, indent=2))

三、小结

知识点掌握程度核心函数/模型
FCN / U-Net理解原理全卷积 + 跳跃连接;医学分割首选
Mask R-CNN理解流程ROI Align + 多任务 Loss
PaddleOCR必须掌握PaddleOCR.ocr() 一行完成检测+识别
版面分析理解应用PPStructure 输出带类型的结构化块
表格识别理解应用HTML 转 DataFrame → Excel

四、课后练习

基础题

  1. 用 PaddleOCR 对一张包含中英文的路牌照片进行 OCR,输出识别结果并可视化。
  2. 使用 torchvision.models.segmentation.fcn_resnet50 对图像进行语义分割,过滤出"人"这一类别并生成掩码覆盖图。

进阶题

  1. 收集 10 张表格图片,使用 PP-Structure 提取表格内容,导出为 Excel 文件并对比准确率。
  2. 使用 U-Net 训练一个自定义的二分类分割模型(如道路分割、皮肤病变分割),使用 Dice Loss 作为损失函数。
  3. 实现一个文档结构化提取管线:输入一张扫描合同图片,提取(甲方、乙方、金额、日期)等关键字段并输出 JSON。

思考题

  1. 语义分割中的"跳跃连接"解决了什么问题?去掉跳跃连接后会怎样?
  2. Mask R-CNN 的 ROI Align 与 Faster R-CNN 的 ROI Pooling 有什么区别?为什么对分割任务至关重要?
  3. 在实际文档 OCR 中,文本检测(Detection)和文本识别(Recognition)哪个环节更容易出错?如何改进?

Python 学习资料