YOLO + OpenClaw 缺陷检测智能体,低代码实战方案
向AI转型的程序员都关注公众号 机器学习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-y conda 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 # 安装 YOLOv8 pip 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.156 1 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/tools cd 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 YOLO import json from pathlib import Path defdetect_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 Path from.detect_single import detect_single defdetect_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)+1 return{ '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 pd import json defgenerate_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: 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"收到的报表示例:
📊 今日缺陷统计 总检测: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: 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"收到的预警示例:
⚠️ 紧急预警:光伏板热斑 照片: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_data tool: file-system.list_files params: directory:"/data/reports" pattern:"daily_report_*.csv" date_range:"-3 months" -step: analyze_trend tool:>用户:给每台设备打分,低于 60 分的推送维保建议 OpenClaw:已创建评分任务,依据 YOLO 检测的表面缺陷自动评分自动生成的配置:
tasks/device_health_scoring.yaml --- 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:>⚠️ 设备健康度预警 设备: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: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"自然语言检索示例:
用户:找 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 缺陷检测智能体已就绪"企业微信中应该能收到测试消息。
效果对比
指标 | 人工质检 | YOLO + OpenClaw | 提升 |
|---|---|---|---|
检测准确率 | 78% | 96% | +18% |
漏检率 | 22% | 4% | -82% |
统计时间 | 1 小时/天 | 自动 | -100% |
响应时间 | 数小时 | 数分钟 | -95% |
成本 | 25 万/年 | 5 万/年 | -80% |
机器学习算法AI大数据技术
搜索公众号添加:datanlp
长按图片,识别二维码
阅读过本文的人还看了以下文章:
最顶尖的OCR算法有哪些?
最强一键抠图19Kstar 的 Rembg 开源神器
实时语义分割ENet算法,提取书本/票据边缘
整理开源的中文大语言模型,以规模较小、可私有化部署、训练成本较低的模型为主
《大语言模型》PDF下载
动手学深度学习-(李沐)PyTorch版本
YOLOv9电动车头盔佩戴检测,详细讲解模型训练
TensorFlow 2.0深度学习案例实战
基于40万表格数据集TableBank,用MaskRCNN做表格检测
《基于深度学习的自然语言处理》中/英PDF
Deep Learning 中文版初版-周志华团队
【全套视频课】最全的目标检测算法系列讲解,通俗易懂!
《美团机器学习实践》_美团算法团队.pdf
《深度学习入门:基于Python的理论与实现》高清中文PDF+源码
《深度学习:基于Keras的Python实践》PDF和代码
特征提取与图像处理(第二版).pdf
python就业班学习视频,从入门到实战项目
2019最新《PyTorch自然语言处理》英、中文版PDF+源码
《21个项目玩转深度学习:基于TensorFlow的实践详解》完整版PDF+附书代码
《深度学习之pytorch》pdf+附书源码
PyTorch深度学习快速实战入门《pytorch-handbook》
【下载】豆瓣评分8.1,《机器学习实战:基于Scikit-Learn和TensorFlow》
《Python数据分析与挖掘实战》PDF+完整源码
汽车行业完整知识图谱项目实战视频(全23课)
李沐大神开源《动手学深度学习》,加州伯克利深度学习(2019春)教材
笔记、代码清晰易懂!李航《统计学习方法》最新资源全套!
《神经网络与深度学习》最新2018版中英PDF+源码
将机器学习模型部署为REST API
FashionAI服装属性标签图像识别Top1-5方案分享
重要开源!CNN-RNN-CTC 实现手写汉字识别
yolo3 检测出图像中的不规则汉字
同样是机器学习算法工程师,你的面试为什么过不了?
前海征信大数据算法:风险概率预测
【Keras】完整实现‘交通标志’分类、‘票据’分类两个项目,让你掌握深度学习图像分类
VGG16迁移学习,实现医学图像识别分类工程项目
特征工程(一)
特征工程(二) :文本数据的展开、过滤和分块
特征工程(三):特征缩放,从词袋到 TF-IDF
特征工程(四): 类别特征
特征工程(五): PCA 降维
特征工程(六): 非线性特征提取和模型堆叠
特征工程(七):图像特征提取和深度学习
如何利用全新的决策树集成级联结构gcForest做特征工程并打分?
Machine Learning Yearning 中文翻译稿
不断更新资源
深度学习、机器学习、数据分析、python
搜索公众号添加:datayx
