当前位置: 首页 > news >正文

YOLO python 实现多种物体识别(时钟,水杯,小熊,路人,车辆)

本文介绍了一个基于YOLO的目标检测类ObjectDetector,支持YOLOv8标准模型和YOLO-World自定义模型。该类提供了两种模型加载方式:标准YOLOv8模型(80类)和可自定义检测类别的YOLO-World模型。主要功能包括模型自动加载和单张图片检测,能够输出检测目标的类别、数量和平均置信度,并保存检测结果图像。使用示例展示了如何初始化检测器并进行图片检测。该实现具有自动回退机制,当指定模型加载失败时会自动切换为标准模型。

from ultralytics import YOLO
import cv2
import osclass ObjectDetector:def __init__(self, model_type='standard'):"""参数:model_type: 'standard' 或 'world'"""self.model_type = model_typeself.model = Noneself.load_model()def load_model(self):"""加载模型"""try:if self.model_type == 'world':# 加载YOLO World模型self.model = YOLO("E:/PYTHON/object_regconnition/YOLO-World/yolo_world_v2_l_clip_large_o365v1_goldg_pretrain_800ft-9df82e55.pth")# 设置自定义类别custom_classes = ["person", "bicycle", "car", "motorcycle", "bus", "truck", "dog", "cat", "bird", "chair", "table", "laptop", "phone"]self.model.set_classes(custom_classes)print("✅ YOLO World模型加载成功,使用自定义类别")else:# 加载标准YOLOv8模型self.model = YOLO('yolov8n.pt')print("✅ 标准YOLOv8模型加载成功,使用80个预定义类别")print(f"📊 可检测类别数量: {len(self.model.names)}")except Exception as e:print(f"❌ 模型加载失败: {e}")# 回退到标准模型print("🔄 回退到标准YOLOv8模型...")self.model = YOLO('yolov8n.pt')self.model_type = 'standard'def detect_image(self, image_path, save_result=True):"""检测单张图片"""if not os.path.exists(image_path):print(f"❌ 图片不存在: {image_path}")returntry:# 进行预测results = self.model.predict(image_path, conf=0.25)# 处理结果result = results[0]# 打印检测结果print(f"\n🎯 在 {os.path.basename(image_path)} 中检测到:")print("-" * 50)detections = {}for box in result.boxes:cls_id = int(box.cls.item())confidence = box.conf.item()class_name = self.model.names[cls_id]if class_name not in detections:detections[class_name] = []detections[class_name].append(confidence)# 打印汇总结果for class_name, confidences in detections.items():avg_conf = sum(confidences) / len(confidences)print(f"  {class_name}: {len(confidences)} 个, 平均置信度: {avg_conf:.3f}")# 保存结果图像if save_result:output_path = f"detected_{os.path.basename(image_path)}"result.save(filename=output_path)print(f"💾 结果保存为: {output_path}")return resultexcept Exception as e:print(f"❌ 检测失败: {e}")return None# 使用示例
if __name__ == "__main__":# 创建检测器detector = ObjectDetector(model_type='standard')  # 或 'world'# 检测图片image_path = "image.jpg"  # 替换为你的图片路径detector.detect_image(image_path)# 检测图片image_path = "image2.png"  # 替换为你的图片路径detector.detect_image(image_path)

http://www.dtcms.com/a/553847.html

相关文章:

  • wordpress如何自动采集网站图片建模培训
  • 建设银行网站会员怎么用装修设计公司快餐店
  • 华宇亮相2025丽泽法务论坛,共探法治前沿与法商融合新路径
  • 嫦娥号地月轨道、环月(一个月)MATLAB仿真
  • Spring AI Alibaba 【六】
  • .NET10 - 尝试一下Blazor Web Assembly Standalone App的fingerprint新特性
  • 浏览器使用 <embed> 标签预览 PDF 的原理
  • 未来之窗昭和仙君(四十七)开发商品进销存——东方仙盟筑基期
  • 交流平台网站架构怎么做wordpress客户端登录界面
  • 网站附件下载表格怎么做营销是做什么
  • Xcode26升级以后重要
  • Mac电脑解决sudo密码问题方法
  • 仓颉语言宏(Cangjie Macros)详细介绍及强大使用
  • Python异常、模块、包
  • flink 流式窗口
  • 仿京东电商的网站开发智慧团建网站什么时候维护好
  • 23.NAT之Easy-IP
  • Godot游戏开发——C# (一)
  • PyTorch实战:从零搭建CV模型技术文章大纲
  • 高效的DDC可编程控制器风机水泵空调节能控制器公司
  • PIL (Python Imaging Library) 相关方法详解1
  • U-Net 家族全解析
  • 德语网站制作网页设计建网站
  • Windows Linux 子系统 (WSL) 上的 Ubuntu
  • ftp工具下载网站源码教程手机视频wordpress
  • LeetCode 二叉树 437. 路径总和 III
  • 【GoLang】【框架学习】【GORM】4. 使用 BeforeUpdate hook 操作时,出现反射报错
  • 有哪些好点的单页网站公司管理制度完整版
  • 庭田科技亮相成都复材盛会,以仿真技术赋能产业革新
  • 网站安全认证去哪做国内十大咨询公司排名