YOLOv8 classify介绍

2024-09-05 16:36
文章标签 介绍 yolov8 classify

本文主要是介绍YOLOv8 classify介绍,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

      图像分类器(image classifier)的输出是单个类别标签和置信度分数。当你只需要知道图像属于哪个类别,而不需要知道该类别的目标位于何处或它们的确切形状时,图像分类非常有用。

      YOLOv8支持的预训练分类模型包括:YOLOv8n-cls、YOLOv8s-cls、YOLOv8m-cls、YOLOv8l-cls、YOLOv8x-cls。分类模型在ImageNet数据集上进行预训练,而检测、分割和Pose模型是在COCO数据集上进行预训练。

      数据集格式

      (1).对于Ultralytics YOLO分类任务,数据集必须在根目录下以特定的拆分目录(split-directory)结构进行组织,以便进行正确的训练、测试和验证(可选的)过程。此结构包括用于训练(train)和测试(test)阶段的单独目录,以及用于验证(val)的可选目录。

      (2).每个目录都应包含数据集中每个类别的一个子目录。子目录以相应的类别命名,包含该类别的所有图像。确保每个图像文件都具有唯一的名称,并以JPEG或PNG等通用格式存储。

      (3).例如CIFAR-10数据集的目录结构如下所示:

      这里使用 https://blog.csdn.net/fengbingchun/article/details/141635132 中的数据集,通过YOLOv8 classify进行train和predict:

      train代码如下:

import argparse
import colorama
from ultralytics import YOLO
import torchdef parse_args():parser = argparse.ArgumentParser(description="YOLOv8 train")parser.add_argument("--yaml", required=True, type=str, help="yaml file or datasets path(classify)")parser.add_argument("--epochs", required=True, type=int, help="number of training")parser.add_argument("--task", required=True, type=str, choices=["detect", "segment", "classify"], help="specify what kind of task")parser.add_argument("--imgsz", type=int, default=640, help="input net image size")args = parser.parse_args()return argsdef train(task, yaml, epochs, imgsz):if task == "detect":model = YOLO("yolov8n.pt") # load a pretrained model, should be a *.pt PyTorch model to run this methodelif task == "segment":model = YOLO("yolov8n-seg.pt") # load a pretrained model, should be a *.pt PyTorch model to run this methodelif task == "classify":model = YOLO("yolov8n-cls.pt") # n/s/m/l/xelse:raise ValueError(colorama.Fore.RED + f"Error: unsupported task: {task}")# petience: Training stopped early as no improvement observed in last patience epochs, use patience=0 to disable EarlyStoppingresults = model.train(data=yaml, epochs=epochs, imgsz=imgsz, patience=150, augment=True) # train the model, supported parameter reference, for example: runs/segment(detect)/train3/args.yamlmetrics = model.val() # It'll automatically evaluate the data you trained, no arguments needed, dataset and settings rememberedif task == "classify":print("Top-1 Accuracy:", metrics.top1) # top1 accuracyprint("Top-5 Accuracy:", metrics.top5) # top5 accuracymodel.export(format="onnx", opset=12, simplify=True, dynamic=False, imgsz=imgsz) # onnx, export the model, cannot specify dynamic=True, opencv does not support# model.export(format="torchscript", imgsz=imgsz) # libtorch# model.export(format="engine", imgsz=imgsz, dynamic=False, verbose=False, batch=1, workspace=2) # tensorrt fp32# model.export(format="engine", imgsz=imgsz, dynamic=False, verbose=False, batch=1, workspace=2, half=True) # tensorrt fp16# model.export(format="engine", imgsz=imgsz, dynamic=False, verbose=False, batch=1, workspace=2, int8=True, data=yaml) # tensorrt int8# model.export(format="openvino", imgsz=imgsz) # openvino fp32# model.export(format="openvino", imgsz=imgsz, half=True) # openvino fp16# model.export(format="openvino", imgsz=imgsz, int8=True, data=yaml) # openvino int8, INT8 export requires 'data' arg for calibrationif __name__ == "__main__":# python test_yolov8_train.py --yaml datasets/melon_new_detect/melon_new_detect.yaml --epochs 1000 --task detect --imgsz 640colorama.init(autoreset=True)args = parse_args()print("Runging on GPU") if torch.cuda.is_available() else print("Runting on CPU")train(args.task, args.yaml, args.epochs, args.imgsz)print(colorama.Fore.GREEN + "====== execution completed ======")

      执行结果如下图所示:因数据集很小,训练速度很快

      predict代码如下:

import colorama
import argparse
from ultralytics import YOLO
import os
import torchimport numpy as np
np.bool = np.bool_ # Fix Error: AttributeError: module 'numpy' has no attribute 'bool'. OR: downgrade numpy: pip unistall numpy; pip install numpy==1.23.1def parse_args():parser = argparse.ArgumentParser(description="YOLOv8 predict")parser.add_argument("--model", required=True, type=str, help="model file")parser.add_argument("--task", required=True, type=str, choices=["detect", "segment", "classify"], help="specify what kind of task")parser.add_argument("--dir_images", required=True, type=str, help="directory of test images")parser.add_argument("--dir_result", type=str, default="", help="directory where the image results are saved")args = parser.parse_args()return argsdef get_images(dir):# supported image formatsimg_formats = (".bmp", ".jpeg", ".jpg", ".png", ".webp")images = []for file in os.listdir(dir):if os.path.isfile(os.path.join(dir, file)):# print(file)_, extension = os.path.splitext(file)for format in img_formats:if format == extension.lower():images.append(file)breakreturn imagesdef predict(model, task, dir_images, dir_result):model = YOLO(model) # load an model, support format: *.pt, *.onnx, *.torchscript, *.engine, openvino_model# model.info() # display model information # only *.pt format supportimages = get_images(dir_images)# print("images:", images)if task == "detect" or task =="segment":os.makedirs(dir_result) #, exist_ok=True)for image in images:device = "cuda" if torch.cuda.is_available() else "cpu"results = model.predict(dir_images+"/"+image, verbose=True, device=device)# print("results:", results)if task == "detect" or task =="segment":for result in results:result.save(dir_result+"/"+image)else:print(f"class names:{results[0].names}: top5: {results[0].probs.top5}; conf:{results[0].probs.top5conf}")if __name__ == "__main__":# python test_yolov8_predict.py --model runs/detect/train10/weights/best_int8.engine --dir_images datasets/melon_new_detect/images/test --dir_result result_detect_engine_int8 --task classifycolorama.init(autoreset=True)args = parse_args()print("Runging on GPU") if torch.cuda.is_available() else print("Runting on CPU")predict(args.model, args.task, args.dir_images, args.dir_result)print(colorama.Fore.GREEN + "====== execution completed ======")

      执行结果如下图所示:top1识别率100%

      GitHub:https://github.com/fengbingchun/NN_Test

这篇关于YOLOv8 classify介绍的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1139489

相关文章

Python中win32包的安装及常见用途介绍

《Python中win32包的安装及常见用途介绍》在Windows环境下,PythonWin32模块通常随Python安装包一起安装,:本文主要介绍Python中win32包的安装及常见用途的相关... 目录前言主要组件安装方法常见用途1. 操作Windows注册表2. 操作Windows服务3. 窗口操作

c++中的set容器介绍及操作大全

《c++中的set容器介绍及操作大全》:本文主要介绍c++中的set容器介绍及操作大全,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录​​一、核心特性​​️ ​​二、基本操作​​​​1. 初始化与赋值​​​​2. 增删查操作​​​​3. 遍历方

HTML img标签和超链接标签详细介绍

《HTMLimg标签和超链接标签详细介绍》:本文主要介绍了HTML中img标签的使用,包括src属性(指定图片路径)、相对/绝对路径区别、alt替代文本、title提示、宽高控制及边框设置等,详细内容请阅读本文,希望能对你有所帮助... 目录img 标签src 属性alt 属性title 属性width/h

MybatisPlus service接口功能介绍

《MybatisPlusservice接口功能介绍》:本文主要介绍MybatisPlusservice接口功能介绍,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友... 目录Service接口基本用法进阶用法总结:Lambda方法Service接口基本用法MyBATisP

MySQL复杂SQL之多表联查/子查询详细介绍(最新整理)

《MySQL复杂SQL之多表联查/子查询详细介绍(最新整理)》掌握多表联查(INNERJOIN,LEFTJOIN,RIGHTJOIN,FULLJOIN)和子查询(标量、列、行、表子查询、相关/非相关、... 目录第一部分:多表联查 (JOIN Operations)1. 连接的类型 (JOIN Types)

java中BigDecimal里面的subtract函数介绍及实现方法

《java中BigDecimal里面的subtract函数介绍及实现方法》在Java中实现减法操作需要根据数据类型选择不同方法,主要分为数值型减法和字符串减法两种场景,本文给大家介绍java中BigD... 目录Java中BigDecimal里面的subtract函数的意思?一、数值型减法(高精度计算)1.

Pytorch介绍与安装过程

《Pytorch介绍与安装过程》PyTorch因其直观的设计、卓越的灵活性以及强大的动态计算图功能,迅速在学术界和工业界获得了广泛认可,成为当前深度学习研究和开发的主流工具之一,本文给大家介绍Pyto... 目录1、Pytorch介绍1.1、核心理念1.2、核心组件与功能1.3、适用场景与优势总结1.4、优

Java实现本地缓存的常用方案介绍

《Java实现本地缓存的常用方案介绍》本地缓存的代表技术主要有HashMap,GuavaCache,Caffeine和Encahche,这篇文章主要来和大家聊聊java利用这些技术分别实现本地缓存的方... 目录本地缓存实现方式HashMapConcurrentHashMapGuava CacheCaffe

Spring Security介绍及配置实现代码

《SpringSecurity介绍及配置实现代码》SpringSecurity是一个功能强大的Java安全框架,它提供了全面的安全认证(Authentication)和授权(Authorizatio... 目录简介Spring Security配置配置实现代码简介Spring Security是一个功能强

JSR-107缓存规范介绍

《JSR-107缓存规范介绍》JSR是JavaSpecificationRequests的缩写,意思是Java规范提案,下面给大家介绍JSR-107缓存规范的相关知识,感兴趣的朋友一起看看吧... 目录1.什么是jsR-1072.应用调用缓存图示3.JSR-107规范使用4.Spring 缓存机制缓存是每一