Skip to content

计算机视觉 AI ​

人看到照片时,会自然地辨认物体、位置和场景;计算机最初接触到的则是像素数组。例如 RGB 图像可以表示为高度、宽度和三个颜色通道的数值。计算机视觉研究如何从这些数据提取特征,并完成分类、定位、分割、生成或图像相关问答。

手机身份验证、道路环境分析、工业质检和医学影像都能使用视觉技术,但不同领域对数据、评估与可靠性的要求相差很大。本章沿着卷积网络、Vision Transformer、目标检测、图像分割、扩散、CLIP 和 VLM 展开,说明这些技术各自输入什么、输出什么、如何连接。

代码采用 Python 3.10 以上的写法。数值例子使用手工图形或随机张量,展示张量形状和计算流程;需要预训练权重的函数会单独说明依赖,并优先要求已准备好的本地文件。随机模型没有识别能力,模拟框也不代表检测到了真实物体。文中不提供未经执行的准确率或训练成果。

卷积神经网络 CNN ​

CNN 通过局部连接与参数共享处理图像。一个小卷积核在多个空间位置重复使用,使网络能以较少参数寻找局部模式;堆叠层之后,特征可以组合为更复杂的结构。这受到局部感受野思想启发,但不能简单等同于复刻人类视觉系统。

滑动窗口如何计算 ​

对单通道图像,一个 3×3 核读取九个邻近像素,逐项相乘后求和形成一个输出。移动窗口就得到整张特征图。深度学习库通常实现不翻转卷积核的互相关,也习惯称为卷积。

不填充、步长为一时,输出尺寸为 H−kH+1 与 W−kW+1。使用 padding 与 stride 后要相应改变。下面用人工 Sobel 核观察白色方块的垂直边缘;CNN 训练时的核通常由数据学习,不能把所有核都说成人工设计或全部都说成必然训练得到。

实例 ​

python
import numpy as np

def correlate_gray(pixels, weights, stride=1, padding=0):
    pixels = np.asarray(pixels, dtype=np.float64)
    weights = np.asarray(weights, dtype=np.float64)
    if pixels.ndim != 2 or weights.ndim != 2:
        raise ValueError("此演示只接收二维灰度矩阵")
    if stride < 1 or padding < 0:
        raise ValueError("步长应为正,填充不能为负")
    padded = np.pad(pixels, padding, mode="constant")
    kh, kw = weights.shape
    rows = (padded.shape[0] - kh) // stride + 1
    columns = (padded.shape[1] - kw) // stride + 1
    if rows <= 0 or columns <= 0:
        raise ValueError("卷积核大于填充后的输入")
    result = np.empty((rows, columns), dtype=np.float64)
    for row in range(rows):
        for column in range(columns):
            top, left = row * stride, column * stride
            window = padded[top:top + kh, left:left + kw]
            result[row, column] = np.sum(window * weights)
    return result

if __name__ == "__main__":
    square = np.zeros((8, 8), dtype=float)
    square[2:6, 2:6] = 1.0
    vertical_edges = np.array([[-1, 0, 1], [-2, 0, 2], [-1, 0, 1]], dtype=float)
    response = correlate_gray(square, vertical_edges)
    print("人工输入图形:\n", square)
    print("边缘响应:\n", np.round(response, 3))
    print("输出形状:", response.shape)

池化怎样减少空间尺寸 ​

最大池化在窗口内保留最大值,平均池化则取平均。它们可以降低分辨率与后续计算量,并提供一定局部稳定性,但也会丢失细节,不能保证重要特征永远不变。检测小物体或精确边界时,这种损失尤其需要考虑。

实例 ​

python
import numpy as np

def pool_max_2d(matrix, window=2, stride=None):
    values = np.asarray(matrix, dtype=float)
    stride = window if stride is None else stride
    if values.ndim != 2 or min(window, stride) < 1:
        raise ValueError("需要二维输入与正的窗口、步长")
    out_h = (values.shape[0] - window) // stride + 1
    out_w = (values.shape[1] - window) // stride + 1
    if out_h <= 0 or out_w <= 0:
        raise ValueError("池化窗口超过输入")
    pooled = np.empty((out_h, out_w), dtype=float)
    for row, y in enumerate(range(0, values.shape[0] - window + 1, stride)):
        for column, x in enumerate(range(0, values.shape[1] - window + 1, stride)):
            pooled[row, column] = values[y:y + window, x:x + window].max()
    return pooled

if __name__ == "__main__":
    feature = np.array([[0, 1, 3, 2], [2, 4, 1, 0],
                        [1, 0, 5, 2], [3, 2, 1, 4]], dtype=float)
    print("示例特征:\n", feature)
    print("不重叠最大池化:\n", pool_max_2d(feature))
    print("重叠最大池化:\n", pool_max_2d(feature, window=2, stride=1))

经典网络的设计变化 ​

架构首次发表时间主要设计思想学习时关注什么
AlexNet2012深层卷积、ReLU、Dropout 与数据增强的组合GPU 训练与大规模分类的结合
VGG2014反复使用较小的 3×3 卷积规则堆叠与较大的参数量
ResNet2015通过残差路径学习增量映射深层优化与信息传递
EfficientNet2019联合缩放深度、宽度和分辨率在计算预算下安排模型规模

这些是历史上的重要路线,不能把发表时的速度或排名直接当成今天所有设备上的结论。任务、输入尺寸、训练策略和预训练权重都会影响实际选择。

残差路径保留输入 ​

残差块采用 y=F(x)+x,让主分支学习对输入的变化。如果分辨率或通道数改变,需要用投影让捷径分支与主分支形状一致,再做逐元素相加。

这种路径有助于深层优化和梯度传播,但不意味着梯度问题全部消失。下面的分类器包含卷积、批归一化、残差、下采样、全局池化和分类头,只用随机输入检查前向形状,没有进行训练。

实例 ​

python
import torch
from torch import nn

class ResidualUnit(nn.Module):
    def __init__(self, input_channels, output_channels, step=1):
        super().__init__()
        self.main = nn.Sequential(
            nn.Conv2d(input_channels, output_channels, 3, stride=step, padding=1, bias=False),
            nn.BatchNorm2d(output_channels), nn.ReLU(),
            nn.Conv2d(output_channels, output_channels, 3, padding=1, bias=False),
            nn.BatchNorm2d(output_channels),
        )
        self.skip = nn.Identity()
        if input_channels != output_channels or step != 1:
            self.skip = nn.Sequential(
                nn.Conv2d(input_channels, output_channels, 1, stride=step, bias=False),
                nn.BatchNorm2d(output_channels),
            )
        self.activation = nn.ReLU()

    def forward(self, tensor):
        return self.activation(self.main(tensor) + self.skip(tensor))

class ResidualClassifier(nn.Module):
    def __init__(self, classes=10):
        super().__init__()
        self.stem = nn.Sequential(nn.Conv2d(3, 24, 3, padding=1, bias=False),
                                  nn.BatchNorm2d(24), nn.ReLU())
        self.features = nn.Sequential(
            ResidualUnit(24, 24), ResidualUnit(24, 48, step=2),
            ResidualUnit(48, 48),
        )
        self.spatial_summary = nn.AdaptiveAvgPool2d(1)
        self.classification_head = nn.Linear(48, classes)

    def forward(self, image_batch):
        if image_batch.ndim != 4 or image_batch.shape[1] != 3:
            raise ValueError("分类器要求 B×3×H×W 的 RGB 张量")
        features = self.features(self.stem(image_batch))
        summary = self.spatial_summary(features).flatten(1)
        return self.classification_head(summary)

if __name__ == "__main__":
    torch.manual_seed(113)
    network = ResidualClassifier(classes=10).eval()
    sample_batch = torch.randn(4, 3, 32, 32)
    with torch.inference_mode():
        logits = network(sample_batch)
    print(network)
    print("输入张量:", tuple(sample_batch.shape))
    print("输出 logits:", tuple(logits.shape))
    print("参数总数:", sum(parameter.numel() for parameter in network.parameters()))
    print("当前权重未训练,输出不能当作物体识别结果。")

需要安装适合本机的 PyTorch;CPU 可完成这一小规模形状演示。分类头输出的是 logits,训练时通常直接交给交叉熵,不必预先做 Softmax。推理时可转换为分布,但随机模型的最大值不具有可靠识别含义。

Vision Transformer ​

ViT 将图像变成小块序列,再使用 Transformer 编码器处理。它展示了通用序列结构在视觉中的用途;成功通常还依赖数据规模、增强和预训练。可以从 ViT 论文了解最初的设计。

把图像切成 Patch ​

224×224 图像用 16×16 不重叠块切分,会产生 14×14=196 个块。RGB 下每块包含 16×16×3 个数,经展平与线性投影得到统一宽度的向量。也可以用核大小与步长都为块边长的卷积实现相同映射。

实例 ​

python
import torch
from torch import nn

class ImagePatchTokens(nn.Module):
    def __init__(self, image_size=224, patch_size=16, channels=3, width=192):
        super().__init__()
        if image_size % patch_size:
            raise ValueError("本例要求图像边长可被块边长整除")
        self.image_size = image_size
        self.patch_size = patch_size
        self.token_count = (image_size // patch_size) ** 2
        self.project = nn.Conv2d(channels, width, kernel_size=patch_size, stride=patch_size)

    def forward(self, images):
        if tuple(images.shape[-2:]) != (self.image_size, self.image_size):
            raise ValueError("输入分辨率与初始化配置不同")
        grid = self.project(images)
        return grid.flatten(start_dim=2).transpose(1, 2)

if __name__ == "__main__":
    module = ImagePatchTokens(image_size=224, patch_size=16, width=192)
    batch = torch.randn(1, 3, 224, 224)
    with torch.inference_mode():
        sequence = module(batch)
    print("图像:", tuple(batch.shape))
    print("块序列:", tuple(sequence.shape))
    print("块数量:", module.token_count)

组合完整的 ViT 分类结构 ​

经典分类结构会在块序列前增加可学习的 class token,让它在注意力层中汇总信息;再加入位置表,使网络区分块的位置。经过多层归一化、注意力和 MLP 后,读取 class token 并映射到类别分数。

下面重新给出所需类,可单独保存运行。它手工实现多头注意力与残差块,使用小分辨率和较小宽度检查结构。改变分辨率时位置表长度也要处理,不能直接向固定表输入任意尺寸。

实例 ​

python
import torch
from torch import nn

class PatchSequence(nn.Module):
    def __init__(self, side, patch, width):
        super().__init__()
        if side % patch:
            raise ValueError("图像尺寸必须整除 patch")
        self.side = side
        self.count = (side // patch) ** 2
        self.embedding = nn.Conv2d(3, width, patch, stride=patch)

    def forward(self, images):
        if tuple(images.shape[-2:]) != (self.side, self.side):
            raise ValueError("输入尺寸与位置表不匹配")
        return self.embedding(images).flatten(2).transpose(1, 2)

class VisualAttention(nn.Module):
    def __init__(self, width, head_count):
        super().__init__()
        if width % head_count:
            raise ValueError("特征宽度应能被头数整除")
        self.head_count = head_count
        self.part_width = width // head_count
        self.projection = nn.Linear(width, 3 * width)
        self.combine = nn.Linear(width, width)

    def forward(self, tokens):
        batch, length, width = tokens.shape
        projected = self.projection(tokens)
        projected = projected.reshape(batch, length, 3, self.head_count, self.part_width)
        projected = projected.permute(2, 0, 3, 1, 4)
        queries, keys, values = projected.unbind(dim=0)
        logits = torch.matmul(queries, keys.transpose(-1, -2)) / self.part_width ** 0.5
        attention = logits.softmax(dim=-1)
        readout = torch.matmul(attention, values).transpose(1, 2).reshape(batch, length, width)
        return self.combine(readout)

class VisualEncoderBlock(nn.Module):
    def __init__(self, width, heads, expansion=4):
        super().__init__()
        self.attention_norm = nn.LayerNorm(width)
        self.attention = VisualAttention(width, heads)
        self.mlp_norm = nn.LayerNorm(width)
        self.mlp = nn.Sequential(nn.Linear(width, expansion * width), nn.GELU(),
                                  nn.Linear(expansion * width, width))

    def forward(self, tokens):
        tokens = tokens + self.attention(self.attention_norm(tokens))
        return tokens + self.mlp(self.mlp_norm(tokens))

class CompactVisionTransformer(nn.Module):
    def __init__(self, side=32, patch=8, width=128, depth=4, heads=4, classes=10):
        super().__init__()
        self.patches = PatchSequence(side, patch, width)
        self.summary_token = nn.Parameter(torch.zeros(1, 1, width))
        self.positions = nn.Parameter(torch.zeros(1, self.patches.count + 1, width))
        self.layers = nn.ModuleList([VisualEncoderBlock(width, heads) for _ in range(depth)])
        self.final_norm = nn.LayerNorm(width)
        self.classifier = nn.Linear(width, classes)
        nn.init.trunc_normal_(self.positions, std=0.02)
        nn.init.trunc_normal_(self.summary_token, std=0.02)

    def forward(self, images):
        tokens = self.patches(images)
        first = self.summary_token.expand(images.shape[0], -1, -1)
        tokens = torch.cat([first, tokens], dim=1) + self.positions
        for layer in self.layers:
            tokens = layer(tokens)
        return self.classifier(self.final_norm(tokens)[:, 0])

if __name__ == "__main__":
    torch.manual_seed(127)
    model = CompactVisionTransformer().eval()
    images = torch.randn(2, 3, 32, 32)
    with torch.inference_mode():
        scores = model(images)
    print("位置向量数量:", model.positions.shape[1])
    print("图像与分类输出:", tuple(images.shape), tuple(scores.shape))
    print("参数量:", sum(value.numel() for value in model.parameters()))
    print("本例只验证网络结构,没有训练或下载任何权重。")

CNN 与 ViT 的取舍 ​

方面卷积路线ViT 路线
结构偏好局部性与参数共享较强通过位置机制和数据学习空间关系
数据条件小数据中常有实用优势原始设计较依赖充分训练,预训练可改变取舍
计算卷积内核成熟,成本取决于分辨率与通道全局注意力成本受块数影响明显
可视化可查看特征图和响应可查看注意力,但不能视作完整解释
远距离联系通过层级堆叠等逐渐扩大感受野全局注意力可直接连接远处块
任务选择结合已有权重与设备测试同样要比较迁移效果、延迟和内存

不存在一个固定样本量门槛,超过后就必须用 ViT。小数据配合好的预训练模型也能使用 Transformer;现代 CNN 也持续吸收其他设计经验。ConvNeXt 属于受到 Transformer 设计启发的卷积网络,不能直接把它当作注意力与卷积混合的通用代名词。

目标检测 ​

分类通常为整张图像给出类别,检测还要输出每个目标的边界框、类别和分数。同一图中可能有多个对象,评价既要看类别,也要看框与标注的重叠关系。框并不提供精确轮廓,遮挡、小目标和相似物体都可能造成错误。

两阶段的 R-CNN 路线 ​

两阶段方法先生成可能包含物体的候选区域,再为区域做分类与框回归。共享特征、候选网络和区域特征对齐的变化,使不同代际在精度和运行效率上有所改进。

模型主要变化计算方面的理解
R-CNN对候选区域提取 CNN 特征各区域重复计算较多
Fast R-CNN共享整图特征并使用 ROI Pooling减少候选区域的重复特征提取
Faster R-CNN用 RPN 生成候选区域将候选生成纳入网络
Mask R-CNN增加掩码分支并采用 ROIAlign同时承担实例分割任务

这些比较说明结构变化,不承诺每张图固定多少秒。推理速度依赖骨干、图像尺寸、候选数量、硬件与实现,应在相同条件下比较。

单阶段的 YOLO 路线 ​

单阶段检测通常直接在特征图上预测物体与位置,避免独立的区域提议步骤。早期 YOLO 可用 S×S 网格、每格预测边界框与类别来理解;后来的不同版本可能采用多尺度、无锚框或不同头部设计,不能把早期公式套到全部型号。

YOLO 常用于重视延迟的应用,但“实时”需要结合帧率、分辨率、批量和设备判断。提高置信度阈值可能减少误报,也可能遗漏目标;不能只看绘制出来的几个框评估检测质量。

DETR 的集合预测 ​

DETR 把目标检测组织为集合预测,通过学习到的查询和匹配损失产生一组对象结果,经典设计不依赖锚框与传统 NMS。它仍需要预处理、网络计算、类别判断与阈值处理,并不是完全没有后处理的任意检测器。

这种方式简化了部分手工设计环节,后续变体也改变了训练与查询组织。DETR 论文可以帮助理解一对一匹配为何能减少重复预测。

实作:YOLO11 检测与绘制 ​

这里保留 YOLO11 作为明确型号的示例,不称它为最新模型。默认模式生成三个虚构框,用于检查框、标签与图像绘制。真实模式必须安装 ultralytics 并提供已下载的权重路径,不会把人工框伪装成推理结果。

实例 ​

python
from dataclasses import asdict, dataclass
from pathlib import Path
import numpy as np
from PIL import Image, ImageDraw, ImageFont

@dataclass
class Detection:
    box: list[float]
    class_id: int
    label: str
    score: float
    simulated: bool

def demo_rgb_image(height=480, width=640):
    pixels = np.empty((height, width, 3), dtype=np.uint8)
    pixels[:, :, 0] = np.linspace(80, 190, width, dtype=np.uint8)[None, :]
    pixels[:, :, 1] = np.linspace(160, 95, height, dtype=np.uint8)[:, None]
    pixels[:, :, 2] = 175
    return pixels

class DetectionAdapter:
    def __init__(self, weights_path=None, demo=True):
        self.demo = demo
        self.weights_path = weights_path
        self.model = None
        self.colors = np.random.default_rng(131).integers(40, 225, size=(80, 3))

    def load(self):
        if self.demo:
            return self
        if not self.weights_path or not Path(self.weights_path).is_file():
            raise FileNotFoundError("真实模式需要已有的本地 YOLO11 权重")
        from ultralytics import YOLO
        self.model = YOLO(str(self.weights_path))
        return self

    def predict(self, image, confidence=0.25):
        if image.ndim != 3 or image.shape[2] != 3:
            raise ValueError("需要 RGB 三通道图像")
        height, width = image.shape[:2]
        if self.demo:
            layouts = [([0.12, 0.2, 0.31, 0.62], 0, "person", 0.91),
                       ([0.36, 0.42, 0.71, 0.82], 2, "car", 0.84),
                       ([0.76, 0.3, 0.91, 0.56], 16, "dog", 0.77)]
            return [Detection([a * width, b * height, c * width, d * height],
                              identifier, label, score, True)
                    for (a, b, c, d), identifier, label, score in layouts
                    if score >= confidence]
        if self.model is None:
            raise RuntimeError("应先调用 load() 准备模型")
        # 用 PIL 明确传入 RGB,避免不同数组接口的颜色约定混淆。
        predictions = self.model.predict(source=Image.fromarray(image), conf=confidence,
                                         verbose=False)
        records = []
        for result in predictions:
            if result.boxes is None:
                continue
            boxes = result.boxes.xyxy.detach().cpu().tolist()
            classes = result.boxes.cls.detach().cpu().tolist()
            scores = result.boxes.conf.detach().cpu().tolist()
            for box, class_number, score in zip(boxes, classes, scores):
                identifier = int(class_number)
                records.append(Detection(box, identifier, result.names[identifier],
                                          float(score), False))
        return records

    def draw(self, image, detections):
        canvas = Image.fromarray(np.asarray(image, dtype=np.uint8)).copy()
        painter = ImageDraw.Draw(canvas)
        font = ImageFont.load_default()
        for item in detections:
            x1, y1, x2, y2 = item.box
            x1, x2 = np.clip([x1, x2], 0, canvas.width - 1)
            y1, y2 = np.clip([y1, y2], 0, canvas.height - 1)
            if x2 <= x1 or y2 <= y1:
                continue
            color = tuple(int(value) for value in self.colors[item.class_id % len(self.colors)])
            painter.rectangle((x1, y1, x2, y2), outline=color, width=3)
            suffix = " DEMO" if item.simulated else ""
            text = f"{item.label} {item.score:.2f}{suffix}"
            bounds = painter.textbbox((0, 0), text, font=font)
            label_width = bounds[2] - bounds[0] + 6
            label_height = bounds[3] - bounds[1] + 6
            top = max(0, y1 - label_height)
            painter.rectangle((x1, top, min(canvas.width - 1, x1 + label_width),
                               top + label_height), fill=color)
            painter.text((x1 + 3, top + 2), text, fill="white", font=font)
        return np.asarray(canvas)

def real_yolo_file_example(weights, image_path, output_path):
    image_file = Path(image_path)
    if not image_file.is_file():
        raise FileNotFoundError(image_file)
    adapter = DetectionAdapter(weights_path=weights, demo=False).load()
    pixels = np.array(Image.open(image_file).convert("RGB"))
    detections = adapter.predict(pixels)
    Image.fromarray(adapter.draw(pixels, detections)).save(output_path)
    return [asdict(item) for item in detections]

if __name__ == "__main__":
    adapter = DetectionAdapter(demo=True).load()
    image = demo_rgb_image()
    records = adapter.predict(image)
    annotated = adapter.draw(image, records)
    print("人工测试图形尺寸:", image.shape)
    print("虚构框,仅用于绘制验证:", [asdict(item) for item in records])
    print("绘制后的数组尺寸:", annotated.shape)

默认演示依赖 NumPy 和 Pillow,不加载模型、不保存文件。真实函数会读取用户提供的图片和权重,并保存标注图;真实的训练也可通过 Ultralytics 的 train 接口配置数据集、轮数与图像尺寸,但本章不执行训练。检测模型与分割模型的结果字段不同,掩码仅在对应任务中出现,使用前可查看 YOLO11 文档。

图像分割 ​

分割把判断细化到像素。检测框只告诉物体大致位置,分割掩码可以描述轮廓,便于面积测量、前景提取与区域分析。分割输出仍会受边缘模糊、遮挡和领域差异影响,不能把掩码当作天然准确的测量结果。

语义、实例与全景分割 ​

任务表示目标例子常见路线
语义分割每个像素的类别所有人像素同为“人”,不区分个体U-Net、DeepLab、FCN 等
实例分割类别及不同对象实例分开标记两个人和两条狗Mask R-CNN、YOLO 分割版本
全景分割统一组织对象实例与背景区域同时描述行人、车辆与道路Panoptic FPN、MaskFormer 等

如果画面里有两个人和两条狗,语义结果包含两种对象类别,但不会直接输出“第一个人”和“第二个人”的独立实例。实例分割则为每个可区分目标给出单独掩码;全景表示还要处理道路、天空等背景区域。

SAM 的可提示分割 ​

2023 年发布的 Segment Anything Model 展示了可提示分割:先编码图像,再依据点、框或掩码等空间提示生成候选区域。经典公开的 SamPredictor 接口没有直接把任意文字当作提示的通用能力,文字定位通常需要其他模型或后续系统配合。

一个点可能对应多个合理区域,因此模型可返回多个候选及质量估计分数,不保证每次都是精确物体轮廓。需要选择、补充提示并检查结果。下面把接口形状演示与真正的 SAM 推理分开。

实例 ​

python
from pathlib import Path
import numpy as np
from PIL import Image

class SpatialPromptDemo:
    def __init__(self):
        self.shape = None

    def set_image(self, image):
        if image.ndim != 3 or image.shape[2] != 3:
            raise ValueError("本例要求 RGB 图像")
        self.shape = image.shape[:2]
        return self

    def require_image(self):
        if self.shape is None:
            raise RuntimeError("先设置图像再提交提示")

    def from_points(self, coordinates, labels):
        self.require_image()
        points = np.asarray(coordinates, dtype=float)
        labels = np.asarray(labels, dtype=int)
        if points.ndim != 2 or points.shape[1] != 2 or len(points) != len(labels):
            raise ValueError("每个点需要 x、y 坐标和一个标签")
        if not np.isin(labels, [0, 1]).all():
            raise ValueError("点标签只允许前景 1 或背景 0")
        yy, xx = np.indices(self.shape)
        mask = np.zeros(self.shape, dtype=bool)
        for (x, y), label in zip(points, labels):
            region = (xx - x) ** 2 + (yy - y) ** 2 <= 18 ** 2
            mask = (mask | region) if label == 1 else (mask & ~region)
        return {"mask": mask, "simulated": True, "meaning": "圆形只是接口替身"}

    def from_box(self, box):
        self.require_image()
        x1, y1, x2, y2 = [int(value) for value in box]
        height, width = self.shape
        x1, x2 = max(0, x1), min(width, x2)
        y1, y2 = max(0, y1), min(height, y2)
        if x2 <= x1 or y2 <= y1:
            raise ValueError("框没有有效面积")
        mask = np.zeros(self.shape, dtype=bool)
        mask[y1:y2, x1:x2] = True
        return {"mask": mask, "simulated": True, "meaning": "矩形不是模型预测"}

def sam_local_inference(checkpoint, image_path, output_dir, model_type="vit_b"):
    import torch
    from segment_anything import sam_model_registry, SamPredictor
    if not Path(checkpoint).is_file() or not Path(image_path).is_file():
        raise FileNotFoundError("需要已有的 checkpoint 和图片")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    network = sam_model_registry[model_type](checkpoint=str(checkpoint)).to(device).eval()
    predictor = SamPredictor(network)
    image = np.array(Image.open(image_path).convert("RGB"))
    predictor.set_image(image)
    height, width = image.shape[:2]
    points = np.array([[width * 0.5, height * 0.5]], dtype=np.float32)
    point_labels = np.array([1], dtype=np.int32)
    with torch.inference_mode():
        masks, quality_scores, low_resolution = predictor.predict(
            point_coords=points, point_labels=point_labels, multimask_output=True)
    target = Path(output_dir)
    target.mkdir(parents=True, exist_ok=True)
    for number, mask in enumerate(masks):
        Image.fromarray(mask.astype(np.uint8) * 255).save(target / f"candidate_{number}.png")
    return {"scores": quality_scores.tolist(), "mask_count": len(masks),
            "low_resolution_shape": tuple(low_resolution.shape)}

if __name__ == "__main__":
    pixels = np.zeros((160, 200, 3), dtype=np.uint8)
    demo = SpatialPromptDemo().set_image(pixels)
    for result in [demo.from_points([(60, 70)], [1]),
                   demo.from_box((30, 20, 140, 130)),
                   demo.from_points([(65, 70), (80, 70)], [1, 0])]:
        print(result["meaning"], "掩码面积", int(result["mask"].sum()))

真实分支需要 PyTorch、Pillow、NumPy 和匹配的 segment_anything 环境,权重类型必须与 model_type 相符。CPU 可用于某些小规模检查,但大权重推理可能很慢。模型获取与用法可查看 SAM 官方代码入口。默认入口只是几何掩码演示,不会调用该模型或写文件。

工业中怎样使用分割 ​

领域可支持的工作常见任务方向
医学影像器官或病灶区域辅助标注、尺寸分析语义或实例分割,需专业验证
道路环境可行驶区域、车道与场景要素语义分割及其他感知任务
遥感地表覆盖、建筑物轮廓语义与实例两类都可能需要
制造质检瑕疵区域、零件轮廓与测量根据对象与缺陷定义选择任务
视频编辑前景提取、人物与背景分离交互分割、实例及视频分割

部署前需要检查跨设备、光照、材料和成像方式的变化。像素精度、IoU、边界误差与实际业务成本应一起评估;医学和测量应用还不能把单次掩码输出直接替代专业判断。

扩散生成模型 ​

扩散路线通过向数据逐渐加噪构造学习任务,再训练网络依据噪声状态、时间及条件进行去噪。经典 Stable Diffusion 属于相关的潜空间扩散系统;不能根据商业产品名称推断所有未公开的内部架构。

前向过程:按调度加入噪声 ​

设每一步有噪声强度 β,令 α=1−β,累计乘积为 ᾱ。可直接从干净图像 x₀ 采样某一时间步:x_t=√ᾱ_t·x₀+√(1−ᾱ_t)·ε,其中 ε 来自标准高斯分布。

因此前向采样是随机过程,固定随机种子才能复现某次采样。噪声强度由调度控制,足够靠后的分布接近高斯噪声,并不意味着有限步末尾必然与干净图像彻底无关。

实例 ​

python
import numpy as np

class GaussianNoiseSchedule:
    def __init__(self, steps=1000, beta_begin=0.0001, beta_end=0.02, seed=137):
        if steps < 1 or not 0 < beta_begin <= beta_end < 1:
            raise ValueError("噪声调度配置无效")
        self.steps = steps
        self.betas = np.linspace(beta_begin, beta_end, steps, dtype=np.float64)
        self.alphas = 1.0 - self.betas
        self.cumulative = np.cumprod(self.alphas)
        self.random = np.random.default_rng(seed)

    def sample(self, clean, time_index, epsilon=None):
        if not 0 <= time_index < self.steps:
            raise IndexError("时间索引超出调度范围")
        clean = np.asarray(clean, dtype=np.float64)
        epsilon = self.random.normal(size=clean.shape) if epsilon is None else np.asarray(epsilon)
        if epsilon.shape != clean.shape:
            raise ValueError("噪声与图像的形状应相同")
        amount = self.cumulative[time_index]
        noisy = np.sqrt(amount) * clean + np.sqrt(1 - amount) * epsilon
        return noisy, epsilon

def synthetic_light_spot(side=64):
    axis = np.linspace(-1, 1, side)
    xx, yy = np.meshgrid(axis, axis)
    spot = np.exp(-(xx ** 2 + yy ** 2) / 0.12)
    spot = (spot - spot.min()) / (spot.max() - spot.min())
    return np.stack([spot, 0.75 * spot, 0.45 * spot], axis=-1)

if __name__ == "__main__":
    image = synthetic_light_spot()
    schedule = GaussianNoiseSchedule()
    shared_noise = np.random.default_rng(139).normal(size=image.shape)
    print("人工光斑图像形状:", image.shape)
    for step in [0, 99, 199, 299, 499, 999]:
        noisy, _ = schedule.sample(image, step, epsilon=shared_noise)
        alpha_bar = schedule.cumulative[step]
        snr = alpha_bar / (1 - alpha_bar)
        print("步", step, "累计系数", round(alpha_bar, 6),
              "系数信噪比", round(snr, 4), "数组标准差", round(float(noisy.std()), 4))

这里的“信噪比”是调度系数之比,实际图像信号功率还与数据分布有关。选定同一个 ε 只为便于比较噪声强度,不等同于模拟了完整马尔可夫采样轨迹。输入图形是中心亮斑,不是具有识别含义的照片。

反向过程:学习噪声或其他目标 ​

经典噪声预测训练随机选择时间步,构造 x_t,让网络根据 x_t、时间和可选条件预测 ε,再用均方误差等目标优化。其他参数化也可预测干净数据、速度或相关目标,不能把所有扩散训练都限定为一种输出。

生成时从噪声开始,按调度器计算下一状态。去噪网络不是简单把真实噪声从图里减掉,因为真实噪声在生成时未知;它学习的是训练分布下的估计关系。采样器如何使用预测,决定了各步更新与随机性。

U-Net 怎样保留空间细节 ​

U-Net 的下采样路径提取较大范围的语义,上采样路径恢复分辨率,对应尺度的跳跃连接传递细节。扩散版本还会引入时间编码、条件信息和注意力等组件。

U-Net 是重要的去噪骨干,但扩散系统也可以使用 Transformer 等其他网络。理解经典结构时,可以先追踪每层特征分辨率与跳跃连接的对应关系,再看文字条件如何进入网络。

DDPM、DDIM 与其他采样器 ​

采样路线基本思想步数示例的含义使用注意
DDPM概率性的逐步反向过程经典训练常见上千时间步推理配置与训练调度需区分
DDIM采用相关隐式采样路径可用更少推理步数η=0 时可形成确定性路径,其他设置可含随机性
LMS线性多步数值方法某些配置使用数十步检查是否与模型调度兼容
DPM-Solver 系列利用扩散方程结构的求解器一些任务可用较少步数收益与模型、配置及质量目标有关

步数不是算法不可改变的属性,默认调度器也由具体模型仓库与应用决定。20 步与 50 步的质量差异不能只靠名字预判,应固定提示、种子、尺寸和权重比较。

经典 Stable Diffusion 的部件 ​

以经典 v1 系列为例,VAE 将像素与潜变量相互转换,文字编码器产生条件表示,U-Net 在潜空间估计去噪目标。文生图从随机潜变量开始,最后用 VAE 解码;图生图先编码已有图像并按强度加噪;局部修改还需掩码与适配的管线或权重。

不同代际的 Stable Diffusion 会更改编码器与骨干,不能把经典三部件当作全部版本的固定实现。下面先用数组显示数据流,再提供需要本地权重的实际管线函数。

实例 ​

python
from pathlib import Path
import numpy as np
from PIL import Image

class LatentFlowDemo:
    def __init__(self, seed=149):
        self.random = np.random.default_rng(seed)
        self.events = []

    def text_condition(self, prompt):
        self.events.append({"operation": "encode_text", "characters": len(prompt)})
        return np.full((1, 16, 32), min(len(prompt), 100) / 100, dtype=np.float32)

    def encode_picture(self, image):
        values = np.asarray(image, dtype=np.float32) / 255
        small = values[::8, ::8].mean(axis=-1)
        self.events.append({"operation": "encode_image_demo", "shape": small.shape})
        return np.repeat(small[None, None, :, :], 4, axis=1)

    def step(self, latent, condition, time_index):
        # 人工衰减用于展示调度,不是训练得到的去噪器。
        self.events.append({"operation": "demo_step", "time": time_index})
        return latent * 0.95 + float(condition.mean()) * 0.01

    def decode(self, latent):
        values = latent[0, :3].transpose(1, 2, 0)
        values = np.repeat(np.repeat(values, 8, axis=0), 8, axis=1)
        return np.clip((values + 1) * 127.5, 0, 255).astype(np.uint8)

    def generate_demo(self, prompt, steps=20):
        if steps < 1:
            raise ValueError("演示步数必须为正")
        self.events.clear()
        condition = self.text_condition(prompt)
        latent = self.random.normal(size=(1, 4, 8, 8)).astype(np.float32)
        for time_index in reversed(range(steps)):
            latent = self.step(latent, condition, time_index)
        return {"image": self.decode(latent), "simulated": True,
                "events": list(self.events)}

def diffusion_text_image(local_model_dir, prompt, destination, seed=151):
    import torch
    from diffusers import StableDiffusionPipeline
    if not Path(local_model_dir).is_dir():
        raise FileNotFoundError("请先准备匹配的本地文生图管线目录")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float16 if device == "cuda" else torch.float32
    pipeline = StableDiffusionPipeline.from_pretrained(
        local_model_dir, torch_dtype=dtype, local_files_only=True).to(device)
    generator = torch.Generator(device=device).manual_seed(seed)
    image = pipeline(prompt=prompt, num_inference_steps=25,
                     generator=generator).images[0]
    image.save(destination)
    return image

def diffusion_image_image(local_model_dir, input_file, prompt, destination):
    import torch
    from diffusers import StableDiffusionImg2ImgPipeline
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float16 if device == "cuda" else torch.float32
    pipeline = StableDiffusionImg2ImgPipeline.from_pretrained(
        local_model_dir, torch_dtype=dtype, local_files_only=True).to(device)
    start_image = Image.open(input_file).convert("RGB").resize((512, 512))
    result = pipeline(prompt=prompt, image=start_image, strength=0.65,
                      num_inference_steps=30).images[0]
    result.save(destination)
    return result

def diffusion_inpaint(local_inpaint_dir, input_file, mask_file, prompt, destination):
    import torch
    from diffusers import StableDiffusionInpaintPipeline
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float16 if device == "cuda" else torch.float32
    pipeline = StableDiffusionInpaintPipeline.from_pretrained(
        local_inpaint_dir, torch_dtype=dtype, local_files_only=True).to(device)
    image = Image.open(input_file).convert("RGB").resize((512, 512))
    mask = Image.open(mask_file).convert("L").resize((512, 512), Image.Resampling.NEAREST)
    result = pipeline(prompt=prompt, image=image, mask_image=mask,
                      num_inference_steps=30).images[0]
    result.save(destination)
    return result

if __name__ == "__main__":
    demo = LatentFlowDemo()
    outcome = demo.generate_demo("花园里的一只橘猫", steps=20)
    print("数组尺寸:", outcome["image"].shape, "模拟标记:", outcome["simulated"])
    print("前几个操作记录:", outcome["events"][:3])
    print("这里只生成流程替身数组,不具有文生图能力,也不保存文件。")

真实函数需要兼容的 PyTorch、Diffusers、Transformers、Accelerate 和 Pillow,以及已准备的完整模型目录、磁盘与内存。CUDA 路径还需要支持的 GPU;CPU 可能耗时较长。局部修改应使用适配 inpainting 的权重,不能假定任意基础文生图 checkpoint 都能直接替代。掩码白色通常表示需要修改的区域,具体以所用管线约定为准,可从 Stable Diffusion 管线文档查阅对应任务。

CLIP 与图文表示对齐 ​

CLIP 是 2021 年公开的重要图文对比学习工作,通过两个编码器把图像与文本映射到可比较的表示空间。它不是历史上第一次研究图文对齐,但推动了可迁移视觉表示和零样本分类的广泛应用。

对比学习的匹配目标 ​

一个批次含 N 张图片与 N 段匹配文字,编码后得到 N×N 的相似度矩阵。对角线是已配对样本,其他位置作为批内负例;训练希望在图到文、文到图两个方向都把配对项排在前面。

负例中也可能存在语义相近或重复描述,因此数据质量与批次构造会影响学习。不能把“其他位置”直接理解成语义绝对不相关,只是当前训练配对关系不同。

两个编码器如何训练 ​

图像编码器可以是 ResNet 或 ViT,文字编码器可采用 Transformer;输出经投影与归一化后计算余弦相关性,并结合温度或缩放参数构造分类损失。下面用小型随机表示演示双向对比目标,再提供真实模型推理函数。

实例 ​

python
from pathlib import Path
import torch
from torch import nn
from torch.nn import functional as F
from PIL import Image

class ContrastivePairDemo(nn.Module):
    def __init__(self, image_width=24, text_width=20, shared_width=16):
        super().__init__()
        self.visual_projector = nn.Linear(image_width, shared_width)
        self.text_projector = nn.Linear(text_width, shared_width)
        self.log_scale = nn.Parameter(torch.tensor(2.0))

    def forward(self, image_features, text_features):
        images = F.normalize(self.visual_projector(image_features), dim=-1)
        texts = F.normalize(self.text_projector(text_features), dim=-1)
        similarities = images @ texts.T
        logits = self.log_scale.exp().clamp(max=100) * similarities
        labels = torch.arange(len(images), device=images.device)
        loss = (F.cross_entropy(logits, labels)
                + F.cross_entropy(logits.T, labels)) / 2
        return similarities, loss

def classify_with_local_clip(checkpoint_dir, image_path, descriptions):
    from transformers import CLIPModel, CLIPProcessor
    if not Path(checkpoint_dir).is_dir() or not Path(image_path).is_file():
        raise FileNotFoundError("需要本地 CLIP 目录和图像")
    if not descriptions:
        raise ValueError("候选描述列表不能为空")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    processor = CLIPProcessor.from_pretrained(checkpoint_dir, local_files_only=True)
    model = CLIPModel.from_pretrained(checkpoint_dir, local_files_only=True).to(device).eval()
    inputs = processor(text=descriptions, images=Image.open(image_path).convert("RGB"),
                       padding=True, return_tensors="pt")
    inputs = {key: value.to(device) for key, value in inputs.items()}
    with torch.inference_mode():
        output = model(**inputs)
        relative_scores = output.logits_per_image.softmax(dim=-1)[0].cpu().tolist()
    return sorted(zip(descriptions, relative_scores), key=lambda pair: pair[1], reverse=True)

if __name__ == "__main__":
    torch.manual_seed(157)
    network = ContrastivePairDemo().eval()
    visual = torch.randn(4, 24)
    textual = torch.randn(4, 20)
    with torch.inference_mode():
        matrix, contrastive_loss = network(visual, textual)
    print("配对矩阵形状:", tuple(matrix.shape))
    print("随机表示相似度:\n", matrix)
    print("双向对比损失的示意值:", float(contrastive_loss))
    print("这些随机表示没有猫、狗或汽车的语义,不应期待某类总分最高。")

默认入口只做随机矩阵计算,不下载权重或更新参数。真实函数需要 Transformers 与本地 CLIP 文件;可为猫、狗、汽车和人物等候选准备合适文本,再观察图文匹配,但结果始终依赖候选集合与模型训练。需要严格按权重对应的处理器缩放、裁剪与归一化图像。

零样本分类的含义 ​

不在目标类别数据集上重新训练分类头,也能将类别写成描述并比较图文相似度,这就是常见的 CLIP 零样本分类方式。描述可以区分“猫的照片”“草地上的橘猫”与“猫的素描”,但任意描述不保证都能被可靠识别。

候选 Softmax 只是这些候选之间的相对分数,不能直接视为校准后的真实正确概率。加入新候选会改变分布,领域变化也可能显著降低效果。CLIP 提供了有用的视觉语言接口,许多生成与理解系统在此基础上使用或改造相关编码器。

视觉语言模型 VLM ​

VLM 将图像表示与语言生成连接,使模型能够接收图像和问题,再产出文本回答。与只比较候选描述的 CLIP 不同,它需要处理视觉条件下的语言输出,也可能出现图像内容幻觉、计数错误和文字识别错误。

LLaVA 的组成 ​

经典 LLaVA 路线包括视觉编码器、投影连接模块和语言模型。图像的 patch 表示经投影对齐到语言模型的隐藏宽度,再与文本信息共同进入生成过程。LLaVA 1.5 等变体使用的连接器与训练设置有所变化,应按具体型号理解。

训练可分为视觉语言特征对齐与指令微调等阶段:先让连接模块建立表示关系,再使用图像指令数据训练可回答问题的系统。哪些部件冻结、哪些被更新取决于实现,不能一概说所有模型在第二阶段都训练全部参数。

视觉与语言的连接方式 ​

方法处理思路理解重点
图像标记占位在文本模板中标记图像位置标记通常不等于用单个词元承载整幅图像
视觉序列拼接将投影后的视觉特征与文本表示组合LLaVA 等使用相关路线,需对齐宽度和掩码
交叉注意力或查询连接器用查询从视觉特征中提取信息Flamingo、BLIP-2 的组件设计各有不同

不要根据闭源产品的使用界面猜测其内部拼接方法。下面先演示视觉投影、文本嵌入和序列连接,再给出本地 LLaVA 1.5 推理函数。随机连接器只证明张量能接起来,没有看图理解能力。

实例 ​

python
from pathlib import Path
import torch
from torch import nn
from PIL import Image

class VisualLanguageConnectorDemo(nn.Module):
    def __init__(self, visual_width=64, language_width=96, vocabulary=256):
        super().__init__()
        self.visual_projection = nn.Sequential(nn.Linear(visual_width, language_width),
                                               nn.GELU(), nn.Linear(language_width, language_width))
        self.text_embeddings = nn.Embedding(vocabulary, language_width)

    def forward(self, image_patch_features, token_ids):
        visual_tokens = self.visual_projection(image_patch_features)
        language_tokens = self.text_embeddings(token_ids)
        if visual_tokens.shape[0] != language_tokens.shape[0]:
            raise ValueError("图像和文字批量大小不同")
        combined = torch.cat([visual_tokens, language_tokens], dim=1)
        attention_mask = torch.ones(combined.shape[:2], dtype=torch.long, device=combined.device)
        return {"visual": visual_tokens, "text": language_tokens,
                "combined": combined, "attention_mask": attention_mask}

def llava_local_answer(model_directory, image_file, question, max_new_tokens=180):
    from transformers import AutoProcessor, LlavaForConditionalGeneration
    if not Path(model_directory).is_dir() or not Path(image_file).is_file():
        raise FileNotFoundError("需要已准备的 LLaVA 1.5 模型目录和图像")
    device = "cuda" if torch.cuda.is_available() else "cpu"
    dtype = torch.float16 if device == "cuda" else torch.float32
    processor = AutoProcessor.from_pretrained(model_directory, local_files_only=True)
    model = LlavaForConditionalGeneration.from_pretrained(
        model_directory, torch_dtype=dtype, local_files_only=True).to(device).eval()
    conversation = [{"role": "user", "content": [
        {"type": "image"}, {"type": "text", "text": question}]}]
    prompt = processor.apply_chat_template(conversation, add_generation_prompt=True)
    image = Image.open(image_file).convert("RGB")
    inputs = processor(text=prompt, images=image, return_tensors="pt")
    inputs = {key: value.to(device) for key, value in inputs.items()}
    if "pixel_values" in inputs:
        inputs["pixel_values"] = inputs["pixel_values"].to(dtype=dtype)
    with torch.inference_mode():
        generated = model.generate(**inputs, max_new_tokens=max_new_tokens, do_sample=False)
    prompt_length = inputs["input_ids"].shape[1]
    return processor.batch_decode(generated[:, prompt_length:], skip_special_tokens=True)[0]

if __name__ == "__main__":
    torch.manual_seed(163)
    connector = VisualLanguageConnectorDemo().eval()
    image_features = torch.randn(1, 16, 64)
    text_ids = torch.randint(0, 256, (1, 12))
    with torch.inference_mode():
        output = connector(image_features, text_ids)
    for name, tensor in output.items():
        print(name, tuple(tensor.shape))
    print("序列已连接,但此处没有语言模型,不会产生图像描述。")

真实函数需要 Transformers、PyTorch、Pillow 和与处理器相符的 LLaVA 1.5 权重。7B 级模型需要较多内存,FP16 权重本身就约十余 GB,运行还要额外缓存;CPU 可用性不代表速度可接受。调用模板、图像处理与模型类别应按 LLaVA 文档核对,不能把任意视觉模型交给同一个类加载。

实作:分类、检测与结果汇总 ​

最后把分类、检测和可视化连接为一条流水线。输入图像先规范为 RGB,分类器使用训练时一致的缩放与归一化;检测保留输入图像坐标;结果同时保存类别、分数、边界框与是否为演示的标记。分类标签集合必须与权重对应,不能只改类别名字就得到新模型。

下面的代码可与前面定义的 ResidualClassifier、DetectionAdapter、demo_rgb_image 放在同一脚本中。它提供独立的随机数据集、训练与验证循环、可信权重加载、结果持久化和绘制功能,但默认入口只提示如何组装,不执行训练或写文件。随机标签训练仅用于检查训练代码,不能展示真实识别能力。

实例 ​

python
import json
from dataclasses import asdict
from pathlib import Path
import numpy as np
import torch
from torch import nn
from torch.nn import functional as F
from torch.utils.data import Dataset, DataLoader
from PIL import Image

class RandomVisionDataset(Dataset):
    """固定随机样本只用于检查训练循环,不包含真实类别规律。"""

    def __init__(self, count=120, classes=10, seed=167):
        generator = torch.Generator().manual_seed(seed)
        self.images = torch.rand(count, 3, 32, 32, generator=generator)
        self.labels = torch.randint(0, classes, (count,), generator=generator)

    def __len__(self):
        return len(self.labels)

    def __getitem__(self, index):
        return self.images[index], self.labels[index]

class VisionApplication:
    def __init__(self, classifier, detector, class_names, device="cpu", trained=False):
        if not class_names:
            raise ValueError("必须提供与分类头对应的标签")
        self.device = torch.device(device)
        self.classifier = classifier.to(self.device)
        self.detector = detector
        self.class_names = list(class_names)
        self.trained = trained

    @staticmethod
    def rgb_array(image):
        if isinstance(image, Image.Image):
            return np.array(image.convert("RGB"))
        array = np.asarray(image)
        if array.ndim == 2:
            array = np.repeat(array[:, :, None], 3, axis=2)
        if array.ndim != 3 or array.shape[2] not in {3, 4}:
            raise ValueError("需要灰度、RGB 或 RGBA 图像")
        if array.shape[2] == 4:
            array = np.array(Image.fromarray(array.astype(np.uint8)).convert("RGB"))
        if array.dtype != np.uint8:
            raise ValueError("数组输入应是 0 到 255 的 uint8,避免重复缩放")
        return np.ascontiguousarray(array)

    def prepare_classifier_input(self, image):
        tensor = torch.from_numpy(image.copy()).permute(2, 0, 1).float().div(255)
        tensor = F.interpolate(tensor.unsqueeze(0), size=(32, 32),
                               mode="bilinear", align_corners=False)
        return tensor.to(self.device)

    def load_classifier(self, checkpoint):
        path = Path(checkpoint)
        if not path.is_file():
            raise FileNotFoundError(path)
        # 只加载自己信任来源的状态字典;版本需支持 weights_only。
        state = torch.load(path, map_location=self.device, weights_only=True)
        if not isinstance(state, dict):
            raise ValueError("权重文件应保存模型状态字典")
        self.classifier.load_state_dict(state, strict=True)
        self.trained = True
        return self

    def classify(self, image):
        self.classifier.eval()
        with torch.inference_mode():
            logits = self.classifier(self.prepare_classifier_input(image))
            if logits.shape[-1] != len(self.class_names):
                raise ValueError("标签数量与分类头输出不一致")
            distribution = logits.softmax(dim=-1)
            score, identifier = distribution.max(dim=-1)
        index = int(identifier.item())
        return {"class_id": index, "label": self.class_names[index],
                "relative_score": float(score.item()), "trained_weights": self.trained,
                "interpretation": "模型输出,需按实际数据验证" if self.trained
                                  else "随机权重输出,不能当作识别结论"}

    def process(self, image):
        pixels = self.rgb_array(image)
        classification = self.classify(pixels)
        detections = self.detector.predict(pixels) if self.detector is not None else []
        annotated = self.detector.draw(pixels, detections) if self.detector is not None else pixels.copy()
        return {"classification": classification,
                "detections": [asdict(item) for item in detections],
                "visualization": annotated,
                "input_shape": list(pixels.shape)}

    @staticmethod
    def save(result, directory):
        target = Path(directory)
        target.mkdir(parents=True, exist_ok=True)
        report = {key: value for key, value in result.items() if key != "visualization"}
        # 保留 box 坐标,便于下游检查与重新绘制。
        (target / "results.json").write_text(
            json.dumps(report, ensure_ascii=False, indent=2), encoding="utf-8")
        Image.fromarray(result["visualization"]).save(target / "annotated.png")
        return target

def evaluate_classifier(model, loader, device):
    model.eval()
    total_loss, correct, count = 0.0, 0, 0
    with torch.inference_mode():
        for images, labels in loader:
            images, labels = images.to(device), labels.to(device)
            logits = model(images)
            total_loss += F.cross_entropy(logits, labels, reduction="sum").item()
            correct += int((logits.argmax(dim=-1) == labels).sum().item())
            count += labels.numel()
    if count == 0:
        raise ValueError("验证数据集为空")
    return {"loss": total_loss / count, "accuracy": correct / count, "count": count}

def train_classifier_demo(application, epochs=2, batch_size=16):
    if epochs < 1 or batch_size < 1:
        raise ValueError("轮数与批量应为正")
    classes = len(application.class_names)
    training = RandomVisionDataset(count=120, classes=classes, seed=173)
    validation = RandomVisionDataset(count=40, classes=classes, seed=179)
    shuffle_generator = torch.Generator().manual_seed(181)
    training_loader = DataLoader(training, batch_size=batch_size, shuffle=True,
                                 generator=shuffle_generator)
    validation_loader = DataLoader(validation, batch_size=batch_size, shuffle=False)
    optimizer = torch.optim.Adam(application.classifier.parameters(), lr=0.001)
    history = []
    for epoch in range(epochs):
        application.classifier.train()
        loss_sum, correct, count = 0.0, 0, 0
        for images, labels in training_loader:
            images = images.to(application.device)
            labels = labels.to(application.device)
            optimizer.zero_grad(set_to_none=True)
            logits = application.classifier(images)
            loss = F.cross_entropy(logits, labels)
            loss.backward()
            optimizer.step()
            loss_sum += float(loss.item()) * labels.numel()
            correct += int((logits.argmax(dim=-1) == labels).sum().item())
            count += labels.numel()
        validation_metrics = evaluate_classifier(application.classifier,
                                                  validation_loader, application.device)
        row = {"epoch": epoch + 1, "training_loss": loss_sum / count,
               "training_accuracy": correct / count, "validation": validation_metrics,
               "random_data_only": True}
        history.append(row)
        print(json.dumps(row, ensure_ascii=False))
    # 随机数据训练不把模型升级为可用于真实识别的状态。
    application.trained = False
    return history

def assemble_demo_application():
    required = ["ResidualClassifier", "DetectionAdapter", "demo_rgb_image"]
    missing = [name for name in required if name not in globals()]
    if missing:
        raise RuntimeError("请先加入前文组件定义:" + ", ".join(missing))
    labels = ["airplane", "automobile", "bird", "cat", "deer",
              "dog", "frog", "horse", "ship", "truck"]
    torch.manual_seed(191)
    classifier = ResidualClassifier(classes=len(labels))
    detector = DetectionAdapter(demo=True).load()
    application = VisionApplication(classifier, detector, labels, device="cpu", trained=False)
    result = application.process(demo_rgb_image())
    return application, result

if __name__ == "__main__":
    print("加入前文组件后,可调用 assemble_demo_application() 进行随机权重流程检查。")
    print("train_classifier_demo(app) 仅用于演示训练与验证,不产生真实准确率结论。")
    print("需要保存时显式调用 app.save(result, 'vision_demo_output')。")

真实项目要用有权使用、标签一致且包含真实规律的数据,划分训练、验证和测试集合,并防止同一对象的近似图像泄漏到不同集合。分类器的颜色通道、缩放、归一化和标签顺序必须与训练一致;检测则要保留框、类别、输入尺寸与阈值。随机数据可以检查代码是否连通,却无法证明模型理解了照片。

进一步使用真实数据集或预训练权重微调前,先确认许可证、算力和评估标准,再比较架构与部署方式。对分类检查混淆矩阵与分类别质量,对检测检查定位与类别指标,对分割检查像素与边界表现,对 VLM 检查事实支持和幻觉。各任务输出形式不同,不能用一条“模型运行成功”的消息替代完整验证。