OpenClaw + YOLO 离线自动化监测

概述与目标

**本文定位**:在已训练并验证的 YOLO 模型上接入 OpenClaw,形成批量检测、报表、预警、趋势分析和通知链路。这里记录的是一套可落地的离线自动化方法,不把大模型调度链路包装成毫秒级实时系统。 --- ## 文章来源与声明 - 来源:微信公众号「新机器视觉」 - 原文链接:[https://mp.weixin.qq.com/s/JE4jFdRm0NZDINRIhPvpBA](https://mp.weixin.qq.com/s/JE4jFdRm0NZDINRIhPvpBA) - 说明:本文仅用于学术分享,如有侵权请联系删除 --- ## 1. 背景与适用边界:先做离线自动化

让 OpenClaw 调度 YOLO 进行 24×7 产线监控,需要同时承担图像采集、模型推理、大模型分析和消息通知。当前记录中的延迟估计为:

  • OpenClaw 调用大模型推理:约 1–3 秒
  • YOLO 检测:约 0.1–0.5 秒
  • 总链路延迟常超过 5 秒,高速流水线难以接受

因此本方案优先保证批处理可复现和结果可追踪,不将其用于未经验证的高速停机控制。本文只覆盖:

  1. 训练一个可用的 YOLO 缺陷检测模型
  2. 创建 OpenClaw 技能,集成 YOLO
  3. 配置自动化任务:日报、预警、趋势分析

01 YOLO 前置(通用流程入口)

本页聚焦 OpenClaw 的离线自动化,不重复维护 YOLO 的通用安装、训练和推理教程。完整流程统一放在YOLO 主笔记:

  • 环境安装与 GPU/CPU 选择;
  • 数据集目录、标注格式和 data.yaml;
  • 640×480 融合输入的 Letterbox/坐标换算;
  • 训练、验证、单图和批量推理命令。

进入下面的 OpenClaw 技能流程前,准备好训练后的 best.pt、data.yaml 和可调用的检测器端点即可。若尚未训练模型,先按上述主笔记完成训练,再回到本页。


02 创建 OpenClaw YOLO 技能

OpenClaw 通过“技能”扩展功能。这里创建一个 YOLO 缺陷检测技能,让 OpenClaw 能调用 YOLO 模型。

1)创建技能目录

mkdir -p yolo-defect-skill/tools
cd yolo-defect-skill

目录结构建议:

yolo-defect-skill/
	skill.json
	prompt.md
	tools/
		detect_single.py
		detect_batch.py
		analyze.py

2)编写技能配置文件 skill.json

{
	"name": "yolo-defect-detect",
	"version": "1.0.0",
	"description": "使用 YOLO 检测产品表面缺陷(划痕、凹坑、污渍、裂纹)",
	"permissions": {
		"file.read": ["*"],
		"file.write": ["*"]
	},
	"tools": [
		"detect_single",
		"detect_batch",
		"generate_report"
	],
	"dependencies": [
		"ultralytics>=8.0.0",
		"opencv-python>=4.8.0",
		"pandas>=2.0.0"
	],
	"config": {
		"model_path": "runs/detect/defect_v1/weights/best.pt",
		"default_conf": 0.25,
		"default_iou": 0.45
	}
}

3)编写检测工具(示例)

tools/detect_single.py:

from ultralytics import YOLO

def detect_single(image_path: str, conf: float = 0.25) -> dict:
	"""检测单张图片中的缺陷"""
	model = YOLO('runs/detect/defect_v1/weights/best.pt')
	results = model(image_path, conf=conf)

	detections = []
	for r in results:
		for box in r.boxes:
			xyxy = box.xyxy[0].tolist()
			cls_id = int(box.cls[0])
			conf_score = float(box.conf[0])
			class_name = r.names[cls_id]
			detections.append({
				"class": class_name,
				"class_id": cls_id,
				"confidence": round(conf_score, 3),
				"bbox": {
					"x1": round(xyxy[0], 2),
					"y1": round(xyxy[1], 2),
					"x2": round(xyxy[2], 2),
					"y2": round(xyxy[3], 2)
				}
			})

	return {
		"image_path": str(image_path),
		"total_detections": len(detections),
		"detections": detections
	}

tools/detect_batch.py(原文此处代码截断较多,下面保留为“可补全模板”):

from pathlib import Path
from .detect_single import detect_single

def detect_batch(image_dir: str, conf: float = 0.25) -> dict:
	"""批量检测目录下所有图片"""
	image_dir = Path(image_dir)
	image_files = []
	image_files += list(image_dir.glob("*.jpg"))
	image_files += list(image_dir.glob("*.png"))

	all_results = []
	for img_path in image_files:
		try:
			all_results.append(detect_single(str(img_path), conf))
		except Exception as e:
			print(f"检测失败: {img_path},错误: {e}")

	total_images = len(image_files)
	total_detections = sum(r["total_detections"] for r in all_results)

	class_stats = {}
	for r in all_results:
		for det in r["detections"]:
			name = det["class"]
			class_stats[name] = class_stats.get(name, 0) + 1

	defect_rate = round((total_detections / total_images * 100), 2) if total_images else 0.0

	return {
		"total_images": total_images,
		"total_detections": total_detections,
		"defect_rate": defect_rate,
		"class_statistics": class_stats,
		"detailed_results": all_results
	}

4)安装技能到 OpenClaw

cd yolo-defect-skill
openclaw skills install .
openclaw skills list | grep yolo-defect-detect

03 配置自动化任务(核心)

通过自然语言配置任务,让 OpenClaw 自动监控 YOLO 输出并触发动作。

方案一:每日缺陷统计报表(定时任务)

场景:每天 02:00 检测所有产品图片,08:00 推送报表到企业微信。 示例配置(YAML):

name: "每日缺陷统计报表"
schedule:
	cron: "0 2 * * *"
workflow:
	- step: detect
		tool: yolo-defect-detect.detect_batch
		params:
			image_dir: "/data/products"
			conf: 0.25
	- step: generate_report
		tool: yolo-defect-detect.generate_report
		params:
			results: "${steps.detect.output}"
			output_path: "/data/reports/daily_report_DATE.csv"
			format: "csv"
	- step: notify
		tool: wecom-bot.send_message
		params:
			message: |
				今日缺陷统计
				总检测: ${steps.detect.output.total_images} 件
				缺陷数: ${steps.detect.output.total_detections} 件
				不良率: ${steps.detect.output.defect_rate}%
				缺陷分布: ${steps.detect.output.class_statistics}
			at_time: "08:00"

方案二:缺陷预警(文件监听)

场景:监听 /data/uav/,有新图片就检测,发现缺陷立即推送预警。

name: "缺陷预警"
description: "监听目录,新文件自动检测并预警"
watch:
	directory: "/data/uav"
	pattern: "*.jpg"
	debounce: 5s
workflow:
	- step: detect
		tool: yolo-defect-detect.detect_single
		params:
			image_path: "${event.file_path}"
			conf: 0.25
	- step: check_defect
		condition: "${steps.detect.output.total_detections} > 0"
		tool: wecom-bot.send_message
		params:
			message: |
				紧急预警: 发现缺陷
				照片: ${event.file_name}
				缺陷数: ${steps.detect.output.total_detections}
				结果: ${steps.detect.output.detections}
			priority: "high"

方案三:月度趋势分析(定时 + 图表)

场景:统计近 3 个月缺陷数据,生成趋势图表并推送。

name: "月度质量趋势分析"
schedule:
	cron: "0 9 1 * *"  # 每月 1 号 09:00
workflow:
	- step: collect_data
		tool: file-system.list_files
		params:
			directory: "/data/reports"
			pattern: "daily_report_*.csv"
			date_range: "-3 months"
	- step: analyze_trend
		tool: data-analyze.trend_analysis
		params:
			data_files: "${steps.collect_data.output}"
			metrics:
				- defect_rate
				- class_distribution
	- step: generate_chart
		tool: data-visual.create_chart
		params:
			data: "${steps.analyze_trend.output}"
			chart_type: "line"
			output_path: "/data/charts/monthly_trend_DATE.png"
	- step: send_report
		tool: wecom-bot.send_message
		params:
			message: |
				月度质量趋势分析(近 3 个月)
				关键发现:
				1. 划痕问题在 2 号线持续上升
				2. 凹坑问题整体下降
			attachments:
				- "${steps.generate_chart.output}"

方案四:设备健康度评分(自动化决策)

场景:根据缺陷数量给设备打分,低于阈值推送维保建议。

name: "设备健康度评分"
schedule:
	cron: "0 18 * * *"  # 每天 18:00
workflow:
	- step: collect_defects
		tool: yolo-defect-detect.detect_batch
		params:
			image_dir: "/data/products"
			conf: 0.25
	- step: calculate_scores
		tool: data-analyze.device_scoring
		params:
			defect_data: "${steps.collect_defects.output}"
			scoring_rule: |
				基础分: 100
				划痕: -2/个
				凹坑: -3/个
				污渍: -1/个
				裂纹: -5/个
	- step: notify_low_score
		condition: "${steps.calculate_scores.output.min_score} < 60"
		tool: wecom-bot.send_message
		params:
			message: |
				设备健康度预警
				设备: ${steps.calculate_scores.output.low_score_device}
				评分: ${steps.calculate_scores.output.min_score}
				建议: 立即安排维保

方案五:自动归档与自然语言检索(知识管理)

场景:缺陷图片按类型归档,后续可用自然语言检索。

name: "自动化数据归档"
schedule:
	cron: "0 3 * * *"  # 每天 03:00
workflow:
	- step: detect_and_classify
		tool: yolo-defect-detect.detect_batch
		params:
			image_dir: "/data/products/temp"
			conf: 0.25
	- step: archive_by_class
		tool: file-system.archive_by_class
		params:
			defect_data: "${steps.detect_and_classify.output.detailed_results}"
			target_dir: "/data/defects_archive/DATE/"
			naming_rule: "{class}_{timestamp}_{index}.jpg"

04 企业微信集成配置(示例)

1)创建企业微信应用

在企业微信管理后台创建应用并获取:

  • CorpId
  • Secret
  • AgentId

2)配置 OpenClaw 企业微信插件

openclaw plugins install @openclaw/wecom-bot

openclaw config set wecom.corpId "your-corp-id"
openclaw config set wecom.agentId "your-agent-id"
openclaw config set wecom.secret "your-secret"
openclaw config set wecom.enabled true

openclaw restart

3)测试消息推送

openclaw wecom send "测试消息:YOLO 缺陷检测智能体已就绪"

效果对比(示例表)

指标 人工质检 YOLO + OpenClaw 提升
检测准确率 78% 96% +18%
漏检率 22% 4% -82%
统计时间 1 小时/天 自动 -100%
响应时间 数小时 数分钟 -95%
成本 25 万/年 5 万/年 -80%
--- ## 06 验证、失败边界与结论

验证顺序

  1. 先用 YOLO 主笔记中的单图和批量推理命令确认 best.pt、类别映射和置信度阈值有效。
  2. 再单独运行 OpenClaw 技能的 detect_single 与 detect_batch,检查 JSON 字段、图片路径和检测数量。
  3. 最后启用定时任务、归档和通知;每一步都保留输入目录、模型版本、阈值、输出目录和失败日志。

失败边界

  • 模型未完成训练、类别顺序不一致或 data.yaml 不可读时,不进入 OpenClaw 调度层。
  • 文件监听/定时任务只能保证触发,不保证检测准确率;阈值、漏检和误检必须回到 YOLO 验证集重新评估。
  • 企业微信凭据、文件读写权限、网络和插件版本是独立故障源,应分别检查,不要统称为“模型问题”。
  • 高速流水线、需要毫秒级闭环或直接停机控制的场景不适用本方案,除非另行完成端到端延迟和安全验证。

文中的“效果对比”表来自原始方案示例,不是本机实测;在没有对应数据集、日期和评测脚本前,不应把其中的百分比当作本项目结论。

结论

本页保留 OpenClaw 自动化方法,YOLO 安装、训练、标注和推理统一回到 YOLO 主笔记,避免同一套检测教程在两个页面重复。


备注

  • 原文中部分代码片段存在截断与字符错误(例如 batch 检测统计、YAML 时间表达等)。本页已按“可运行、可补全”的结构重新排版,并把明显的断裂位置改成模板形式,便于你后续对接真实 OpenClaw 工具与插件。