文章来源:机器学习AI算法工程
仅用于学术分享,如有侵权,请联系后台作删文处理
让 OpenClaw 指挥 YOLO,7×24 小时盯着流水线,发现缺陷立即停机报警,顺便生成日报——这听起来很美。
但现实是:OpenClaw 调用大模型推理需要 1-3 秒,YOLO 检测需要 0.1-0.5 秒,总延迟 5 秒以上,对高速流水线来说是致命的。
解决方案:不追求实时,先做离线自动化。
本教程不讲复杂原理,只讲三件事:
- 训练一个能用的 YOLO 缺陷检测模型
- 创建 OpenClaw 技能,集成 YOLO
- 配置自动化任务:日报、预警、趋势分析
全程低代码,大部分配置只需对着 OpenClaw 说句话。
第一步:快速训练 YOLO 模型
如果你已经有训练好的 YOLO 模型,直接跳到第二步。
一、环境配置(5 分钟)
# 创建虚拟环境conda create -n yolo-defect python=3.10-yconda activate yolo-defect# 安装 PyTorch(有 GPU 用第一个,无 GPU 用第二个)# GPU 版本(CUDA 12.1)pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cu121# CPU 版本pip install torch torchvision torchaudio --index-url https://download.pytorch.org/whl/cpu# 安装 YOLOv8pip install ultralytics -i https://pypi.douban.com/simple/二、准备数据集
目录结构:
defect_dataset/├── images/│ ├── train/ # 训练集图片(70%)│ │ ├── IMG_001.jpg│ │ └── ...│ └── val/ # 验证集图片(20%)└── labels/ # 标注文件(与 images 结构一一对应) ├── train/ │ ├── IMG_001.txt # 对应 IMG_001.jpg │ └── ... └── val/标注格式(每行一个缺陷):
类别ID 中心点x 中心点y 宽度 高度示例(检测到 2 个缺陷):
0 0.512 0.423 0.234 0.1561 0.678 0.345 0.089 0.123数据集配置文件(data.yaml):
path: /path/to/defect_dataset # 数据集根目录train: images/train # 训练集路径val: images/val # 验证集路径nc:4# 类别数量names:# 类别名称- scratch # 划痕- dent # 凹坑- stain # 污渍- crack # 裂纹三、开始训练
from ultralytics import YOLO# 加载预训练模型(yolov8n 最快,yolov8s 最平衡)model = YOLO('yolov8n.pt')# 开始训练(自动下载预训练权重)results = model.train( data='defect_dataset/data.yaml', epochs=100,# 训练轮数 imgsz=640,# 输入尺寸 batch=16,# 批次大小(根据 GPU 显存调整) name='defect_v1',# 实验名称 device=0,# GPU ID(CPU 设为 'cpu') patience=20# 早停机制)训练完成后,最佳模型保存在:
runs/detect/defect_v1/weights/best.pt快速验证模型效果:
from ultralytics import YOLO# 加载训练好的模型model = YOLO('runs/detect/defect_v1/weights/best.pt')# 单张图片检测results = model('test.jpg', conf=0.25)# 批量检测results = model('/data/products/*.jpg', conf=0.25, save=True)# 结果保存在 runs/detect/predict/ 目录第二步:创建 OpenClaw YOLO 技能
OpenClaw安装参考下面这篇文章:
OpenClaw实战教程:从零到一掌握本地AI智能体
OpenClaw 通过"技能"扩展功能。我们创建一个 YOLO 缺陷检测技能,让 OpenClaw 能够调用 YOLO 模型。
一、创建技能目录
mkdir-p yolo-defect-skill/toolscd yolo-defect-skill目录结构:
yolo-defect-skill/├── skill.json # 技能配置文件├── prompt.md # 系统提示词└── tools/ # 检测工具 ├── detect_single.py ├── detect_batch.py └── analyze.py二、编写技能配置文件
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}}三、编写检测工具
tools/detect_single.py:
from ultralytics import YOLOimport jsonfrom pathlib import Pathdefdetect_single(image_path:str, conf:float=0.25)->dict:""" 检测单张图片中的缺陷 Args: image_path: 图片路径 conf: 置信度阈值 Returns: 检测结果字典 """# 加载模型 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 Pathfrom.detect_single import detect_singledefdetect_batch(image_dir:str, conf:float=0.25)->dict:""" 批量检测目录下的所有图片 Args: image_dir: 图片目录 conf: 置信度阈值 Returns: 批量检测结果 """# 获取所有图片 image_files =list(Path(image_dir).glob("*.jpg"))+list(Path(image_dir).glob("*.png"))# 批量检测 all_results =[]for img_path in image_files:try: result = detect_single(str(img_path), conf) all_results.append(result)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']: class_name = det['class'] class_stats[class_name]= class_stats.get(class_name,0)+1return{'total_images': total_images,'total_detections': total_detections,'defect_rate':round(total_detections / total_images *100,2)if total_images >0else0,'class_statistics': class_stats,'detailed_results': all_results}tools/analyze.py:
import pandas as pdimport jsondefgenerate_report(results:dict, output_path:str,format:str='csv')->str:""" 生成检测报告 Args: results: 检测结果(来自 detect_batch) output_path: 输出路径 format: 输出格式('csv', 'json') Returns: 生成的文件路径 """# 提取详细数据 detailed_data =[]for img_result in results['detailed_results']:for det in img_result['detections']: detailed_data.append({'image_path': img_result['image_path'],'class': det['class'],'confidence': det['confidence'],'x1': det['bbox']['x1'],'y1': det['bbox']['y1'],'x2': det['bbox']['x2'],'y2': det['bbox']['y2']})# 生成 DataFrame df = pd.DataFrame(detailed_data)# 保存 output_file = Path(output_path)ifformat=='csv': df.to_csv(output_file, index=False, encoding='utf-8-sig')elifformat=='json': df.to_json(output_file, orient='records', force_ascii=False, indent=2)# 生成统计摘要 summary ={'总检测图片数': results['total_images'],'总缺陷数': results['total_detections'],'缺陷率':f"{results['defect_rate']}%",'各类别统计': results['class_statistics']}# 保存摘要 summary_file = output_file.parent /f"{output_file.stem}_summary.json"withopen(summary_file,'w', encoding='utf-8')as f: json.dump(summary, f, ensure_ascii=False, indent=2)returnstr(output_file),str(summary_file)四、安装技能到 OpenClaw
# 进入技能目录cd yolo-defect-skill# 安装技能openclaw skills install.# 验证安装openclaw skills list |grep yolo-defect-detect第三步:配置自动化任务(核心!)
这是最关键的一步。我们通过自然语言配置,让 OpenClaw 自动监测 YOLO 识别结果,并根据不同场景触发不同动作。
方案一:每日缺陷统计报表(定时任务)
场景:每天凌晨 2 点检测所有产品图片,早上 8 点推送报表到企业微信
配置方式(一句话搞定):
用户:每天凌晨 2 点,检测 /data/products/ 目录下所有图片,统计缺陷类型,早上 8 点把报表发我企业微信OpenClaw:已创建定时任务,每天 02:00 执行检测,08:00 推送报表OpenClaw 自动生成的配置:
tasks/daily_defect_report.yaml---name:"每日缺陷统计报表"schedule:cron:"0 2 * * *"workflow:-step: detecttool: yolo-defect-detect.detect_batchparams:image_dir:"/data/products"conf:0.25-step: generate_reporttool: yolo-defect-detect.generate_reportparams:results:"${steps.detect.output}"output_path:"/data/reports/daily_report_{{date}}.csv"format:"csv"-step: notifytool: wecom-bot.send_messageparams: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"收到的报表示例:
📊 今日缺陷统计总检测:102,345 件 | 缺陷数:1,237 件 | 不良率:1.21%缺陷分布:▸ 划痕:623 次(重点查 2 号线)▸ 凹坑:398 次▸ 污渍:216 次▸ 裂纹:0 次方案二:实时缺陷预警(文件监听)
场景:监听 /data/uav/ 目录,无人机上传新照片后自动检测,发现缺陷立即推送预警
配置方式:
用户:监听 /data/uav/ 目录,有新文件就用 YOLO 检测,发现缺陷立即发企业微信预警OpenClaw:已创建文件监听任务,检测到缺陷将推送至企业微信自动生成的配置:
tasks/realtime_defect_alert.yaml---name:"实时缺陷预警"description:"监听目录,新文件自动检测并预警"watch:directory:"/data/uav"pattern:"*.jpg"debounce: 5s # 5 秒内的新文件批量处理workflow:-step: detecttool: yolo-defect-detect.detect_singleparams:image_path:"${event.file_path}"conf:0.25-step: check_defectcondition:"${steps.detect.output.total_detections} > 0"tool: wecom-bot.send_messageparams:message:| ⚠️ 紧急预警:发现缺陷 照片:${event.file_name} 缺陷数:${steps.detect.output.total_detections} 检测结果: ${steps.detect.output.detections}priority:"high"收到的预警示例:
⚠️ 紧急预警:光伏板热斑照片:DJI_20240309_1423.jpg位置:1 号线工位 5时间:2024-03-09 14:23:15检测结果:▸ 划痕:5 处(置信度:0.87~0.95)▸ 裂纹:1 处(置信度:0.92)⚠️ 风险等级:高📍 立即停机检查![此处应有图片:企业微信收到的预警截图]
方案三:月度质量趋势分析(数据挖掘)
场景:统计过去 3 个月的缺陷数据,生成趋势图表,识别问题模式
配置方式:
用户:帮我统计过去 3 个月的缺陷数据,生成趋势图表OpenClaw:已生成趋势报告,划痕问题在 2 号线持续上升,建议重点关注自动生成的配置:
tasks/monthly_trend_analysis.yaml---name:"月度质量趋势分析"schedule:cron:"0 9 1 * *"# 每月 1 号早上 9 点workflow:-step: collect_datatool: file-system.list_filesparams:directory:"/data/reports"pattern:"daily_report_*.csv"date_range:"-3 months"-step: analyze_trendtool: data-analyze.trend_analysisparams:data_files:"${steps.collect_data.output}"metrics:["defect_rate","class_distribution","line_performance"]-step: generate_charttool: data-visual.create_chartparams:data:"${steps.analyze_trend.output}"chart_type:"line"output_path:"/data/charts/monthly_trend_{{date}}.png"-step: send_reporttool: wecom-bot.send_messageparams:message:| 📈 月度质量趋势分析 请查看附件 关键发现: 1. 划痕问题在 2 号线持续上升(+15%) 2. 凹坑问题整体下降(-8%) 3. 整体不良率稳定在 1.2% 左右attachments:["${steps.generate_chart.output}"]方案四:设备健康度评分(自动化决策)
场景:根据 YOLO 检测的缺陷数量,自动给每台设备打分,低于 60 分的推送维保建议
配置方式:
用户:给每台设备打分,低于 60 分的推送维保建议OpenClaw:已创建评分任务,依据 YOLO 检测的表面缺陷自动评分自动生成的配置:
tasks/device_health_scoring.yaml---name:"设备健康度评分"schedule:cron:"0 18 * * *"# 每天 18:00workflow:-step: collect_defectstool: yolo-defect-detect.detect_batchparams:image_dir:"/data/products"conf:0.25-step: calculate_scorestool: data-analyze.device_scoringparams:defect_data:"${steps.collect_defects.output}"scoring_rule:| 基础分:100 分 划痕:-2 分/个 凹坑:-3 分/个 污渍:-1 分/个 裂纹:-5 分/个-step: notify_low_scorecondition:"${steps.calculate_scores.output.min_score} < 60"tool: wecom-bot.send_messageparams:message:| ⚠️ 设备健康度预警 设备:${steps.calculate_scores.output.low_score_device} 评分:${steps.calculate_scores.output.min_score} 分 主要问题:${steps.calculate_scores.output.main_issues} 建议:立即安排维保priority:"high"推送的评分报告示例:
⚠️ 设备健康度预警设备:2 号线工位 3评分:45 分主要问题:划痕数量激增(共 35 处)评分明细:- 基础分:100 分- 划痕扣分:-35 分(35 处 × 2 分)- 凹坑扣分:-15 分(5 处 × 3 分)- 污渍扣分:-5 分(5 处 × 1 分)= 最终得分:45 分建议:立即安排维保,检查设备磨损情况方案五:自动化数据归档与检索(知识管理)
场景:把所有缺陷图片按类型归档,以后用自然语言就能快速检索
配置方式:
用户:把所有缺陷图片按类型归档,以后我说"找 3 月所有划痕"就能查到OpenClaw:已创建归档规则,支持自然语言检索自动生成的配置:
tasks/auto_archiving.yaml---name:"自动化数据归档"schedule:cron:"0 3 * * *"# 每天 3:00workflow:-step: detect_and_classifytool: yolo-defect-detect.detect_batchparams:image_dir:"/data/products/temp"conf:0.25-step: archive_by_classtool: file-system.archive_by_classparams:defect_data:"${steps.detect_and_classify.output.detailed_results}"target_dir:"/data/defects_archive/{{date}}/"naming_rule:"{class}_{timestamp}_{index}.jpg"自然语言检索示例:
用户:找 3 月所有划痕图片OpenClaw:找到 1,237 张划痕图片,已打包发送到企业微信第四步:企业微信集成配置
OpenClaw 支持多种消息推送渠道,这里以企业微信为例。
一、创建企业微信应用
登录 企业微信管理后台 进入「应用管理」→「应用」→「创建应用」 获取以下信息: 企业 ID(CorpId) 应用 Secret(Secret) 应用 ID(AgentId)
二、配置 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三、测试消息推送
# 发送测试消息openclaw wecom send "测试消息:YOLO 缺陷检测智能体已就绪"企业微信中应该能收到测试消息。
夜雨聆风