产线质检 · 视频看一遍逐件判定

更新时间:
复制 MD 格式

每个零件一张合格参照图加一段白话标准,qwen4-max 看视频逐件比对,输出固定格式质检判定。

机加工零件的外观缺陷(划痕、油污、毛刺)传统上靠训练视觉模型或人工目检:训练要按品类采集并标注样本,换一类零件就要重来一轮;人工目检又难保各班次判定标准一致。本玩法把顺序倒过来——每个零件准备一张合格参照图、一段文字质检标准,让 qwen4-max 看一遍产线视频、对照参照图逐件比对,直接输出带出现时间与严重等级的固定格式质检判定。本篇以一条虚构机加工零件产线跑通,方法同样适用于 3C、汽车零部件、五金冲压的外观复检工位。

说明

免责声明:本页展示内容均为 AI 模型生成,仅供参考,不构成任何效果承诺;文中零件、产线画面与缺陷样本均为合成虚构的演示素材,缺陷由程序画入、画在哪里画了什么全程有记录,不指向任何真实工厂或产品;产线视频为本地帧合成,非真实拍摄;实际产出效果与 Credits 消耗以控制台“用量详情”为准。

调用链:生成 6 张合格参照图 → 在参照图上画入 6 处缺陷并写缺陷记录 → 本地合成合格/缺陷两条产线视频 → qwen4-max 看一遍视频、对照参照图与质检标准逐件比对 → 输出固定格式判定 → 与缺陷记录逐条核对:6/6 缺陷检出,合格片零误报。全链工具:bl image(参照图)、Pillow(画缺陷)、ffmpeg(合成视频)。

实测产出

说明输入素材与脚本原文见步骤 1–5。

6 处画入的缺陷全部被识别并定级:毛刺判 P0(装配前必须去除),划痕与油污判 P1(返修或清洗后复验);每条带出现时间、画面证据与返修建议,例如对螺母毛刺的描述:“六角螺母右侧棱边(约3点位置)外轮廓出现连续≥3个向外伸出的亮色尖状飞边”。合格片判“无异常”,一条缺陷都不报。

零件序号 / 零件画入的缺陷模型报出的出现时间(该零件停留时间段)定级(模型 = 预期)核对
第 1 件 · 深沟球轴承划痕1.2s(0.4–1.6)P1 = P1命中
第 2 件 · 直齿圆柱齿轮油污3.2s(2.4–3.6)P1 = P1命中
第 3 件 · 六角法兰螺母毛刺5.2s(4.4–5.6)P0 = P0命中
第 4 件 · 阶梯轴划痕7.2s(6.4–7.6)P1 = P1命中
第 5 件 · 圆形法兰盘油污9.2s(8.4–9.6)P1 = P1命中
第 6 件 · 圆柱螺旋压缩弹簧毛刺11.2s(10.4–11.6)P0 = P0命中
合格片 · 6 件合格零件未画任何缺陷一条异常都没报无问题零误报

查看实测产出 · qwen4-max 返回的完整判定原文(6 条缺陷,固定格式)

{
  "observations": [
    {
      "timestamp_sec": 1.2,
      "defect_type": "scratch",
      "severity": "P1",
      "confidence": 0.82,
      "evidence": "轴承外圈顶面(约12点位置)出现一条相对基准图新增的亮色折线状痕迹,横跨外圈端面,非倒角高光。",
      "rework_advice": "用油石/抛光布沿圆周方向轻抛外圈端面去除线痕,清洗后复验表面粗糙度。"
    },
    {
      "timestamp_sec": 3.2,
      "defect_type": "oil_stain",
      "severity": "P1",
      "confidence": 0.8,
      "evidence": "齿轮左下齿根附近端面(约7-8点位置)出现暗褐/黑色附着斑片,边界有扩散感,基准图该处为均匀拉丝面。",
      "rework_advice": "超声清洗或溶剂擦拭去除油污斑片,干燥后复验表面清洁度。"
    },
    {
      "timestamp_sec": 5.2,
      "defect_type": "burr",
      "severity": "P0",
      "confidence": 0.85,
      "evidence": "六角螺母右侧棱边(约3点位置)外轮廓出现连续≥3个向外伸出的亮色尖状飞边,超出基准六角轮廓。",
      "rework_advice": "装配前去毛刺:锉削/刷磨右侧棱边飞边并倒钝,清洗后复验轮廓。"
    },
    {
      "timestamp_sec": 7.2,
      "defect_type": "scratch",
      "severity": "P1",
      "confidence": 0.83,
      "evidence": "阶梯轴下部台阶端面出现一条相对基准图新增的亮色弧形线状沟痕,横跨台阶面,非加工纹理。",
      "rework_advice": "抛光去除台阶面线状划痕,清洗后复验表面质量。"
    },
    {
      "timestamp_sec": 9.2,
      "defect_type": "oil_stain",
      "severity": "P1",
      "confidence": 0.8,
      "evidence": "法兰右侧端面(约3点两螺栓孔之间)出现暗色附着斑片伴扩散小点,基准图该处为干净拉丝面。",
      "rework_advice": "溶剂清洗去除油污斑片,干燥后复验清洁度。"
    },
    {
      "timestamp_sec": 11.2,
      "defect_type": "burr",
      "severity": "P0",
      "confidence": 0.84,
      "evidence": "弹簧底端线圈外轮廓下方出现连续≥3个向外伸出的亮色尖状凸起/飞边,超出基准线圈轮廓。",
      "rework_advice": "装配前去除端部飞边毛刺(磨削/刷磨),清洗后复验端部轮廓。"
    }
  ],
  "overall": "reject"
}

查看核对结果 · verification.json(匹配规则与逐条偏移)

{
  "recall": "6/6",
  "hits": [
    {
      "slot": 1,
      "part": "ref_1",
      "type": "scratch",
      "timestamp_sec": 1.2,
      "window_sec": [0.4, 1.6],
      "offset_sec": 0.2,
      "severity_expected": "P1",
      "severity_reported": "P1",
      "severity_ok": true,
      "confidence": 0.82
    },
    {
      "slot": 2,
      "part": "ref_2",
      "type": "oil_stain",
      "timestamp_sec": 3.2,
      "window_sec": [2.4, 3.6],
      "offset_sec": 0.2,
      "severity_expected": "P1",
      "severity_reported": "P1",
      "severity_ok": true,
      "confidence": 0.8
    },
    {
      "slot": 3,
      "part": "ref_3",
      "type": "burr",
      "timestamp_sec": 5.2,
      "window_sec": [4.4, 5.6],
      "offset_sec": 0.2,
      "severity_expected": "P0",
      "severity_reported": "P0",
      "severity_ok": true,
      "confidence": 0.85
    },
    {
      "slot": 4,
      "part": "ref_4",
      "type": "scratch",
      "timestamp_sec": 7.2,
      "window_sec": [6.4, 7.6],
      "offset_sec": 0.2,
      "severity_expected": "P1",
      "severity_reported": "P1",
      "severity_ok": true,
      "confidence": 0.83
    },
    {
      "slot": 5,
      "part": "ref_5",
      "type": "oil_stain",
      "timestamp_sec": 9.2,
      "window_sec": [8.4, 9.6],
      "offset_sec": 0.2,
      "severity_expected": "P1",
      "severity_reported": "P1",
      "severity_ok": true,
      "confidence": 0.8
    },
    {
      "slot": 6,
      "part": "ref_6",
      "type": "burr",
      "timestamp_sec": 11.2,
      "window_sec": [10.4, 11.6],
      "offset_sec": 0.2,
      "severity_expected": "P0",
      "severity_reported": "P0",
      "severity_ok": true,
      "confidence": 0.84
    }
  ],
  "missed_slots": [],
  "false_positives_defect_video": [],
  "severity_match": "6/6",
  "pass_video_observations": 0,
  "pass_video_overall": "pass",
  "pass_clean": true,
  "overall_defect_video": "reject",
  "accept": true
}

操作步骤

步骤 1:生成合格参照图、写质检标准

用百炼命令行工具 bl image 命令按统一顶拍视角为 6 种零件各生成一张合格参照图,作为比对参照;质检标准写成一段白话:三类缺陷的定义、定级规则,以及不计缺陷的排除项(传送带纹理、阴影、倒角高光等)。

合格参照图(输入)

深沟球轴承(合格参照)

深沟球轴承合格参照图

直齿圆柱齿轮(合格参照)

直齿圆柱齿轮合格参照图

六角法兰螺母(合格参照)

六角法兰螺母合格参照图

阶梯轴(合格参照)

阶梯轴合格参照图

圆形法兰盘(合格参照)

圆形法兰盘合格参照图

圆柱螺旋压缩弹簧(合格参照)

圆柱螺旋压缩弹簧合格参照图

复现脚本

#!/usr/bin/env python3
"""方案一制备①:bl image generate 6 张合格零件基准图(工业顶拍、统一背景与光照)。
可复现:固定 seed;密钥环境变量 TOKEN_PLAN_API_KEY 优先(Token Plan sk-sp-),缺省向上级目录查找 .env。"""
import os, subprocess, sys

ROOT = os.path.dirname(os.path.abspath(__file__))
ASSETS = os.path.join(ROOT, "assets")
KEY = os.environ.get("TOKEN_PLAN_API_KEY")
if not KEY:
    d = ROOT
    for _ in range(6):
        p = os.path.join(d, ".env")
        if os.path.exists(p):
            KEY = [l.split("=", 1)[1].strip() for l in open(p) if l.startswith("TOKEN_PLAN_API_KEY=")][0]
            break
        d = os.path.dirname(d)
if not KEY:
    sys.exit("未找到 TOKEN_PLAN_API_KEY:请设环境变量,或在上级目录放置含该键的 .env")

BASE = ("工业质检基准照片:顶拍垂直视角,单个{part}零件居中置于深灰色哑光传送带背景上,"
        "金属表面机加工纹理均匀,无划痕、无油污、无毛刺,边缘完整清晰,"
        "柔和均匀工业照明,浅景深轻微, photorealistic,画面无文字、无水印、无人物、无其他零件")
PARTS = [
    ("ref_1", "深沟球轴承(金属外圈内圈与保持架钢球清晰可见)", 11),
    ("ref_2", "直齿圆柱齿轮(齿形完整、齿顶圆清晰)", 22),
    ("ref_3", "六角法兰螺母(螺纹孔与法兰面清晰)", 33),
    ("ref_4", "阶梯轴(车削台阶与轴端倒角清晰)", 44),
    ("ref_5", "圆形法兰盘(均布螺栓孔与中心孔清晰)", 55),
    ("ref_6", "圆柱螺旋压缩弹簧(端圈并紧磨平、螺距均匀)", 66),
]
env = dict(os.environ, BAILIAN_CALLER_TYPE="script", BAILIAN_CALLER_NAME="qoder", NO_COLOR="1")
for prefix, part, seed in PARTS:
    cmd = ["bl", "image", "generate", "--prompt", BASE.format(part=part),
           "--model", "qwen-image-3.0-pro",
           "--size", "1024*1024", "--seed", str(seed), "--prompt-extend", "false",
           "--watermark", "false", "--out-dir", ASSETS, "--out-prefix", prefix,
           "--api-key", KEY, "--base-url", "https://token-plan.cn-beijing.maas.aliyuncs.com",
           "--output", "json"]
    r = subprocess.run(cmd, env=env, capture_output=True, text=True)
    print(prefix, "rc=", r.returncode)
    if r.returncode != 0:
        print(r.stdout[-1500:], r.stderr[-1500:])
        sys.exit(f"FAIL {prefix}")
print("OK 6 refs:", sorted(f for f in os.listdir(ASSETS) if f.startswith("ref_")))
你是机加工零件产线的视觉质检工位。前 6 张图依次为视频中 6 个零件的合格基准图(黄金样本),视频为顶拍停走式质检工位:每 2 秒一个零件进入、停留、退出,顺序与基准图一致。将视频画面与对应基准图逐一对比,只报出相对基准图新增的异常,输出全部疑似缺陷:
1 划痕 scratch:金属表面(含加工面与外圆)的线状痕迹——亮色线或带亮边的暗色沟槽;
2 油污 oil_stain:表面暗褐/黑色附着斑片,边界有扩散感;
3 毛刺 burr:零件外轮廓边缘连续 ≥3 个向外伸出基准轮廓的亮色尖状凸起/飞边;
定级:毛刺=P0(装配前必须去除);划痕/油污=P1(返修或清洗后复验)。
每条缺陷给出:出现时间戳(秒,按视频时间轴)、类型、置信度 0-1、画面证据、返修建议、定级。
全片无缺陷时 observations 为空数组且 overall=pass;存在任一缺陷 overall=reject。
传送带纹理、零件阴影、孔洞透底、倒角高光、齿顶亮边、齿根反光点、六角棱角单点亮斑与基准图已有的氧化色痕不属于缺陷,不得报出;轮廓内部的反光亮斑不计毛刺。

步骤 2:在参照图上各画一处缺陷、写缺陷记录

用 Pillow 按三类形态在参照图上各加一处缺陷(划痕=亮线带暗沟、油污=暗色扩散斑、毛刺=外轮廓向外伸出的尖状凸起),落点先确认确在零件表面;同时把类型、精确位置框、面积与预期定级写入 defect_truth.json,画在哪里、画了什么全程有记录。

缺陷图(输入)

深沟球轴承(画入划痕,P1)

画入划痕的深沟球轴承

直齿圆柱齿轮(画入油污,P1)

画入油污的直齿圆柱齿轮

六角法兰螺母(画入毛刺,P0)

画入毛刺的六角法兰螺母

阶梯轴(画入划痕,P1)

画入划痕的阶梯轴

圆形法兰盘(画入油污,P1)

画入油污的圆形法兰盘

圆柱螺旋压缩弹簧(画入毛刺,P0)

画入毛刺的圆柱螺旋压缩弹簧

复现脚本

#!/usr/bin/env python3
"""方案一制备②:PIL 程序化注入三类缺陷 ×6(划痕=亮线 / 油污=暗斑 / 毛刺=边缘噪点)。
每处注入先校验落点确在零件掩膜内,再绘制;defect_truth.json 记录类型+精确 bbox+面积+预期定级。"""
import json, math, os
from PIL import Image, ImageDraw, ImageFilter

S = os.path.join(os.path.dirname(os.path.abspath(__file__)), "assets")
SEV = {"scratch": "P1", "oil_stain": "P1", "burr": "P0"}


def mask_of(im):
    g = im.convert("L")
    return g.point(lambda v: 255 if v > 90 else 0)


def coverage(m, box):
    region = m.crop(box)
    px = region.tobytes()
    return sum(1 for v in px if v) / len(px)


def longest_run_row(m):
    w, h = m.size
    px = m.load()
    best = (0, 0, 0)
    for y in range(160, h - 160, 4):
        run = start = 0
        for x in range(w):
            if px[x, y]:
                if run == 0:
                    start = x
                run += 1
                if run > best[0]:
                    best = (run, start, y)
            else:
                run = 0
    return best


def best_oil_center(m, r):
    w, h = m.size
    best = (0.0, None)
    for cy in range(220, h - 220, 40):
        for cx in range(220, w - 220, 40):
            c = coverage(m, (cx - r - 12, cy - r - 12, cx + r + 12, cy + r + 12))
            if c > best[0]:
                best = (c, (cx, cy))
    return best


def draw_scratch(ov, pts):
    d = ImageDraw.Draw(ov)
    d.line(pts, fill=(238, 243, 248, 230), width=9)
    d.line([(x + 1, y + 3) for x, y in pts], fill=(50, 54, 60, 190), width=4)
    for x, y in pts[1:-1]:
        d.line([(x, y), (x + 8, y - 7)], fill=(238, 243, 248, 170), width=2)


def draw_oil(ov, cx, cy, r):
    d = ImageDraw.Draw(ov)
    blob = [(cx + r * math.cos(a) * (0.75 + 0.35 * math.sin(3 * a)),
             cy + r * 0.72 * math.sin(a) * (0.8 + 0.3 * math.cos(2 * a)))
            for a in [i * math.pi / 9 for i in range(18)]]
    d.polygon(blob, fill=(24, 19, 14, 185))
    for dx, dy, rr in [(r * 0.9, -r * 0.5, 7), (-r * 0.8, r * 0.6, 5), (r * 0.4, r * 0.85, 4)]:
        d.ellipse([cx + dx - rr, cy + dy - rr, cx + dx + rr, cy + dy + rr], fill=(24, 19, 14, 160))


def draw_burr(ov, m, cx, cy, ang0, ang1):
    d = ImageDraw.Draw(ov)
    w, h = m.size
    px = m.load()
    pts = []
    for i in range(7):
        a = ang0 + (ang1 - ang0) * i / 6
        # 沿射线自外向内找零件外轮廓边界(毛刺长在外观边缘)
        edge = None
        for r in range(500, 60, -1):
            x, y = int(cx + r * math.cos(a)), int(cy + r * math.sin(a))
            if not (0 <= x < w and 0 <= y < h):
                continue
            if px[x, y]:
                edge = (int(cx + (r + 1) * math.cos(a)), int(cy + (r + 1) * math.sin(a)))
                break
        if edge is None:
            continue
        ex, ey = edge
        L = 10 + (i % 3) * 4
        tx, ty = ex + L * math.cos(a), ey + L * math.sin(a)
        perp = a + math.pi / 2
        bx, by = 3 * math.cos(perp), 3 * math.sin(perp)
        d.polygon([(ex + bx, ey + by), (tx, ty), (ex - bx, ey - by)], fill=(215, 220, 226, 230))
        pts.append((ex, ey))
    for ex, ey in pts:
        for k in range(4):
            d.point((ex + (k % 2) * 3 - 1, ey + (k // 2) * 3 - 1), fill=(225, 230, 235, 200))
    return pts


CFG = [
    ("defect_1", "ref_1", "scratch", {}),
    ("defect_2", "ref_2", "oil_stain", {"r": 48}),
    ("defect_3", "ref_3", "burr", {"cx": 512, "cy": 512, "a0": -0.5, "a1": 0.35}),
    ("defect_4", "ref_4", "scratch", {"rot": 18}),
    ("defect_5", "ref_5", "oil_stain", {"r": 55}),
    ("defect_6", "ref_6", "burr", {"cx": 512, "cy": 512, "a0": 1.15, "a1": 1.85}),
]

truth = []
for did, ref, typ, kw in CFG:
    im = Image.open(f"{S}/{ref}.png").convert("RGB")
    m = mask_of(im)
    ov = Image.new("RGBA", im.size, (0, 0, 0, 0))
    if typ == "scratch":
        run, x0, y = longest_run_row(m)
        assert run >= 180, (did, run)
        xs = [x0 + 15 + (run - 30) * i / 4 for i in range(5)]
        pts = [(int(x), y + (i % 2) * 6 - 3) for i, x in enumerate(xs)]
        if kw.get("rot"):
            # 斜跨台阶环:避免亮线与机加工环边平行而被当作几何轮廓
            a = math.radians(kw["rot"])
            cx = sum(p[0] for p in pts) / len(pts)
            cy = sum(p[1] for p in pts) / len(pts)
            pts = [(int(cx + (x - cx) * math.cos(a) - (yy - cy) * math.sin(a)),
                    int(cy + (x - cx) * math.sin(a) + (yy - cy) * math.cos(a))) for x, yy in pts]
        kw["pts"] = pts
        box = (min(p[0] for p in pts) - 4, min(p[1] for p in pts) - 8,
               max(p[0] for p in pts) + 10, max(p[1] for p in pts) + 8)
        assert coverage(m, box) > (0.3 if kw.get("rot") else 0.6), (did, coverage(m, box))
        draw_scratch(ov, pts)
    elif typ == "oil_stain":
        c, center = best_oil_center(m, kw["r"])
        assert c > 0.75 and center, (did, c)
        kw["cx"], kw["cy"] = center
        box = (kw["cx"] - kw["r"] - 12, kw["cy"] - kw["r"] - 12, kw["cx"] + kw["r"] + 12, kw["cy"] + kw["r"] + 12)
        draw_oil(ov, kw["cx"], kw["cy"], kw["r"])
    else:
        pts = draw_burr(ov, m, kw["cx"], kw["cy"], kw["a0"], kw["a1"])
        assert pts, did
        box = (min(p[0] for p in pts) - 6, min(p[1] for p in pts) - 6,
               max(p[0] for p in pts) + 18, max(p[1] for p in pts) + 18)
    ov = ov.filter(ImageFilter.GaussianBlur(0.6))
    out = Image.alpha_composite(im.convert("RGBA"), ov).convert("RGB")
    out.save(f"{S}/{did}.png")
    alpha = ov.split()[3]
    ab = alpha.getbbox()
    truth.append({"id": did, "part": ref, "type": typ, "bbox": list(ab),
                  "area_px": sum(1 for v in alpha.tobytes() if v > 40),
                  "expected_severity": SEV[typ]})
    print(did, typ, "bbox=", ab)

json.dump(truth, open(f"{S}/defect_truth.json", "w"), ensure_ascii=False, indent=1)
print("OK truth 6 条")
编号零件缺陷类型缺陷位置框(px)预期定级
defect_1深沟球轴承划痕414, 228, 608, 251P1
defect_2直齿圆柱齿轮油污410, 667, 513, 747P1
defect_3六角法兰螺母毛刺664, 408, 734, 575P0
defect_4阶梯轴划痕431, 574, 592, 638P1
defect_5圆形法兰盘油污683, 463, 799, 553P1
defect_6圆柱螺旋压缩弹簧毛刺449, 693, 601, 737P0

步骤 3:合成产线视频

顶拍、传送带走走停停的工位:每个零件 0.4s 进入、停留 1.2s、0.4s 退出,6 件共 12s,传送带纹理滚动模拟输送。合格片用合格参照图、缺陷片用缺陷图,ffmpeg 编码为两条 mp4;每个零件的停留时间段写入 video_truth.json 供后续核对。

产线视频(输入)

合格片:12 秒 · 6 件均合格,应判“无异常”

缺陷片:12 秒 · 6 处画入缺陷,应逐件报出

复现脚本

#!/usr/bin/env python3
"""方案一制备③:本地帧合成合格/缺陷产线视频(顶拍停走式质检工位,零生成 Credits)。
每槽 2s:进入 0.4s → 停留 1.2s(belt 滚动、零件静止)→ 退出 0.4s;video_truth.json 记录槽位时间窗。
ffmpeg 编码 H.264 yuv420p。"""
import json, os, subprocess
from collections import deque
from PIL import Image, ImageChops, ImageDraw, ImageFilter

R = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(R, "assets")
W = H = 640
FPS = 10
SLOT = 2.0
PART = 400
PX = (W - PART) // 2
DWELL_Y = (H - PART) // 2

# 传送带纹理 tile(含滚动余量)
belt = Image.new("RGB", (W, H + 48), (52, 56, 62))
d = ImageDraw.Draw(belt)
for y in range(0, H + 48, 24):
    d.line([(0, y), (W, y)], fill=(44, 48, 54), width=2)
    d.line([(0, y + 3), (W, y + 3)], fill=(60, 64, 70), width=1)
noise = Image.effect_noise((W, H + 48), 6).convert("L")
belt = Image.composite(Image.new("RGB", belt.size, (66, 70, 76)), belt, noise.point(lambda v: 255 if v > 150 else 0))


def clean_mask(mask, k=15):
    # 先剔除小连通域去背景噪点/亮条(闭运算会把它们连成大块逃过过滤),
    # 再闭运算≥15:齿隙/圈隙/法兰缘缺口一律用基准图自身像素回填,视频零件区域与基准图逐字一致
    w, h = mask.size
    px = mask.load()
    seen = bytearray(w * h)
    comps = []
    for sy in range(h):
        for sx in range(w):
            i = sy * w + sx
            if not px[sx, sy] or seen[i]:
                continue
            comp = []
            dq = deque([i])
            seen[i] = 1
            while dq:
                c = dq.popleft()
                comp.append(c)
                cx, cy = c % w, c // w
                for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
                    if 0 <= nx < w and 0 <= ny < h:
                        ni = ny * w + nx
                        if px[nx, ny] and not seen[ni]:
                            seen[ni] = 1
                            dq.append(ni)
            if len(comp) >= 400:
                comps.append(comp)
    out = Image.new("L", (w, h), 0)
    op = out.load()
    for comp in comps:
        for c in comp:
            op[c % w, c // w] = 255
    out = out.filter(ImageFilter.MaxFilter(max(k, 15))).filter(ImageFilter.MinFilter(max(k, 15)))
    # 扩 1px 覆盖抗锯齿边缘,再填封闭孔(暗带/轴孔):视频零件像素与基准图逐字一致,避免轮廓差异被误读
    out = out.filter(ImageFilter.MaxFilter(3))
    return fill_holes(out)


def fill_holes(out):
    w, h = out.size
    op = out.load()
    seen = bytearray(w * h)
    dq = deque()
    for x in range(w):
        for y in (0, h - 1):
            i = y * w + x
            if not op[x, y] and not seen[i]:
                seen[i] = 1
                dq.append(i)
    for y in range(h):
        for x in (0, w - 1):
            i = y * w + x
            if not op[x, y] and not seen[i]:
                seen[i] = 1
                dq.append(i)
    while dq:
        c = dq.popleft()
        cx, cy = c % w, c // w
        for nx, ny in ((cx + 1, cy), (cx - 1, cy), (cx, cy + 1), (cx, cy - 1)):
            if 0 <= nx < w and 0 <= ny < h:
                ni = ny * w + nx
                if not op[nx, ny] and not seen[ni]:
                    seen[ni] = 1
                    dq.append(ni)
    for i in range(w * h):
        if not seen[i]:
            op[i % w, i // w] = 255
    return out


def part_sprite(path, ref_path=None, k=1):
    im = Image.open(path).convert("RGBA").resize((PART, PART))
    if ref_path:
        # 缺陷 sprite = 基准图保真掩膜 ∪ 注入差异区;并集不再做连通域过滤(毛刺三角底落在轮廓外 1px,会被当噪点剔除)
        ref = Image.open(ref_path).convert("RGB").resize((PART, PART))
        base = clean_mask(ref.convert("L").point(lambda v: 255 if v > 90 else 0), k)
        diff = ImageChops.difference(im.convert("RGB"), ref).convert("L").point(lambda v: 255 if v > 12 else 0)
        mask = fill_holes(ImageChops.lighter(base, diff))
    else:
        # k>1 仅用于阶梯轴:填平法兰缘阈值缺口;其余零件不做闭运算(避免齿隙/凹角被连桥误读为毛刺)
        mask = clean_mask(im.convert("L").point(lambda v: 255 if v > 90 else 0), k)
    im.putalpha(mask)
    sh = Image.new("RGBA", (PART + 40, PART + 40), (0, 0, 0, 0))
    a = mask.point(lambda v: min(110, v))
    sh.paste(Image.new("RGBA", im.size, (10, 12, 16, 255)), (20, 26), a)
    sh = sh.filter(ImageFilter.GaussianBlur(7))
    sh.paste(im, (20, 20), im)
    return sh


def y_at(u):
    """u∈[0,2) 槽内时间 → 零件顶部 y"""
    if u < 0.4:
        return -PART - 20 + (DWELL_Y + PART + 20) * (u / 0.4)
    if u < 1.6:
        return DWELL_Y
    return DWELL_Y + (H + 20 - DWELL_Y) * ((u - 1.6) / 0.4)


def render(names, out, ref_names=None):
    ks = [1, 1, 1, 9, 1, 1]
    sprites = [part_sprite(f"{S}/{n}.png", f"{S}/{ref_names[i]}.png" if ref_names else None, ks[i])
               for i, n in enumerate(names)]
    fd = os.path.join(R, f"_frames_{out}")
    os.makedirs(fd, exist_ok=True)
    total = int(FPS * SLOT * len(names))
    for f in range(total):
        t = f / FPS
        slot = int(t // SLOT)
        u = t - slot * SLOT
        off = int(t * 40) % 24
        frame = belt.crop((0, off, W, off + H)).convert("RGBA")
        y = int(y_at(u))
        frame.alpha_composite(sprites[slot], (PX - 20, y - 20))
        frame.convert("RGB").save(f"{fd}/{f:03d}.png")
    subprocess.run(["ffmpeg", "-y", "-framerate", str(FPS), "-i", f"{fd}/%03d.png",
                    "-c:v", "libx264", "-pix_fmt", "yuv420p", "-crf", "23",
                    "-movflags", "+faststart", f"{S}/{out}.mp4"],
                   check=True, capture_output=True)
    for f in os.listdir(fd):
        os.remove(os.path.join(fd, f))
    os.rmdir(fd)
    print(out, os.path.getsize(f"{S}/{out}.mp4") // 1024, "KB")


refs = [f"ref_{i}" for i in range(1, 7)]
defs = [f"defect_{i}" for i in range(1, 7)]
render(refs, "line_pass")
render(defs, "line_defect", refs)

truth = json.load(open(f"{S}/defect_truth.json"))
slots = []
for i in range(6):
    slots.append({"slot": i + 1, "part": refs[i], "defect_id": truth[i]["id"],
                  "type": truth[i]["type"], "expected_severity": truth[i]["expected_severity"],
                  "window_sec": [round(i * SLOT + 0.4, 1), round(i * SLOT + 1.6, 1)],
                  "frame_bbox": [PX, DWELL_Y, PX + PART, DWELL_Y + PART]})
json.dump({"fps": FPS, "slot_sec": SLOT, "slots": slots},
          open(f"{S}/video_truth.json", "w"), ensure_ascii=False, indent=1)
print("OK videos + truth")
零件序号零件缺陷类型停留时间段(s)
1深沟球轴承划痕0.4 – 1.6
2直齿圆柱齿轮油污2.4 – 3.6
3六角法兰螺母毛刺4.4 – 5.6
4阶梯轴划痕6.4 – 7.6
5圆形法兰盘油污8.4 – 9.6
6圆柱螺旋压缩弹簧毛刺10.4 – 11.6

步骤 4:单次调用:视频 + 参照图 + 标准 → 固定格式判定

把 6 张合格参照图、产线视频(视频直接内嵌在请求里)与质检标准放进同一次请求发给 qwen4-max。模型对照参照图逐件比对、只报相对参照新增的异常,并按固定格式判定表逐件填写;两条视频各调用一次,原始响应全量保存。

说明关键参数:模型

qwen4-max · 固定格式判定表输出 · 输出长度上限 4000(模型的思考过程也计入)· 随机性固定(temperature=0 + 固定 seed),复跑可复现。
{
  "observations": [
    {
      "timestamp_sec": "数字,出现时间(秒)",
      "defect_type": "scratch 或 oil_stain 或 burr 或 other",
      "severity": "P0 或 P1 或 P2 或 none",
      "confidence": "数字,0-1",
      "evidence": "画面证据",
      "rework_advice": "返修建议"
    }
  ],
  "overall": "pass 或 reject"
}

复现脚本

#!/usr/bin/env python3
"""方案一④:质检标准 + 产线视频 → qwen4-max 单次调用(chat/completions · json_schema strict)。
视频以 base64 data URI 内嵌;合格/缺陷两条视频各一次调用;原始响应全量留档。
路由:Token Plan 专属端点 compatible-mode,密钥 TOKEN_PLAN_API_KEY(环境变量优先,缺省向上找 .env)。"""
import base64, json, os, urllib.request

R = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(R, "assets")


def _key():
    k = os.environ.get("TOKEN_PLAN_API_KEY")
    if k:
        return k
    d = os.path.dirname(os.path.abspath(__file__))
    for _ in range(6):
        p = os.path.join(d, ".env")
        if os.path.exists(p):
            for l in open(p):
                if l.startswith("TOKEN_PLAN_API_KEY="):
                    return l.split("=", 1)[1].strip()
        d = os.path.dirname(d)
    raise SystemExit("未找到 TOKEN_PLAN_API_KEY:请设环境变量,或在上级目录放置含该键的 .env")


KEY = _key()

STANDARD = (
    "你是机加工零件产线的视觉质检工位。前 6 张图依次为视频中 6 个零件的合格基准图(黄金样本),"
    "视频为顶拍停走式质检工位:每 2 秒一个零件进入、停留、退出,顺序与基准图一致。"
    "将视频画面与对应基准图逐一对比,只报出相对基准图新增的异常,输出所有疑似缺陷:\n"
    "1 划痕 scratch:金属表面(含加工面与外圆)的线状痕迹——亮色线或带亮边的暗色沟槽;\n"
    "2 油污 oil_stain:表面暗褐/黑色附着斑片,边界有扩散感;\n"
    "3 毛刺 burr:零件外轮廓边缘连续 ≥3 个向外伸出基准轮廓的亮色尖状凸起/飞边;\n"
    "定级:毛刺=P0(装配前必须去除);划痕/油污=P1(返修或清洗后复验)。\n"
    "每条缺陷给出:出现时间戳(秒,按视频时间轴)、类型、置信度 0-1、画面证据、返修建议、定级。\n"
    "全片无缺陷时 observations 为空数组且 overall=pass;存在任一缺陷 overall=reject。\n"
    "传送带纹理、零件阴影、孔洞透底、倒角高光、齿顶亮边、齿根反光点、六角棱角单点亮斑与基准图已有的氧化色痕不属于缺陷,不得报出;"
    "轮廓内部的反光亮斑不计毛刺。"
)

SCHEMA = {
    "type": "object", "additionalProperties": False,
    "properties": {
        "observations": {"type": "array", "items": {
            "type": "object", "additionalProperties": False,
            "properties": {
                "timestamp_sec": {"type": "number"},
                "defect_type": {"type": "string", "enum": ["scratch", "oil_stain", "burr", "other"]},
                "severity": {"type": "string", "enum": ["P0", "P1", "P2", "none"]},
                "confidence": {"type": "number"},
                "evidence": {"type": "string"},
                "rework_advice": {"type": "string"}},
            "required": ["timestamp_sec", "defect_type", "severity", "confidence", "evidence", "rework_advice"]}},
        "overall": {"type": "string", "enum": ["pass", "reject"]}},
    "required": ["observations", "overall"]}


def b64(p):
    return base64.b64encode(open(p, "rb").read()).decode()


def call(video):
    payload = {
        "model": "qwen4-max",
        "messages": [{"role": "user", "content": [
            {"type": "image_url", "image_url": {"url": f"data:image/png;base64,{b64(f'{S}/ref_{i}.png')}"}}
            for i in range(1, 7)] + [
            {"type": "video_url", "video_url": {"url": f"data:video/mp4;base64,{b64(f'{S}/{video}.mp4')}"}},
            {"type": "text", "text": STANDARD}]}],
        "response_format": {"type": "json_schema",
                            "json_schema": {"name": "qc_verdict", "strict": True, "schema": SCHEMA}},
        "max_tokens": 4000, "temperature": 0.0, "seed": 7}
    req = urllib.request.Request("https://token-plan.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions",
                                 data=json.dumps(payload).encode(),
                                 headers={"Authorization": f"Bearer {KEY}", "Content-Type": "application/json"})
    with urllib.request.urlopen(req, timeout=300) as r:
        return json.load(r)


for video in ["line_defect", "line_pass"]:
    resp = call(video)
    json.dump(resp, open(f"{R}/verdict_{video}.json", "w"), ensure_ascii=False, indent=1)
    v = json.loads(resp["choices"][0]["message"]["content"])
    print(video, "overall=", v["overall"], "obs=", len(v["observations"]),
          "finish=", resp["choices"][0]["finish_reason"])
    for o in v["observations"]:
        print("  ", o["timestamp_sec"], o["defect_type"], o["severity"], round(o["confidence"], 2), o["evidence"][:40])

步骤 5:与缺陷记录逐条核对、合格片对照

核对脚本把判定与缺陷记录逐条匹配:缺陷类型直接对 + 出现时间落在该零件停留时间段内(允许误差 ±0.6 秒)+ 画面证据描述含缺陷关键词 + 定级对账;模型报出的异常若对不上任何画入缺陷计误报,合格片要求一条异常都不报。本次结果:6 处全部检出(6/6)、定级一致 6/6、误报 0 条、合格片判“无异常”,六条出现时间都比停留时间段中心晚 0.2 秒。

复现脚本

#!/usr/bin/env python3
"""方案一⑤:判定 JSON 与注入真值核销。
匹配规则:类型直配(schema enum)+ 时间戳落槽窗 ±0.6s + evidence 关键词组校验 + 定级对账;
未被任何真值槽匹配的 observation 计误报;合格片要求 observations 为空且 overall=pass。"""
import json, os

R = os.path.dirname(os.path.abspath(__file__))
S = os.path.join(R, "assets")
KW = {"scratch": ["划痕", "刮伤", "亮线", "沟痕", "线状"],
      "oil_stain": ["油污", "油渍", "暗斑", "暗褐", "斑片"],
      "burr": ["毛刺", "飞边", "凸点", "凸起", "尖刺"]}
TOL = 0.6

truth = json.load(open(f"{S}/video_truth.json"))["slots"]
vd = json.loads(json.load(open(f"{R}/verdict_line_defect.json"))["choices"][0]["message"]["content"])
vp = json.loads(json.load(open(f"{R}/verdict_line_pass.json"))["choices"][0]["message"]["content"])

hits, used = [], set()
for slot in truth:
    w0, w1 = slot["window_sec"]
    match = None
    for i, o in enumerate(vd["observations"]):
        if i in used or o["defect_type"] != slot["type"]:
            continue
        if not (w0 - TOL <= o["timestamp_sec"] <= w1 + TOL):
            continue
        if not any(k in o["evidence"] for k in KW[slot["type"]]):
            continue
        match = (i, o)
        break
    if match:
        i, o = match
        used.add(i)
        hits.append({"slot": slot["slot"], "part": slot["part"], "type": slot["type"],
                     "timestamp_sec": o["timestamp_sec"], "window_sec": slot["window_sec"],
                     "offset_sec": round(o["timestamp_sec"] - (w0 + w1) / 2, 2),
                     "severity_expected": slot["expected_severity"], "severity_reported": o["severity"],
                     "severity_ok": o["severity"] == slot["expected_severity"],
                     "confidence": o["confidence"]})
missed = [s["slot"] for s in truth if s["slot"] not in [h["slot"] for h in hits]]
fps = [o for i, o in enumerate(vd["observations"]) if i not in used]
pass_clean = (vp["overall"] == "pass" and len(vp["observations"]) == 0)

result = {"recall": f"{len(hits)}/{len(truth)}", "hits": hits, "missed_slots": missed,
          "false_positives_defect_video": fps,
          "severity_match": f"{sum(1 for h in hits if h['severity_ok'])}/{len(hits)}",
          "pass_video_observations": len(vp["observations"]), "pass_video_overall": vp["overall"],
          "pass_clean": pass_clean,
          "overall_defect_video": vd["overall"],
          "accept": len(hits) == len(truth) and not fps and pass_clean and vd["overall"] == "reject"}
json.dump(result, open(f"{R}/verification.json", "w"), ensure_ascii=False, indent=1)
print("recall", result["recall"], "| severity", result["severity_match"],
      "| FP", len(fps), "| pass_clean", pass_clean, "| accept", result["accept"])
for h in hits:
    print("  slot", h["slot"], h["type"], h["timestamp_sec"], "offset", h["offset_sec"],
          h["severity_reported"], "ok" if h["severity_ok"] else "MISMATCH")

说明

  • 覆盖边界:本链路核验顶拍停留帧中可见的外观缺陷;小到看不见的缺陷、内部缺陷与尺寸偏差不在覆盖范围内,正式质检决策仍应遵循工厂自身质量体系,本玩法作为辅助复检工具。
  • 素材与标准:零件与产线画面为合成虚构,缺陷由程序画入且记录全程可知,用于验证链路;接入真实产线时以实际画面与质检标准替换,效果数据以试点实测为准。