first commit
This commit is contained in:
commit
6f7de660aa
299
.gitignore
vendored
Normal file
299
.gitignore
vendored
Normal file
@ -0,0 +1,299 @@
|
||||
### Python template
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
### IntelliJ IDEA ###
|
||||
.idea/
|
||||
*.iws
|
||||
*.iml
|
||||
*.ipr
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# spec
|
||||
manage.spec
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
staticfiles/
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
|
||||
|
||||
# Environments
|
||||
.venv
|
||||
venv/
|
||||
ENV/
|
||||
.vscode
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
|
||||
|
||||
### Node template
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
|
||||
# Runtime data
|
||||
pids
|
||||
*.pid
|
||||
*.seed
|
||||
*.pid.lock
|
||||
|
||||
# Directory for instrumented libs generated by jscoverage/JSCover
|
||||
lib-cov
|
||||
|
||||
# Coverage directory used by tools like istanbul
|
||||
coverage
|
||||
|
||||
# nyc test coverage
|
||||
.nyc_output
|
||||
|
||||
# Bower dependency directory (https://bower.io/)
|
||||
bower_components
|
||||
|
||||
# node-waf configuration
|
||||
.lock-wscript
|
||||
|
||||
# Compiled binary addons (http://nodejs.org/api/addons.html)
|
||||
build/Release
|
||||
|
||||
# Dependency directories
|
||||
node_modules/
|
||||
jspm_packages/
|
||||
|
||||
# Typescript v1 declaration files
|
||||
typings/
|
||||
|
||||
# Optional npm cache directory
|
||||
.npm
|
||||
|
||||
# Optional eslint cache
|
||||
.eslintcache
|
||||
|
||||
# Optional REPL history
|
||||
.node_repl_history
|
||||
|
||||
# Output of 'npm pack'
|
||||
*.tgz
|
||||
|
||||
# Yarn Integrity file
|
||||
.yarn-integrity
|
||||
|
||||
|
||||
### Linux template
|
||||
*~
|
||||
|
||||
# temporary files which can be created if a process still has a handle open of a deleted file
|
||||
.fuse_hidden*
|
||||
|
||||
# KDE directory preferences
|
||||
.directory
|
||||
|
||||
# Linux trash folder which might appear on any partition or disk
|
||||
.Trash-*
|
||||
|
||||
# .nfs files are created when an open file is removed but is still being accessed
|
||||
.nfs*
|
||||
|
||||
|
||||
### VisualStudioCode template
|
||||
.vscode/*
|
||||
!.vscode/settings.json
|
||||
!.vscode/tasks.json
|
||||
!.vscode/launch.json
|
||||
!.vscode/extensions.json
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
### Windows template
|
||||
# Windows thumbnail cache files
|
||||
Thumbs.db
|
||||
ehthumbs.db
|
||||
ehthumbs_vista.db
|
||||
|
||||
# Dump file
|
||||
*.stackdump
|
||||
|
||||
# Folder config file
|
||||
Desktop.ini
|
||||
|
||||
# Recycle Bin used on file shares
|
||||
$RECYCLE.BIN/
|
||||
|
||||
# Windows Installer files
|
||||
*.cab
|
||||
*.msi
|
||||
*.msm
|
||||
*.msp
|
||||
|
||||
# Windows shortcuts
|
||||
*.lnk
|
||||
|
||||
|
||||
### macOS template
|
||||
# General
|
||||
*.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
|
||||
### SublimeText template
|
||||
# Cache files for Sublime Text
|
||||
*.tmlanguage.cache
|
||||
*.tmPreferences.cache
|
||||
*.stTheme.cache
|
||||
|
||||
# Workspace files are user-specific
|
||||
*.sublime-workspace
|
||||
|
||||
# Project files should be checked into the repository, unless a significant
|
||||
# proportion of contributors will probably not be using Sublime Text
|
||||
# *.sublime-project
|
||||
|
||||
# SFTP configuration file
|
||||
sftp-config.json
|
||||
|
||||
# Package control specific files
|
||||
Package Control.last-run
|
||||
Package Control.ca-list
|
||||
Package Control.ca-bundle
|
||||
Package Control.system-ca-bundle
|
||||
Package Control.cache/
|
||||
Package Control.ca-certs/
|
||||
Package Control.merged-ca-bundle
|
||||
Package Control.user-ca-bundle
|
||||
oscrypto-ca-bundle.crt
|
||||
bh_unicode_properties.cache
|
||||
|
||||
# Sublime-github package stores a github token in this file
|
||||
# https://packagecontrol.io/packages/sublime-github
|
||||
GitHub.sublime-settings
|
||||
|
||||
|
||||
### Vim template
|
||||
# Swap
|
||||
[._]*.s[a-v][a-z]
|
||||
[._]*.sw[a-p]
|
||||
[._]s[a-v][a-z]
|
||||
[._]sw[a-p]
|
||||
|
||||
# Session
|
||||
Session.vim
|
||||
|
||||
# Temporary
|
||||
.netrwhist
|
||||
|
||||
# Auto-generated tag files
|
||||
tags
|
||||
|
||||
|
||||
### VirtualEnv template
|
||||
# Virtualenv
|
||||
[Bb]in
|
||||
[Ii]nclude
|
||||
[Ll]ib
|
||||
[Ll]ib64
|
||||
[Ss]cripts
|
||||
pyvenv.cfg
|
||||
pip-selfcheck.json
|
||||
.env
|
||||
|
||||
|
||||
### Project template
|
||||
|
||||
izan/media/
|
||||
|
||||
.pytest_cache/
|
||||
|
||||
*.pt
|
||||
*.pdparams
|
||||
|
||||
|
BIN
SetParams.zip
Normal file
BIN
SetParams.zip
Normal file
Binary file not shown.
144
SetParams/DataType/BaseParam.py
Normal file
144
SetParams/DataType/BaseParam.py
Normal file
@ -0,0 +1,144 @@
|
||||
import json
|
||||
from .TypeDef import *
|
||||
from typing import Union
|
||||
from abc import abstractmethod
|
||||
|
||||
|
||||
class BaseParam:
|
||||
"""
|
||||
参数基类
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
"""
|
||||
参数基类,算法中所有需要参数的方法中,使用的参数必须继承该类型
|
||||
"""
|
||||
self.file = ''
|
||||
self.param_list = []
|
||||
|
||||
def save_to_file(self, file: str) -> None:
|
||||
"""
|
||||
将参数保存到文件
|
||||
:param file: 文件完整路径
|
||||
:return: None
|
||||
"""
|
||||
with open(file, 'w') as f:
|
||||
f.write(str(self))
|
||||
f.flush()
|
||||
|
||||
def add_param(self, p: Union[IntType, BoolType, FloatType, StringType, ListType, EnumType]) -> None:
|
||||
"""
|
||||
将数据添加到参数列表中,以支持序列化
|
||||
:param p: 单个数据,必须为系统支持的参数类型之一:IntType, BoolType, FloatType, StringType, ListType, EnumType
|
||||
:return: None
|
||||
"""
|
||||
self.param_list.append(p)
|
||||
|
||||
def read_from_str(self, content: str) -> None:
|
||||
"""
|
||||
将字符串反序列化为对象中的参数
|
||||
:param content: 要反序列化的字符串
|
||||
:return: None
|
||||
"""
|
||||
self.param_list.clear()
|
||||
objs = json.loads(content)
|
||||
for obj in objs:
|
||||
#try:
|
||||
item = obj #json.loads(obj)
|
||||
t = item["type"]
|
||||
param = None
|
||||
|
||||
if t == "B":
|
||||
param = BoolType(item["name"],
|
||||
item["value"],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
elif t == "I":
|
||||
param = IntType(item["name"],
|
||||
item["value"],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
elif t == "F":
|
||||
param = FloatType(item["name"],
|
||||
item["value"],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
#param.length = item["length"]
|
||||
elif t == "S":
|
||||
item['length']=len(item["value"])
|
||||
param = StringType(item["name"],
|
||||
item["value"],
|
||||
item['length'],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
elif t == "L":
|
||||
param = ListType(item["name"],
|
||||
item["value"],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
#param.length = item["length"]
|
||||
elif t == "E":
|
||||
param = EnumType(item["name"],
|
||||
item["value"],
|
||||
item["items"],
|
||||
item["description"],
|
||||
item["default"],
|
||||
item["show"])
|
||||
param.index = item["index"]
|
||||
|
||||
if param:
|
||||
self.param_list.append(param)
|
||||
# except Exception as e:
|
||||
# pass
|
||||
|
||||
def read_from_file(self, file: str) -> None:
|
||||
"""
|
||||
从文件读取序列化后的参数字符串,并反序列化为对象
|
||||
:param file: 文件完整路径
|
||||
:return: None
|
||||
"""
|
||||
with open(file, 'r') as f:
|
||||
content = f.read()
|
||||
self.read_from_str(content)
|
||||
|
||||
@property
|
||||
def param_string(self) -> str:
|
||||
"""
|
||||
获取Json格式的参数字符串
|
||||
:return: 返回Json格式的参数字符串
|
||||
"""
|
||||
for i, p in enumerate(self.param_list):
|
||||
p.index = i
|
||||
return self.__str__()
|
||||
|
||||
def __str__(self) -> str:
|
||||
"""
|
||||
重写str方法用于将对象序列化为Json字符串
|
||||
:return: 序列化后的JSON字符串
|
||||
"""
|
||||
ret = []
|
||||
for index, item in enumerate(self.param_list):
|
||||
obj = item.obj
|
||||
if isinstance(obj, dict):
|
||||
obj["index"] = index
|
||||
item_obj = json.dumps(obj)
|
||||
ret.append(item_obj)
|
||||
return json.dumps(ret)
|
||||
|
||||
def get(self, name: str) -> Union[None, IntType, BoolType, FloatType, StringType, ListType, EnumType,]:
|
||||
"""
|
||||
根据数据名称获取指定的数据对象
|
||||
:param name: 数据名称
|
||||
:return:
|
||||
"""
|
||||
return next((x for x in self.param_list if x.name == name), None)
|
21
SetParams/DataType/ParamDef.py
Normal file
21
SetParams/DataType/ParamDef.py
Normal file
@ -0,0 +1,21 @@
|
||||
from .TypeDef import *
|
||||
from .BaseParam import *
|
||||
|
||||
|
||||
class TrainParams(BaseParam):
|
||||
"""
|
||||
训练参数示例,使用时需要根据实际情况修改,如有其他参数(如推理函数的参数)需要自定义,并继承自 BaseParam
|
||||
"""
|
||||
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
|
||||
# 例如训练的时候需要传入以下参数
|
||||
gpu_num = IntType("gpu_num", 2)
|
||||
support_cpu = BoolType("support_cpu", True)
|
||||
labels = EnumType("labels", 0, ["dog", "cat"])
|
||||
labels.default = 0
|
||||
|
||||
self.add_param(gpu_num)
|
||||
self.add_param(support_cpu)
|
||||
self.add_param(labels)
|
243
SetParams/DataType/TypeDef.py
Normal file
243
SetParams/DataType/TypeDef.py
Normal file
@ -0,0 +1,243 @@
|
||||
import json
|
||||
from typing import List
|
||||
from abc import abstractmethod
|
||||
|
||||
|
||||
class __BaseType:
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: object,
|
||||
description: str,
|
||||
default: object,
|
||||
show: bool):
|
||||
"""
|
||||
所有数据类型的基类
|
||||
:param name: 数据名称
|
||||
:param value: 数据值
|
||||
:param description: 描述,用于前端UI展示
|
||||
:param default: 该参数的默认值
|
||||
"""
|
||||
self.name = name
|
||||
self.description = description
|
||||
self.index = -1
|
||||
self.default = default
|
||||
self.value = value
|
||||
self.show = show
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def type(self) -> str:
|
||||
"""
|
||||
参数类型,用于前端/后台的序列化与反序列化。前端展示时也需要根据此字段类型绘制不同的控件
|
||||
:return: 一般使用单个字母,如:整型(I),布尔型(B),浮点型(F),字符串(S),列表(L),枚举(E)
|
||||
"""
|
||||
pass
|
||||
|
||||
@property
|
||||
def _base_obj(self) -> dict:
|
||||
"""
|
||||
用于创建所有数据类型的共有对象字典
|
||||
:return:
|
||||
"""
|
||||
return {
|
||||
"index": self.index,
|
||||
"name": self.name,
|
||||
"value": self.value,
|
||||
"description": self.description,
|
||||
"default": self.default,
|
||||
"type": self.type,
|
||||
"show": self.show
|
||||
}
|
||||
|
||||
@property
|
||||
@abstractmethod
|
||||
def obj(self) -> dict:
|
||||
"""
|
||||
抽象属性,获取数据类型的对象字典
|
||||
:return:
|
||||
"""
|
||||
return self._base_obj
|
||||
|
||||
def __str__(self):
|
||||
"""
|
||||
重写数据类型的字符串序列化方法
|
||||
:return:
|
||||
"""
|
||||
return json.dumps(self.obj)
|
||||
|
||||
|
||||
class BoolType(__BaseType):
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: bool = False,
|
||||
description: str = "",
|
||||
default: bool = False,
|
||||
show: bool = True):
|
||||
"""
|
||||
布尔类型数据
|
||||
:param name: 数据名称
|
||||
:param value: 数据值
|
||||
:param description: 描述,用于前端UI展示
|
||||
:param default: 该参数的默认值
|
||||
"""
|
||||
super().__init__(name, value, description, default, show)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return 'B'
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
return super()._base_obj
|
||||
|
||||
|
||||
class IntType(__BaseType):
|
||||
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: int = 0,
|
||||
description: str = "",
|
||||
default: int = 0,
|
||||
show: bool = True):
|
||||
"""
|
||||
整数类型
|
||||
:param name: 数据名称
|
||||
:param value: 数据值
|
||||
:param description: 描述,用于前端UI展示
|
||||
:param default: 该参数的默认值
|
||||
"""
|
||||
super().__init__(name, value, description, default, show)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return 'I'
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
return super()._base_obj
|
||||
|
||||
|
||||
class FloatType(__BaseType):
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: float = 0.,
|
||||
description: str = "",
|
||||
default: float = 0.,
|
||||
show: bool = True):
|
||||
"""
|
||||
浮点类型
|
||||
:param name: 数据名称
|
||||
:param value: 数据值
|
||||
:param description: 描述,用于前端UI展示
|
||||
:param default: 该参数的默认值
|
||||
"""
|
||||
super().__init__(name, value, description, default, show)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return 'F'
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
return super()._base_obj
|
||||
|
||||
|
||||
class StringType(__BaseType):
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: str = "",
|
||||
length: int = -1,
|
||||
description: str = "",
|
||||
default: str = "",
|
||||
show: bool = True):
|
||||
"""
|
||||
字符串类型
|
||||
:param name: 数据名称,用于程序内部标识该数据
|
||||
:param value: 数据值
|
||||
:param length: 字符串长度
|
||||
:param description: 描述,用于前端页面对该数据进行展示
|
||||
:param default: 默认值
|
||||
"""
|
||||
super().__init__(name, value, description, default, show)
|
||||
self.length = length
|
||||
if length > 0:
|
||||
self.value = value[:length]
|
||||
else:
|
||||
self.value = value
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return 'S'
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
base_obj = super()._base_obj
|
||||
base_obj["length"] = self.length
|
||||
return base_obj
|
||||
|
||||
|
||||
class ListType(__BaseType):
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: list = None,
|
||||
description: str = "",
|
||||
default: list = None,
|
||||
show: bool = True):
|
||||
"""
|
||||
列表类型
|
||||
:param name: 数据名称,用于程序内部标识该数据
|
||||
:param value: 数据值
|
||||
:param description: 描述,用于前端页面对该数据进行展示
|
||||
:param default: 默认值
|
||||
"""
|
||||
if not default:
|
||||
default = []
|
||||
|
||||
if not value:
|
||||
value = default
|
||||
|
||||
self.length = len(value)
|
||||
super().__init__(name, value, description, default, show)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return "L"
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
base_obj = super()._base_obj
|
||||
base_obj["length"] = self.length
|
||||
return base_obj
|
||||
|
||||
|
||||
class EnumType(__BaseType):
|
||||
def __init__(self,
|
||||
name: str,
|
||||
value: int = -1,
|
||||
items: List[str] = None,
|
||||
description: str = "",
|
||||
default: int = -1,
|
||||
show: bool = True):
|
||||
"""
|
||||
枚举类型
|
||||
:param name: 数据名称,用于程序内部标识该数据
|
||||
:param value: 数据值,即选择了枚举列表中的第几项
|
||||
:param items: 枚举范围,枚举项必须为字符串类型
|
||||
:param description: 描述,用于前端页面对该数据进行展示
|
||||
:param default: 默认值
|
||||
"""
|
||||
if not items:
|
||||
items = []
|
||||
default = -1
|
||||
self.items = items
|
||||
super().__init__(name, value, description, default, show)
|
||||
|
||||
@property
|
||||
def type(self) -> str:
|
||||
return "E"
|
||||
|
||||
@property
|
||||
def obj(self) -> dict:
|
||||
base_obj = super()._base_obj
|
||||
base_obj["items"] = self.items
|
||||
return base_obj
|
0
SetParams/DataType/__init__.py
Normal file
0
SetParams/DataType/__init__.py
Normal file
1
SetParams/TrainParams-0.json
Normal file
1
SetParams/TrainParams-0.json
Normal file
@ -0,0 +1 @@
|
||||
["{\"index\": 0, \"name\": \"gpu_num\", \"value\": 2, \"description\": \"\", \"default\": 0, \"type\": \"I\"}", "{\"index\": 1, \"name\": \"support_cpu\", \"value\": true, \"description\": \"\", \"default\": false, \"type\": \"B\"}", "{\"index\": 2, \"name\": \"labels\", \"value\": 0, \"description\": \"\", \"default\": 0, \"type\": \"E\", \"items\": [\"dog\", \"cat\"]}"]
|
1
SetParams/TrainParams.json
Normal file
1
SetParams/TrainParams.json
Normal file
@ -0,0 +1 @@
|
||||
["{\"index\": 0, \"name\": \"num_classes\", \"value\": 0, \"description\": \"\", \"default\": 9, \"type\": \"I\"}", "{\"index\": 1, \"name\": \"lr\", \"value\": 0.0, \"description\": \"\", \"default\": 0.005, \"type\": \"F\"}", "{\"index\": 2, \"name\": \"lr_schedulerList\", \"value\": [30, 60], \"description\": \"\", \"default\": [30, 60], \"type\": \"L\", \"length\": 2}", "{\"index\": 3, \"name\": \"device\", \"value\": \"\", \"description\": \"\", \"default\": \"cpu\", \"type\": \"S\", \"length\": -1}", "{\"index\": 4, \"name\": \"DatasetDir\", \"value\": \"\", \"description\": \"\", \"default\": \"./datasets/M006B_duanmian\", \"type\": \"S\", \"length\": -1}", "{\"index\": 5, \"name\": \"saveModDir\", \"value\": \"\", \"description\": \"\", \"default\": \"./saved_model/M006B_duanmian.pt\", \"type\": \"S\", \"length\": -1}", "{\"index\": 6, \"name\": \"resumeModPath\", \"value\": \"\", \"description\": \"\", \"default\": \"\", \"type\": \"S\", \"length\": -1}", "{\"index\": 7, \"name\": \"epochnum\", \"value\": 0, \"description\": \"\", \"default\": 100, \"type\": \"I\"}", "{\"index\": 8, \"name\": \"saveEpoch\", \"value\": 0, \"description\": \"\", \"default\": 1, \"type\": \"I\"}"]
|
0
SetParams/__init__.py
Normal file
0
SetParams/__init__.py
Normal file
49
SetParams/main.py
Normal file
49
SetParams/main.py
Normal file
@ -0,0 +1,49 @@
|
||||
from DataType.TypeDef import *
|
||||
from DataType.ParamDef import *
|
||||
|
||||
|
||||
def train(params: TrainParams):
|
||||
"""
|
||||
后台提交训练请求时,可以参考此方法,从前端传递的参数中取出需要的值
|
||||
:param params:
|
||||
:return:
|
||||
"""
|
||||
# 存在的参数可以使用name字段获取到
|
||||
cpu_num = params.get("gpu_num")
|
||||
print(cpu_num)
|
||||
|
||||
# 不存在的参数获取的时候返回None
|
||||
th = params.get("th")
|
||||
print(th)
|
||||
|
||||
|
||||
def get_train_config_json():
|
||||
"""
|
||||
前端获取训练所需要的参数JSON字符串时,使用str方法即可获取JSON字符串
|
||||
:return:
|
||||
"""
|
||||
# 第一种方法:
|
||||
# 创建新对象
|
||||
params = TrainParams()
|
||||
# 从指定文件名中读取配置
|
||||
params.read_from_file("TrainParams.json")
|
||||
# 转为字符串
|
||||
print(str(params))
|
||||
|
||||
# 第二种方法
|
||||
# 也可以直接将文本传递给前端,但是可能需要考虑转义符号(\)的处理
|
||||
with open("TrainParams.json", "r") as f:
|
||||
print(f.read())
|
||||
|
||||
return params
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 当前端需要获取参数列表时,参照此函数中的实现
|
||||
get_train_config_json()
|
||||
|
||||
# 当前端传递回来参数的JSON字符串时,使用下述方法,将字符串反序列化为对象,然后传递给对应的函数
|
||||
params = TrainParams()
|
||||
params.read_from_str(
|
||||
'["{\\"index\\": 0, \\"name\\": \\"gpu_num\\", \\"value\\": 2, \\"description\\": \\"\\", \\"default\\": 0, \\"type\\": \\"I\\"}", "{\\"index\\": 1, \\"name\\": \\"support_cpu\\", \\"value\\": true, \\"description\\": \\"\\", \\"default\\": false, \\"type\\": \\"B\\"}", "{\\"index\\": 2, \\"name\\": \\"labels\\", \\"value\\": 0, \\"description\\": \\"\\", \\"default\\": 0, \\"type\\": \\"E\\", \\"items\\": [\\"dog\\", \\"cat\\"]}"]')
|
||||
train(params)
|
65
SetParams_Demo.py
Normal file
65
SetParams_Demo.py
Normal file
@ -0,0 +1,65 @@
|
||||
import sys
|
||||
import json
|
||||
from setparams import TrainParams
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
def ppx_train(params,id):
|
||||
|
||||
ppx_num_classes = params.get('num_classes').value
|
||||
ppx_epoch = params.get('epochnum').value
|
||||
ppx_saveEpoch = params.get('saveEpoch').value
|
||||
ppx_device = params.get('device').value
|
||||
ppx_DatasetDir = params.get('DatasetDir').value
|
||||
ppx_saveModDir = params.get('saveModDir').value
|
||||
ppx_lr = params.get('lr').value
|
||||
ppx_lr_schedulerList = params.get('lr_schedulerList').value
|
||||
ppx_resumeModPath = params.get('resumeModPath').value
|
||||
ppx_id = id
|
||||
if ppx_resumeModPath == '': ppx_resumeModPath= "/mnt/sdc/algorithm/AICheck-MaskRCNN/app/maskrcnn_ppx/pretrain/mask_rcnn_r50_fpn_2x_coco.pdparams" #'COCO'
|
||||
|
||||
|
||||
|
||||
model.train(
|
||||
num_epochs=ppx_epoch, #***
|
||||
save_interval_epochs=ppx_saveEpoch, #***
|
||||
train_dataset=train_dataset, #***
|
||||
train_batch_size=2,
|
||||
eval_dataset=eval_dataset, #***
|
||||
pretrain_weights=ppx_resumeModPath, #***
|
||||
learning_rate=ppx_lr, #***
|
||||
lr_decay_epochs=ppx_lr_schedulerList, #***
|
||||
warmup_steps=10,
|
||||
warmup_start_lr=0.0,
|
||||
save_dir=ppx_saveModDir, #***
|
||||
use_vdl=True)
|
||||
|
||||
|
||||
|
||||
|
||||
#@start_train_algorithm
|
||||
def main(params_str):
|
||||
params = TrainParams()
|
||||
params.read_from_str(params_str)
|
||||
ppx_train(params,id='1')
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
params_list = [
|
||||
{"index":0,"name":"num_classes","value":9,"description":'类别数(加背景)',"default":9,"type":"I", "show":True},
|
||||
{"index":1,"name":"lr","value":0.0003,"description":'学习率',"default":0.0001,"type":"F", "show":True},
|
||||
{"index":2,"name":"lr_schedulerList","value":[30,60],"description":'学习率衰减轮次',"default":[30,60],"type":"L", "show":True},
|
||||
{"index":3,"name":"device","value":"cpu","description":'训练核心',"default":"cpu","type":"S", "show":True},
|
||||
{"index":4,"name":"DatasetDir","value":"/mnt/sdc/algorithm/PaddleX/datasets/DDX_nb","description":'数据集路径',"default":"/mnt/sdc/algorithm/PaddleX/datasets/DDX_nb","type":"S", "show":False},
|
||||
{"index":5,"name":"saveModDir","value":"/mnt/sdc/algorithm/PaddleX/output","description":'保存模型路径',"default":"/mnt/sdc/algorithm/PaddleX/output","type":"S", "show":False},
|
||||
{"index":6,"name":"resumeModPath","value":'',"description":'继续训练路径',"default":'',"type":"S", "show":False},
|
||||
{"index":7,"name":"epochnum","value":100,"description":'训练轮次',"default":100,"type":"I", "show":True},
|
||||
{"index":8,"name":"saveEpoch","value":2,"description":'保存模型轮次',"default":2,"type":"I", "show":True}]
|
||||
params_str = json.dumps(params_list)
|
||||
print(params_str)
|
||||
|
||||
main(params_str)
|
0
__init__.py
Normal file
0
__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/__init__.py
Normal file
0
app/configs/__init__.py
Normal file
0
app/configs/__init__.py
Normal file
29
app/configs/default.py
Normal file
29
app/configs/default.py
Normal file
@ -0,0 +1,29 @@
|
||||
import os
|
||||
|
||||
# 根目录
|
||||
ROOT_PATH = os.path.split(os.path.abspath(__name__))[0]
|
||||
# 开启debug
|
||||
DEBUG = True
|
||||
# 密钥
|
||||
SECRET_KEY = 'WugjsfiYBEVsiQfiSwEbIOEAGnOIFYqoOYHEIK'
|
||||
|
||||
# 数据库配置
|
||||
# SQLALCHEMY_DATABASE_URI = 'postgresql+psycopg2://deepLearner:dp2021@124.71.203.3:5432/demo'
|
||||
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://demo:demo123@192.168.2.9:3306/flask_demo'
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
# 查询时会显示原始SQL语句
|
||||
SQLALCHEMY_ECHO = True
|
||||
|
||||
# SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(os.path.join(ROOT_PATH, 'demo.db'))
|
||||
# SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
|
||||
# 数据库配置
|
||||
db = {
|
||||
'host': '127.0.0.1',
|
||||
'user': 'root',
|
||||
'password': '',
|
||||
'port': 6379,
|
||||
'database': 'school',
|
||||
'charset': 'utf8',
|
||||
'db': 0
|
||||
}
|
8
app/configs/development.py
Normal file
8
app/configs/development.py
Normal file
@ -0,0 +1,8 @@
|
||||
from .default import * # NOQA F401
|
||||
|
||||
# 数据库配置
|
||||
SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://demo:demo123@192.168.2.9:3306/flask_demo'
|
||||
# SQLALCHEMY_DATABASE_URI = 'mysql+pymysql://demo:demo123@192.168.2.9:3306/flask_demo?allowPublicKeyRetrieval=true&useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=Asia/Shanghai'
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
# 查询时会显示原始SQL语句
|
||||
SQLALCHEMY_ECHO = True
|
3
app/configs/production.py
Normal file
3
app/configs/production.py
Normal file
@ -0,0 +1,3 @@
|
||||
from .default import * # NOQA F401
|
||||
|
||||
DEBUG = False
|
14
app/configs/testing.py
Normal file
14
app/configs/testing.py
Normal file
@ -0,0 +1,14 @@
|
||||
import os
|
||||
|
||||
from .default import ROOT_PATH
|
||||
from .default import * # NOQA F401
|
||||
|
||||
|
||||
TEST_BASE_DIR = os.path.join(ROOT_PATH, '.test')
|
||||
SQLALCHEMY_DATABASE_URI = 'sqlite:///{}'.format(
|
||||
os.path.join(TEST_BASE_DIR, 'demo.db'))
|
||||
# SQLALCHEMY_ECHO = True
|
||||
TESTING = True
|
||||
|
||||
if not os.path.exists(TEST_BASE_DIR):
|
||||
os.makedirs(TEST_BASE_DIR)
|
412
app/controller/AlgorithmController.py
Normal file
412
app/controller/AlgorithmController.py
Normal file
@ -0,0 +1,412 @@
|
||||
"""
|
||||
@Time : 2022/9/20 16:17
|
||||
@Auth : 东
|
||||
@File :AlgorithmController.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:算法接口
|
||||
|
||||
"""
|
||||
import json
|
||||
from functools import wraps
|
||||
from threading import Thread
|
||||
|
||||
from flask import Blueprint, request
|
||||
|
||||
from app.schemas.TrainResult import Report, ProcessValueList
|
||||
from app.utils.RedisMQTool import Task
|
||||
from app.utils.StandardizedOutput import output_wrapped
|
||||
from app.utils.redis_config import redis_client
|
||||
from app.utils.websocket_tool import manager
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
# from pynvml import *
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[0] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
# sys.path.append("/mnt/sdc/algorithm/AICheck-MaskRCNN/app/maskrcnn_ppx")
|
||||
# import ppx as pdx
|
||||
|
||||
bp = Blueprint('AlgorithmController', __name__)
|
||||
|
||||
|
||||
def start_train_algorithm():
|
||||
"""
|
||||
调用训练算法
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/start_train_algorithm', methods=['get'])
|
||||
def wrapped_function():
|
||||
param = request.args.get('param')
|
||||
id = request.args.get('id')
|
||||
t = Thread(target=func, args=(param, id))
|
||||
t.start()
|
||||
return output_wrapped(0, 'success', '成功')
|
||||
|
||||
return wrapped_function
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def start_test_algorithm():
|
||||
"""
|
||||
调用验证算法
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/start_test_algorithm', methods=['get'])
|
||||
def wrapped_function_test():
|
||||
param = request.args.get('param')
|
||||
id = request.args.get('id')
|
||||
t = Thread(target=func, args=(param, id))
|
||||
t.start()
|
||||
return output_wrapped(0, 'success', '成功')
|
||||
|
||||
return wrapped_function_test
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def start_detect_algorithm():
|
||||
"""
|
||||
调用检测算法
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/start_detect_algorithm', methods=['get'])
|
||||
def wrapped_function_detect():
|
||||
param = request.args.get('param')
|
||||
id = request.args.get('id')
|
||||
t = Thread(target=func, args=(param, id))
|
||||
t.start()
|
||||
return output_wrapped(0, 'success', '成功')
|
||||
|
||||
return wrapped_function_detect
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def start_download_pt():
|
||||
"""
|
||||
下载模型
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/start_download_pt', methods=['get'])
|
||||
def wrapped_function_start_download_pt():
|
||||
param = request.args.get('param')
|
||||
func(param)
|
||||
return output_wrapped(0, 'success', '成功')
|
||||
|
||||
return wrapped_function_start_download_pt
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def algorithm_process_value():
|
||||
"""
|
||||
获取中间值, redis订阅发布
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
def wrapped_function(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
print(data)
|
||||
Task(redis_conn=redis_client.get_redis(), channel="ceshi").publish_task(
|
||||
data={'code': 0, 'msg': 'success', 'data': data})
|
||||
return output_wrapped(0, 'success', data)
|
||||
|
||||
return wrapped_function
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def algorithm_process_value_websocket():
|
||||
"""
|
||||
获取中间值, websocket发布
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
def wrapped_function(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
id = data["id"]
|
||||
data_res = {'code': 0, "type": 'connected', 'msg': 'success', 'data': data}
|
||||
manager.send_message_proj_json(message=data_res, id=id)
|
||||
return data
|
||||
|
||||
return wrapped_function
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def obtain_train_param():
|
||||
"""
|
||||
获取训练参数
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/obtain_train_param', methods=['get'])
|
||||
def wrapped_function_train_param(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
return output_wrapped(0, 'success', data)
|
||||
|
||||
return wrapped_function_train_param
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def obtain_test_param():
|
||||
"""
|
||||
获取验证参数
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/obtain_test_param', methods=['get'])
|
||||
def wrapped_function_test_param(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
return output_wrapped(0, 'success', data)
|
||||
|
||||
return wrapped_function_test_param
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def obtain_detect_param():
|
||||
"""
|
||||
获取测试参数
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/obtain_detect_param', methods=['get'])
|
||||
def wrapped_function_inf_param(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
return output_wrapped(0, 'success', data)
|
||||
|
||||
return wrapped_function_inf_param
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
def obtain_download_pt_param():
|
||||
"""
|
||||
获取下载模型参数
|
||||
"""
|
||||
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
@bp.route('/obtain_download_pt_param', methods=['get'])
|
||||
def wrapped_function_obtain_download_pt_param(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
return output_wrapped(0, 'success', data)
|
||||
|
||||
return wrapped_function_obtain_download_pt_param
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
# @start_train_algorithm()
|
||||
# def start(param: str):
|
||||
# """
|
||||
# 例子
|
||||
# """
|
||||
# print(param)
|
||||
# process_value_list = ProcessValueList(name='1', value=[])
|
||||
# report = Report(rate_of_progess=0, process_value=[process_value_list], id='1')
|
||||
#
|
||||
# @algorithm_process_value_websocket()
|
||||
# def process(v: int):
|
||||
# print(v)
|
||||
# report.rate_of_progess = ((v + 1) / 10) * 100
|
||||
# report.precision[0].value.append(v)
|
||||
# return report.dict()
|
||||
#
|
||||
# for i in range(10):
|
||||
# process(i)
|
||||
# return report.dict()
|
||||
from setparams import TrainParams
|
||||
import os
|
||||
from app.schemas.TrainResult import DetectProcessValueDice, DetectReport
|
||||
from app import file_tool
|
||||
|
||||
|
||||
# 启动训练
|
||||
@start_train_algorithm()
|
||||
def train_R0DY(params_str, id):
|
||||
from app.yolov5.train_server import train_start
|
||||
params = TrainParams()
|
||||
params.read_from_str(params_str)
|
||||
print(params.get('device').default)
|
||||
data_list = file_tool.get_file(ori_path=params.get('DatasetDir').value, type_list=params.get('classname').value)
|
||||
weights = params.get('resumeModPath').value # 初始化模型绝对路径
|
||||
img_size = params.get('img_size').value
|
||||
savemodel = os.path.splitext(params.get('saveModDir').value)[0] + '_' + img_size + '.pt' # 模型命名加上图像参数
|
||||
epoches = params.get('epochnum').value
|
||||
batch_size = params.get('batch_size').value
|
||||
device = params.get('device').value
|
||||
|
||||
train_start(weights, savemodel, epoches, img_size, batch_size, device, data_list, id)
|
||||
|
||||
|
||||
# 启动验证程序
|
||||
|
||||
@start_test_algorithm()
|
||||
def validate_RODY(params_str, id):
|
||||
from app.yolov5.validate_server import validate_start
|
||||
params = TrainParams()
|
||||
params.read_from_str(params_str)
|
||||
weights = params.get('modPath').value # 验证模型绝对路径
|
||||
(filename, extension) = os.path.splitext(weights) # 文件名与后缀名分开
|
||||
img_size = int(filename.split('ROD')[1].split('_')[2]) # 获取图像参数
|
||||
# v_num = int(filename.split('ROD')[1].split('_')[1]) #获取版本号
|
||||
output = params.get('outputPath').value
|
||||
batch_size = params.get('batch_size').default
|
||||
device = params.get('device').value
|
||||
|
||||
validate_start(weights, img_size, batch_size, device, output, id)
|
||||
|
||||
|
||||
@start_detect_algorithm()
|
||||
def detect_RODY(params_str, id):
|
||||
from app.yolov5.detect_server import detect_start
|
||||
params = TrainParams()
|
||||
params.read_from_str(params_str)
|
||||
weights = params.get('modPath').value # 检测模型绝对路径
|
||||
input = params.get('inputPath').value
|
||||
outpath = params.get('outputPath').value
|
||||
# (filename, extension) = os.path.splitext(weights) # 文件名与后缀名分开
|
||||
# img_size = int(filename.split('ROD')[1].split('_')[2]) #获取图像参数
|
||||
# v_num = int(filename.split('ROD')[1].split('_')[1]) #获取版本号
|
||||
# batch_size = params.get('batch_size').default
|
||||
device = params.get('device').value
|
||||
|
||||
detect_start(input, weights, outpath, device, id)
|
||||
|
||||
|
||||
@start_download_pt()
|
||||
def Export_model_RODY(params_str):
|
||||
from app.yolov5.export import Start_Model_Export
|
||||
import zipfile
|
||||
params = TrainParams()
|
||||
params.read_from_str(params_str)
|
||||
exp_inputPath = params.get('exp_inputPath').value # 模型路径
|
||||
exp_device = params.get('device').value
|
||||
modellist = Start_Model_Export(exp_inputPath, exp_device)
|
||||
exp_outputPath = exp_inputPath.replace('pt', 'zip') # 压缩文件
|
||||
zipf = zipfile.ZipFile(exp_outputPath, 'w')
|
||||
for file in modellist:
|
||||
zipf.write(file, arcname=Path(file).name) # 将torchscript和onnx模型压缩
|
||||
|
||||
return exp_outputPath
|
||||
# zipf.write(modellist[1], arcname=modellist[1])
|
||||
# zip_inputpath = os.path.join(exp_outputPath, "inference_model")
|
||||
# zip_outputPath = os.path.join(exp_outputPath, "inference_model.zip")
|
||||
|
||||
|
||||
@obtain_train_param()
|
||||
def returnTrainParams():
|
||||
# nvmlInit()
|
||||
# gpuDeviceCount = nvmlDeviceGetCount() # 获取Nvidia GPU块数
|
||||
# _kernel = [f"cuda:{a}" for a in range(gpuDeviceCount)]
|
||||
params_list = [
|
||||
{"index": 0, "name": "epochnum", "value": 10, "description": '训练轮次', "default": 100, "type": "I", 'show': True},
|
||||
{"index": 1, "name": "batch_size", "value": 4, "description": '批次图像数量', "default": 1, "type": "I",
|
||||
'show': True},
|
||||
{"index": 2, "name": "img_size", "value": 640, "description": '训练图像大小', "default": 640, "type": "I",
|
||||
'show': True},
|
||||
{"index": 3, "name": "device", "value": "0", "description": '训练核心', "default": "cuda", "type": "S",
|
||||
"items": '', 'show': True}, # _kernel
|
||||
{"index": 4, "name": "saveModDir", "value": "E:/alg_demo-master/alg_demo/app/yolov5/best.pt",
|
||||
"description": '保存模型路径',
|
||||
"default": "./app/maskrcnn/saved_model/test.pt", "type": "S", 'show': False},
|
||||
{"index": 5, "name": "resumeModPath", "value": 'E:/alg_demo-master/alg_demo/app/yolov5/yolov5s.pt',
|
||||
"description": '继续训练路径', "default": '', "type": "S",
|
||||
'show': False},
|
||||
{"index": 6, "name": "resumeMod", "value": '', "description": '继续训练模型', "default": '', "type": "E", "items": '',
|
||||
'show': True},
|
||||
{"index": 7, "name": "classname", "value": ['logo', '3C'], "description": '类别名称', "default": '', "type": "L",
|
||||
"items": '',
|
||||
'show': False},
|
||||
{"index": 8, "name": "DatasetDir", "value": "E:/aicheck/data_set/11442136178662604800/ori/",
|
||||
"description": '数据集路径',
|
||||
"default": "./app/maskrcnn/datasets/test", "type": "S", 'show': False} # ORI_PATH
|
||||
]
|
||||
# {"index": 9, "name": "saveEpoch", "value": 2, "description": '保存模型轮次', "default": 2, "type": "I", 'show': True}]
|
||||
params_str = json.dumps(params_list)
|
||||
return params_str
|
||||
|
||||
|
||||
@obtain_test_param()
|
||||
def returnValidateParams():
|
||||
# nvmlInit()
|
||||
# gpuDeviceCount = nvmlDeviceGetCount() # 获取Nvidia GPU块数
|
||||
# _kernel = [f"cuda:{a}" for a in range(gpuDeviceCount)]
|
||||
params_list = [
|
||||
{"index": 0, "name": "modPath", "value": "E:/alg_demo-master/alg_demo/app/yolov5/圆孔_123_RODY_1_640.pt",
|
||||
"description": '验证模型路径', "default": "./app/maskrcnn/saved_model/test.pt", "type": "S", 'show': False},
|
||||
{"index": 1, "name": "batch_size", "value": 1, "description": '批次图像数量', "default": 1, "type": "I",
|
||||
'show': False},
|
||||
{"index": 2, "name": "img_size", "value": 640, "description": '训练图像大小', "default": 640, "type": "I",
|
||||
'show': False},
|
||||
{"index": 3, "name": "outputPath", "value": 'E:/aicheck/data_set/11442136178662604800/val_results/',
|
||||
"description": '输出结果路径',
|
||||
"default": './app/maskrcnn/datasets/M006B_waibi/res', "type": "S", 'show': False},
|
||||
{"index": 4, "name": "device", "value": "0", "description": '训练核心', "default": "cuda", "type": "S",
|
||||
"items": '', 'show': False} # _kernel
|
||||
]
|
||||
# {"index": 9, "name": "saveEpoch", "value": 2, "description": '保存模型轮次', "default": 2, "type": "I", 'show': True}]
|
||||
params_str = json.dumps(params_list)
|
||||
return params_str
|
||||
|
||||
|
||||
@obtain_detect_param()
|
||||
def returnDetectParams():
|
||||
# nvmlInit()
|
||||
# gpuDeviceCount = nvmlDeviceGetCount() # 获取Nvidia GPU块数
|
||||
# _kernel = [f"cuda:{a}" for a in range(gpuDeviceCount)]
|
||||
params_list = [
|
||||
{"index": 0, "name": "inputPath", "value": 'E:/aicheck/data_set/11442136178662604800/input/',
|
||||
"description": '输入图像路径', "default": './app/maskrcnn/datasets/M006B_waibi/JPEGImages', "type": "S",
|
||||
'show': False},
|
||||
{"index": 1, "name": "outputPath", "value": 'E:/aicheck/data_set/11442136178662604800/val_results/',
|
||||
"description": '输出结果路径',
|
||||
"default": './app/maskrcnn/datasets/M006B_waibi/res', "type": "S", 'show': False},
|
||||
{"index": 0, "name": "modPath", "value": "E:/alg_demo-master/alg_demo/app/yolov5/圆孔_123_RODY_1_640.pt",
|
||||
"description": '模型路径', "default": "./app/maskrcnn/saved_model/test.pt", "type": "S", 'show': False},
|
||||
{"index": 3, "name": "device", "value": "0", "description": '推理核', "default": "cpu", "type": "S",
|
||||
'show': False},
|
||||
]
|
||||
# {"index": 9, "name": "saveEpoch", "value": 2, "description": '保存模型轮次', "default": 2, "type": "I", 'show': True}]
|
||||
params_str = json.dumps(params_list)
|
||||
return params_str
|
||||
|
||||
|
||||
@obtain_download_pt_param()
|
||||
def returnDownloadParams():
|
||||
params_list = [
|
||||
{"index": 0, "name": "exp_inputPath", "value": 'E:/alg_demo-master/alg_demo/app/yolov5/圆孔_123_RODY_1_640.pt',
|
||||
"description": '转化模型输入路径',
|
||||
"default": '/mnt/sdc/IntelligentizeAI/IntelligentizeAI/data_set/weights/new磁环检测test_183504733393264640_R-DDM_11.pt/',
|
||||
"type": "S", 'show': False},
|
||||
{"index": 1, "name": "device", "value": 'gpu', "description": 'CPU或GPU', "default": 'gpu', "type": "S",
|
||||
'show': False}
|
||||
]
|
||||
params_str = json.dumps(params_list)
|
||||
return params_str
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
par = returnDownloadParams()
|
||||
print(par)
|
||||
Export_model_RODY(par)
|
33
app/controller/WebStatusController.py
Normal file
33
app/controller/WebStatusController.py
Normal file
@ -0,0 +1,33 @@
|
||||
import logging
|
||||
|
||||
from flask import Blueprint, app
|
||||
|
||||
from app.exts import redisClient
|
||||
from app.utils.StandardizedOutput import output_wrapped
|
||||
|
||||
bp = Blueprint('WebStatus', __name__)
|
||||
|
||||
|
||||
@bp.route('/ping', methods=['GET'])
|
||||
def ping():
|
||||
""" For health check.
|
||||
"""
|
||||
res = output_wrapped(0, 'pong', '')
|
||||
return res
|
||||
|
||||
|
||||
@bp.route('/redis/set', methods=['post'])
|
||||
def redis_set():
|
||||
redisClient.set('foo', 'bar', ex=60*60*6)
|
||||
res = output_wrapped(0, 'set foo', '')
|
||||
return res
|
||||
|
||||
|
||||
@bp.route('/redis/get', methods=['get'])
|
||||
def redis_get():
|
||||
""" For health check.
|
||||
"""
|
||||
the_food = redisClient.get('foo')
|
||||
if not the_food:
|
||||
return output_wrapped(5006, 'foo', "")
|
||||
return output_wrapped(0, 'foo', the_food.decode("utf-8"))
|
4
app/controller/__init__.py
Normal file
4
app/controller/__init__.py
Normal file
@ -0,0 +1,4 @@
|
||||
from app.core.common_utils import import_subs
|
||||
|
||||
|
||||
__all__ = import_subs(locals(), modules_only=True)
|
BIN
app/controller/圆孔_123_RODY_1_640.zip
Normal file
BIN
app/controller/圆孔_123_RODY_1_640.zip
Normal file
Binary file not shown.
0
app/core/__init__.py
Normal file
0
app/core/__init__.py
Normal file
319
app/core/common_utils.py
Normal file
319
app/core/common_utils.py
Normal file
@ -0,0 +1,319 @@
|
||||
import orjson
|
||||
|
||||
try:
|
||||
from collections import Mapping
|
||||
except: # noqa E722
|
||||
from collections.abc import Mapping
|
||||
import inspect
|
||||
import importlib
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from typing import Any, Dict, List, Optional
|
||||
from unicodedata import normalize
|
||||
from distutils.version import LooseVersion
|
||||
import logging
|
||||
import datetime
|
||||
|
||||
from flask import request
|
||||
from flask_sqlalchemy import model
|
||||
from sqlalchemy import UniqueConstraint
|
||||
import marshmallow
|
||||
from marshmallow import Schema
|
||||
|
||||
from .webargs import use_kwargs as base_use_kwargs, parser
|
||||
|
||||
from flask.json import JSONEncoder
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class ParamsDict(dict):
|
||||
"""Just available update func.
|
||||
|
||||
Example::
|
||||
|
||||
@use_kwargs(PageParams.update({...}))
|
||||
def list_users(page, page_size, order_by):
|
||||
pass
|
||||
|
||||
"""
|
||||
|
||||
def update(self, other=None):
|
||||
"""Update self by other Mapping and return self.
|
||||
"""
|
||||
ret = ParamsDict(self.copy())
|
||||
if other is not None:
|
||||
for k, v in other.items() if isinstance(other, Mapping) else other:
|
||||
ret[k] = v
|
||||
return ret
|
||||
|
||||
|
||||
# Function version
|
||||
def row2dict(row):
|
||||
return {
|
||||
c.name: str(getattr(row, c.name))
|
||||
for c in row.__table__.columns
|
||||
}
|
||||
|
||||
|
||||
class dict2object(dict):
|
||||
"""
|
||||
Dict to fake object that can use getattr.
|
||||
"""
|
||||
|
||||
def __getattr__(self, name: str) -> Any:
|
||||
if name in self.keys():
|
||||
return self[name]
|
||||
raise AttributeError('object has no attribute {}'.format(name))
|
||||
|
||||
def __setattr__(self, name: str, value: Any) -> None:
|
||||
if not isinstance(name, str):
|
||||
raise TypeError('key must be string type.')
|
||||
self[name] = value
|
||||
|
||||
|
||||
def secure_filename(filename: str) -> str:
|
||||
"""Borrowed from werkzeug.utils.secure_filename.
|
||||
|
||||
Pass it a filename and it will return a secure version of it. This
|
||||
filename can then safely be stored on a regular file system and passed
|
||||
to :func:`os.path.join`.
|
||||
|
||||
On windows systems the function also makes sure that the file is not
|
||||
named after one of the special device files.
|
||||
|
||||
>>> secure_filename(u'哈哈.zip')
|
||||
'哈哈.zip'
|
||||
>>> secure_filename('My cool movie.mov')
|
||||
'My_cool_movie.mov'
|
||||
>>> secure_filename('../../../etc/passwd')
|
||||
'etc_passwd'
|
||||
>>> secure_filename(u'i contain cool \xfcml\xe4uts.txt')
|
||||
'i_contain_cool_umlauts.txt'
|
||||
|
||||
"""
|
||||
|
||||
for sep in os.path.sep, os.path.altsep:
|
||||
if sep:
|
||||
filename = filename.replace(sep, ' ')
|
||||
|
||||
filename = normalize('NFKD', '_'.join(filename.split()))
|
||||
|
||||
filename_strip_re = re.compile(u'[^A-Za-z0-9\u4e00-\u9fa5_.-]')
|
||||
filename = filename_strip_re.sub('', filename).strip('._')
|
||||
|
||||
# on nt a couple of special files are present in each folder. We
|
||||
# have to ensure that the target file is not such a filename. In
|
||||
# this case we prepend an underline
|
||||
windows_device_files = (
|
||||
'CON', 'AUX', 'COM1', 'COM2', 'COM3', 'COM4', 'LPT1',
|
||||
'LPT2', 'LPT3', 'PRN', 'NUL',
|
||||
)
|
||||
if os.name == 'nt' and filename and \
|
||||
filename.split('.')[0].upper() in windows_device_files:
|
||||
filename = '_' + filename
|
||||
|
||||
return filename
|
||||
|
||||
|
||||
def _get_init_args(instance, base_class):
|
||||
"""Get instance's __init__ args and it's value when __call__.
|
||||
"""
|
||||
getargspec = inspect.getfullargspec
|
||||
argspec = getargspec(base_class.__init__)
|
||||
|
||||
defaults = argspec.defaults
|
||||
kwargs = {}
|
||||
if defaults is not None:
|
||||
no_defaults = argspec.args[:-len(defaults)]
|
||||
has_defaults = argspec.args[-len(defaults):]
|
||||
|
||||
kwargs = {k: getattr(instance, k) for k in no_defaults
|
||||
if k != 'self' and hasattr(instance, k)}
|
||||
kwargs.update({k: getattr(instance, k) if hasattr(instance, k) else
|
||||
getattr(instance, k, defaults[i])
|
||||
for i, k in enumerate(has_defaults)})
|
||||
assert len(kwargs) == len(argspec.args) - 1, 'exclude `self`'
|
||||
return kwargs
|
||||
|
||||
|
||||
def use_kwargs(argmap, schema_kwargs: Optional[Dict] = None, **kwargs: Any):
|
||||
"""For fix ``Schema(partial=True)`` not work when used with
|
||||
``@webargs.flaskparser.use_kwargs``. More details ``see webargs.core``.
|
||||
|
||||
Args:
|
||||
|
||||
argmap (marshmallow.Schema,dict,callable): Either a
|
||||
`marshmallow.Schema`, `dict` of argname ->
|
||||
`marshmallow.fields.Field` pairs, or a callable that returns a
|
||||
`marshmallow.Schema` instance.
|
||||
schema_kwargs (dict): kwargs for argmap.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary of parsed arguments.
|
||||
|
||||
"""
|
||||
schema_kwargs = schema_kwargs or {}
|
||||
|
||||
argmap = parser._get_schema(argmap, request)
|
||||
|
||||
if not (argmap.partial or schema_kwargs.get('partial')):
|
||||
return base_use_kwargs(argmap, **kwargs)
|
||||
|
||||
def factory(request):
|
||||
argmap_kwargs = _get_init_args(argmap, Schema)
|
||||
argmap_kwargs.update(schema_kwargs)
|
||||
|
||||
# force set force_all=False
|
||||
only = parser.parse(argmap, request).keys()
|
||||
|
||||
argmap_kwargs.update({
|
||||
'partial': False, # fix missing=None not work
|
||||
'only': only or None,
|
||||
'context': {"request": request},
|
||||
})
|
||||
if tuple(LooseVersion(marshmallow.__version__).version)[0] < 3:
|
||||
argmap_kwargs['strict'] = True
|
||||
|
||||
return argmap.__class__(**argmap_kwargs)
|
||||
|
||||
return base_use_kwargs(factory, **kwargs)
|
||||
|
||||
|
||||
def import_subs(locals_, modules_only: bool = False) -> List[str]:
|
||||
""" Auto import submodules, used in __init__.py.
|
||||
|
||||
Args:
|
||||
|
||||
locals_: `locals()`.
|
||||
modules_only: Only collect modules to __all__.
|
||||
|
||||
Examples::
|
||||
|
||||
# app/models/__init__.py
|
||||
from hobbit_core.utils import import_subs
|
||||
|
||||
__all__ = import_subs(locals())
|
||||
|
||||
Auto collect Model's subclass, Schema's subclass and instance.
|
||||
Others objects must defined in submodule.__all__.
|
||||
"""
|
||||
package = locals_['__package__']
|
||||
path = locals_['__path__']
|
||||
top_mudule = sys.modules[package]
|
||||
|
||||
all_ = []
|
||||
for name in os.listdir(path[0]):
|
||||
if not name.endswith(('.py', '.pyc')) or name.startswith('__init__.'):
|
||||
continue
|
||||
|
||||
module_name = name.split('.')[0]
|
||||
submodule = importlib.import_module(f".{module_name}", package)
|
||||
all_.append(module_name)
|
||||
|
||||
if modules_only:
|
||||
continue
|
||||
|
||||
if hasattr(submodule, '__all__'):
|
||||
for name in getattr(submodule, '__all__'):
|
||||
if not isinstance(name, str):
|
||||
raise Exception(f'Invalid object {name} in __all__, '
|
||||
f'must contain only strings.')
|
||||
setattr(top_mudule, name, getattr(submodule, name))
|
||||
all_.append(name)
|
||||
else:
|
||||
for name, obj in submodule.__dict__.items():
|
||||
if isinstance(obj, (model.DefaultMeta, Schema)) or \
|
||||
(inspect.isclass(obj) and
|
||||
(issubclass(obj, Schema) or
|
||||
obj.__name__.endswith('Service'))):
|
||||
setattr(top_mudule, name, obj)
|
||||
all_.append(name)
|
||||
return all_
|
||||
|
||||
|
||||
def bulk_create_or_update_on_duplicate(
|
||||
db, model_cls, items, updated_at='updated_at', batch_size=500):
|
||||
""" Support MySQL and postgreSQL.
|
||||
https://dev.mysql.com/doc/refman/8.0/en/insert-on-duplicate.html
|
||||
|
||||
Args:
|
||||
|
||||
db: Instance of `SQLAlchemy`.
|
||||
model_cls: Model object.
|
||||
items: List of data,[ example: `[{key: value}, {key: value}, ...]`.
|
||||
updated_at: Field which recording row update time.
|
||||
batch_size: Batch size is max rows per execute.
|
||||
|
||||
Returns:
|
||||
dict: A dictionary contains rowcount and items_count.
|
||||
"""
|
||||
if not items:
|
||||
logger.warning("bulk_create_or_update_on_duplicate save to "
|
||||
f"{model_cls} failed, empty items")
|
||||
return {'rowcount': 0, 'items_count': 0}
|
||||
|
||||
items_count = len(items)
|
||||
table_name = model_cls.__tablename__
|
||||
fields = list(items[0].keys())
|
||||
unique_keys = [c.name for i in model_cls.__table_args__ if isinstance(
|
||||
i, UniqueConstraint) for c in i]
|
||||
columns = [c.name for c in model_cls.__table__.columns if c.name not in (
|
||||
'id', 'created_at')]
|
||||
|
||||
if updated_at in columns and updated_at not in fields:
|
||||
fields.append(updated_at)
|
||||
updated_at_time = datetime.datetime.now()
|
||||
for item in items:
|
||||
item[updated_at] = updated_at_time
|
||||
|
||||
assert set(fields) == set(columns), \
|
||||
'item fields not equal to columns in models:new: ' + \
|
||||
f'{set(fields) - set(columns)}, delete: {set(columns) - set(fields)}'
|
||||
|
||||
for item in items:
|
||||
for column in unique_keys:
|
||||
if column in item and item[column] is None:
|
||||
item[column] = ''
|
||||
|
||||
engine = db.get_engine(bind=getattr(model_cls, '__bind_key__', None))
|
||||
if engine.name == 'postgresql':
|
||||
sql_on_update = ', '.join([
|
||||
f' {field} = excluded.{field}'
|
||||
for field in fields if field not in unique_keys])
|
||||
sql = f"""INSERT INTO {table_name} ({", ".join(fields)}) VALUES
|
||||
({", ".join([f':{key}' for key in fields])})
|
||||
ON CONFLICT ({", ".join(unique_keys)}) DO UPDATE SET
|
||||
{sql_on_update}"""
|
||||
elif engine.name == 'mysql':
|
||||
sql_on_update = '`, `'.join([
|
||||
f' `{field}` = new.{field}' for field in fields
|
||||
if field not in unique_keys])
|
||||
sql = f"""INSERT INTO {table_name} (`{"`, `".join(fields)}`) VALUES
|
||||
({", ".join([f':{key}' for key in fields])}) AS new
|
||||
ON DUPLICATE KEY UPDATE
|
||||
{sql_on_update}"""
|
||||
else:
|
||||
raise Exception(f'not support db: {engine.name}')
|
||||
|
||||
rowcounts = 0
|
||||
while len(items) > 0:
|
||||
batch, items = items[:batch_size], items[batch_size:]
|
||||
try:
|
||||
result = db.session.execute(sql, batch, bind=engine)
|
||||
except Exception as e:
|
||||
logger.error(e, exc_info=True)
|
||||
logger.info(sql)
|
||||
raise e
|
||||
rowcounts += result.rowcount
|
||||
logger.info(f'{model_cls} save_data: rowcount={rowcounts}, '
|
||||
f'items_count: {items_count}')
|
||||
return {'rowcount': rowcounts, 'items_count': items_count}
|
||||
|
||||
|
||||
def orjson_serializer(obj):
|
||||
"""
|
||||
Note that `orjson.dumps()` return byte array, while sqlalchemy expects string, thus `decode()` call.
|
||||
"""
|
||||
return orjson.dumps(obj, option=orjson.OPT_SERIALIZE_NUMPY | orjson.OPT_NAIVE_UTC).decode()
|
68
app/core/err_handler.py
Normal file
68
app/core/err_handler.py
Normal file
@ -0,0 +1,68 @@
|
||||
import logging
|
||||
|
||||
from flask import jsonify, request, make_response, abort
|
||||
from marshmallow import ValidationError
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
# 处理404错误
|
||||
def page_not_found(e):
|
||||
# if a request is in our blog URL space
|
||||
if request.path.startswith('/blog/'):
|
||||
# we return a custom blog 404 page
|
||||
return jsonify({
|
||||
"code": e.code,
|
||||
"message": e.name,
|
||||
"description": e.description,
|
||||
"data": ""
|
||||
}), 404
|
||||
else:
|
||||
# otherwise we return our generic site-wide 404 page
|
||||
return jsonify({
|
||||
"code": e.code,
|
||||
"message": e.name,
|
||||
"description": e.description,
|
||||
"data": ""
|
||||
}), 404
|
||||
|
||||
|
||||
# 处理405错误
|
||||
def method_not_allowed(e):
|
||||
# otherwise we return a generic site-wide 405 page
|
||||
return jsonify({
|
||||
"code": e.code,
|
||||
"message": e.name,
|
||||
"description": e.description,
|
||||
"data": ""
|
||||
}), 405
|
||||
|
||||
|
||||
# 处理其他400错误
|
||||
def exception_400(e):
|
||||
# otherwise we return a generic site-wide 405 page
|
||||
return jsonify({
|
||||
"code": e.code,
|
||||
"message": e.name,
|
||||
"description": e.description,
|
||||
"data": ""
|
||||
}), 400
|
||||
|
||||
|
||||
# 处理其他状态码错误
|
||||
def exception_500(e):
|
||||
print(e)
|
||||
return jsonify({
|
||||
"code": e.code,
|
||||
"message": e.name,
|
||||
"description": e.description,
|
||||
"data": ""
|
||||
}), e.code
|
||||
|
||||
|
||||
# 处理参数校验错误
|
||||
def check_data(schema, data):
|
||||
try:
|
||||
return schema().load(data)
|
||||
except ValidationError as e:
|
||||
abort(make_response(jsonify(code=400, message=str(e.messages), data=None), 400))
|
26
app/core/webargs.py
Normal file
26
app/core/webargs.py
Normal file
@ -0,0 +1,26 @@
|
||||
from collections.abc import Mapping
|
||||
|
||||
from webargs.flaskparser import FlaskParser
|
||||
|
||||
|
||||
def strip_whitespace(value):
|
||||
if isinstance(value, str):
|
||||
value = value.strip()
|
||||
# you'll be getting a MultiDictProxy here potentially, but it should work
|
||||
elif isinstance(value, Mapping):
|
||||
return {k: strip_whitespace(value[k]) for k in value}
|
||||
elif isinstance(value, (list, set)):
|
||||
return type(value)(map(strip_whitespace, value))
|
||||
return value
|
||||
|
||||
|
||||
class CustomParser(FlaskParser):
|
||||
|
||||
def _load_location_data(self, **kwargs):
|
||||
data = super()._load_location_data(**kwargs)
|
||||
return strip_whitespace(data)
|
||||
|
||||
|
||||
parser = CustomParser()
|
||||
use_args = parser.use_args
|
||||
use_kwargs = parser.use_kwargs
|
12
app/exts.py
Normal file
12
app/exts.py
Normal file
@ -0,0 +1,12 @@
|
||||
import redis
|
||||
from flask_sqlalchemy import SQLAlchemy
|
||||
from flask_migrate import Migrate
|
||||
from flask_marshmallow import Marshmallow
|
||||
|
||||
|
||||
db = SQLAlchemy()
|
||||
migrate = Migrate()
|
||||
ma = Marshmallow()
|
||||
|
||||
pool = redis.ConnectionPool(host='localhost', password='sdust2020', port=6379, db=8)
|
||||
redisClient = redis.Redis(connection_pool=pool)
|
253
app/file_tool.py
Normal file
253
app/file_tool.py
Normal file
@ -0,0 +1,253 @@
|
||||
import json
|
||||
import os
|
||||
import shutil
|
||||
from math import ceil
|
||||
from typing import List, Optional, Union
|
||||
|
||||
#from ai_platform.common.config import settings
|
||||
# from ai_platform.model.crud import image_label_crud as ilc, project_list_crud as plc, \
|
||||
# image_dataset_curd as idc
|
||||
#from ai_platform.common.logger import logger
|
||||
# from ai_platform.model.database import session
|
||||
from app.core.common_utils import logger
|
||||
from app.json_util import write_info
|
||||
|
||||
# root_path = settings.root_path
|
||||
|
||||
# root_path = '/home/wd/server/ai_platform/data_set/'
|
||||
|
||||
#db = session
|
||||
|
||||
|
||||
def delete_file(files: List[str]):
|
||||
"""
|
||||
删除文件
|
||||
:param files:
|
||||
:return:
|
||||
"""
|
||||
for file in files:
|
||||
if os.path.exists(file):
|
||||
os.remove(file)
|
||||
|
||||
|
||||
def get_file_then_delete_file(path: str):
|
||||
"""
|
||||
删除指定路径下的所有文件
|
||||
:param path:
|
||||
:return:
|
||||
"""
|
||||
(filedir, filename) = os.path.split(path)
|
||||
if os.path.exists(filedir):
|
||||
del_files = []
|
||||
for (dirpath, dirnames, filenames) in os.walk(filedir):
|
||||
for filename in filenames:
|
||||
del_files.append(os.path.join(dirpath, filename))
|
||||
# del_files = os.listdir(filedir)
|
||||
delete_file(files=del_files)
|
||||
return filedir
|
||||
|
||||
|
||||
def delete_dir_file(files: List[str], json_files: List[str]):
|
||||
"""
|
||||
若训练集、测试机、验证集的存放文件夹不为空, 删除文件夹下所有文件
|
||||
:param json_files:
|
||||
:param files:
|
||||
:return:
|
||||
"""
|
||||
logger.info('删除图片数据')
|
||||
train_target_path = files[0].replace('ori/images', 'trained/images/train')
|
||||
train_filedir = get_file_then_delete_file(train_target_path)
|
||||
|
||||
val_target_path = files[0].replace('ori/images', 'trained/images/val')
|
||||
val_filedir = get_file_then_delete_file(val_target_path)
|
||||
|
||||
test_target_path = files[0].replace('ori/images', 'trained/images/test')
|
||||
test_filedir = get_file_then_delete_file(test_target_path)
|
||||
|
||||
if len(json_files) == 0:
|
||||
logger.info('无json数据')
|
||||
else:
|
||||
logger.info('删除json数据')
|
||||
train_target_path = json_files[0].replace('ori/labels', 'trained/labels/train')
|
||||
get_file_then_delete_file(train_target_path)
|
||||
|
||||
val_target_path = json_files[0].replace('ori/labels', 'trained/labels/val')
|
||||
get_file_then_delete_file(val_target_path)
|
||||
|
||||
val_target_path = json_files[0].replace('ori/labels', 'trained/labels/test')
|
||||
get_file_then_delete_file(val_target_path)
|
||||
return [train_filedir + '/', val_filedir + '/', test_filedir + '/']
|
||||
|
||||
|
||||
def mv_file(train_files: List[str], test_files: List[str], r_v_rate: Optional[float] = 0.9,
|
||||
t_t_rate: Optional[float] = 0.9):
|
||||
"""
|
||||
移动图片标签到指定位置
|
||||
:param train_files:测试集
|
||||
:param test_files:验证集
|
||||
:param r_v_rate:训练集内部比例
|
||||
:param t_t_rate:训练-验证比例
|
||||
:return:
|
||||
"""
|
||||
train_img_files = [i for i in train_files if not i.endswith('.json')]
|
||||
train_json_files = [i for i in train_files if i.endswith('.json')]
|
||||
test_img_files = [i for i in test_files if not i.endswith('.json')]
|
||||
test_json_files = [i for i in test_files if i.endswith('.json')]
|
||||
|
||||
# 训练集、验证集、测试集
|
||||
#logger.info('训练集、验证集、测试集开始划分')
|
||||
train_len_all = len(train_img_files)
|
||||
if t_t_rate is not None:
|
||||
test_len_all = len(test_img_files)
|
||||
len_all = train_len_all + test_len_all
|
||||
t_t_rate_c = test_len_all / len_all
|
||||
if t_t_rate_c > t_t_rate:
|
||||
train_len_all = ceil(len_all * t_t_rate)
|
||||
test_files.extend(train_img_files[train_len_all:])
|
||||
train_len = ceil(train_len_all * r_v_rate)
|
||||
# t_files: 训练集, val_files:验证集
|
||||
t_files = train_img_files[0:train_len]
|
||||
val_files = train_img_files[train_len:train_len_all]
|
||||
|
||||
# 判断目标文件夹是否存在, 存在则删除目录下文件
|
||||
#logger.info('判断目标文件夹是否存在, 存在则删除目录下文件')
|
||||
target_path = delete_dir_file(files=train_img_files, json_files=train_json_files)
|
||||
|
||||
# 放到指定文件夹
|
||||
#logger.info('放到指定文件夹')
|
||||
# t_files:训练集开始移动
|
||||
for file in t_files:
|
||||
if os.path.exists(file):
|
||||
file_path = file.replace('ori/images', 'trained/images/train')
|
||||
# /3148803620347904/ori/images/4.jpg
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(file, file_path)
|
||||
# json 放到指定文件夹下
|
||||
json_file = os.path.splitext(file)[0].replace('images', 'labels') + '.json'
|
||||
if json_file in train_json_files:
|
||||
file_path = json_file.replace('ori/labels', 'trained/labels/train')
|
||||
# /3148803620347904/ori/labels/4.jpg.json
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(json_file, file_path)
|
||||
|
||||
# 测试集开始
|
||||
for file in val_files:
|
||||
if os.path.exists(file):
|
||||
file_path = file.replace('ori/images', 'trained/images/val')
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(file, file_path)
|
||||
# json 放到指定文件夹下
|
||||
json_file = os.path.splitext(file)[0].replace('images', 'labels') + '.json'
|
||||
if json_file in train_json_files:
|
||||
file_path = json_file.replace('ori/labels', 'trained/labels/val')
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(json_file, file_path)
|
||||
|
||||
for file in test_img_files:
|
||||
if os.path.exists(file):
|
||||
file_path = file.replace('ori/images', 'trained/images/test')
|
||||
# /3148803620347904/ori/images/4.jpg
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(file, file_path)
|
||||
# json 放到指定文件夹下
|
||||
json_file = os.path.splitext(file)[0].replace('images', 'labels') + '.json'
|
||||
if json_file in test_json_files:
|
||||
file_path = json_file.replace('ori/labels', 'trained/labels/test')
|
||||
# /3148803620347904/ori/labels/4.jpg.json
|
||||
(filedir, filename) = os.path.split(file_path)
|
||||
if not os.path.exists(filedir):
|
||||
os.makedirs(filedir)
|
||||
shutil.copyfile(json_file, file_path)
|
||||
return target_path
|
||||
|
||||
|
||||
def get_file(ori_path: str, type_list: Union[object,str]):
|
||||
# imgs = idc.get_image_all_proj_no(proj_no=proj_no, db=db)
|
||||
imgs = os.listdir(ori_path + '/images')
|
||||
train_files = []
|
||||
test_files = []
|
||||
# 训练、测试比例强制9:1
|
||||
for img in imgs[0:1]:
|
||||
path = ori_path + 'images/' +img
|
||||
# print(os.path.exists(path))
|
||||
if os.path.exists(path):
|
||||
test_files.append(path)
|
||||
#label = ori_path + 'labels/' + os.path.split(path)[1]
|
||||
(filename1, extension) = os.path.splitext(img) # 文件名与后缀名分开
|
||||
label = ori_path + 'labels/' + filename1 + '.json'
|
||||
if label is not None:
|
||||
#train_files.append(label)
|
||||
test_files.append(label)
|
||||
for img in imgs[1:]:
|
||||
path = ori_path + 'images/' +img
|
||||
if os.path.exists(path):
|
||||
train_files.append(path)
|
||||
(filename2, extension) = os.path.splitext(img) # 文件名与后缀名分开
|
||||
label = ori_path + 'labels/' + filename2 + '.json'
|
||||
if label is not None:
|
||||
train_files.append(label)
|
||||
|
||||
if len(train_files) == 0 or len(test_files) == 0:
|
||||
return False
|
||||
# proj = plc.get_proj_by_proj_no(proj_no=proj_no, db=db)
|
||||
target_path = mv_file(train_files=train_files, test_files=test_files)
|
||||
# 生成标签
|
||||
# img_types = ilc.get_label_by_proj_no(proj_no=proj_no, db=db)
|
||||
# type_list = []
|
||||
# for img_type in img_types:
|
||||
# type_list.append(img_type.lebel_type)
|
||||
type_dict = {'classes': type_list}
|
||||
str_json = json.dumps(type_dict)
|
||||
path = os.path.dirname(ori_path) + '/img_label_type'
|
||||
# path = root_path + proj_no + '/img_label_type'
|
||||
write_info(file_name=path, file_info=json.loads(str_json))
|
||||
target_path.append(path + '.json')
|
||||
return target_path
|
||||
|
||||
|
||||
# def get_file_path(proj_no: str):
|
||||
# """
|
||||
# 识别算法,给算法传递图片路径
|
||||
# :param proj_no:
|
||||
# :return:
|
||||
# """
|
||||
# path = root_path + '/' + proj_no
|
||||
# img_path = path
|
||||
# # 创建他们所需的文件夹
|
||||
# vgg_path = path + '/vgg'
|
||||
# if not os.path.exists(vgg_path):
|
||||
# # vgg不存在,创建
|
||||
# train_path = vgg_path + '/train'
|
||||
# test_path = vgg_path + '/test'
|
||||
# os.makedirs(train_path)
|
||||
# os.makedirs(test_path)
|
||||
# # 生成标签
|
||||
# img_types = ilc.get_label_by_proj_no(proj_no=proj_no, db=db)
|
||||
# type_list = []
|
||||
# for img_type in img_types:
|
||||
# type_list.append(img_type.lebel_type)
|
||||
# type_dict = {'classes': type_list}
|
||||
# str_json = json.dumps(type_dict)
|
||||
# path = root_path + proj_no + '/img_label_type'
|
||||
# write_info(file_name=path, file_info=json.loads(str_json))
|
||||
# return img_path, path + '.json'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# s = os.path.exists('D:/pythonProject/DeepLearnAiPlatform/data_set/868503011860480/ori/images/1.png')
|
||||
# print(s)
|
||||
# file = 'D:/pythonProject/DeepLearnAiPlatform/data_set/3148803620347904/ori/labels/36.json'
|
||||
# file_path = 'D:/pythonProject/DeepLearnAiPlatform/data_set/3148803620347904/trained/labels/36.json'
|
||||
s = get_file(proj_no='3148803620347904')
|
||||
# shutil.copyfile(file, file_path)
|
||||
print(s)
|
28
app/json_util.py
Normal file
28
app/json_util.py
Normal file
@ -0,0 +1,28 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
|
||||
def write_info(file_name, file_info):
|
||||
dir = os.path.dirname(file_name)
|
||||
if not os.path.exists(dir):
|
||||
os.makedirs(dir)
|
||||
with open('{}.json'.format(file_name), 'w', encoding='UTF-8') as fp:
|
||||
json.dump(file_info, fp, indent=4, sort_keys=False)
|
||||
fp.close()
|
||||
|
||||
|
||||
def read_json(file_path):
|
||||
with open(file_path, 'r') as f:
|
||||
data = json.load(f)
|
||||
f.close()
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
path = os.path.abspath(os.path.dirname(__file__))
|
||||
print(path)
|
||||
# write_info('', dict(report_data))
|
||||
# read_json('d://report.json')
|
||||
# s = '/group1/628740635893760/ori/images/7 (1).png'
|
||||
# s1 = s.replace('images', 'labels')
|
||||
# print(s[2])
|
3
app/models/__init__.py
Normal file
3
app/models/__init__.py
Normal file
@ -0,0 +1,3 @@
|
||||
from app.core.common_utils import import_subs
|
||||
|
||||
__all__ = import_subs(locals())
|
130
app/run.py
Normal file
130
app/run.py
Normal file
@ -0,0 +1,130 @@
|
||||
import datetime
|
||||
import importlib
|
||||
import json
|
||||
import logging
|
||||
from typing import List, Dict, Union
|
||||
|
||||
from flask import Flask, request
|
||||
from flask.helpers import get_env
|
||||
from flask_sockets import Sockets
|
||||
|
||||
import sys
|
||||
#sys.path.append("/mnt/sdc/algorithm/AICheck-MaskRCNN")
|
||||
from app.core.common_utils import logger
|
||||
from app.core.err_handler import page_not_found, method_not_allowed, exception_500, exception_400
|
||||
|
||||
from app.exts import db, migrate, ma
|
||||
from app.utils.redis_config import redis_client
|
||||
from app.utils.websocket_tool import manager
|
||||
|
||||
|
||||
def register_extensions(app):
|
||||
db.init_app(app)
|
||||
migrate.init_app(app, db)
|
||||
ma.init_app(app)
|
||||
|
||||
|
||||
def register_blueprints(app):
|
||||
from app import controller
|
||||
for name in controller.__all__:
|
||||
bp = getattr(importlib.import_module(f'app.controller.{name}'), 'bp', None)
|
||||
if bp is not None:
|
||||
app.register_blueprint(
|
||||
bp, url_prefix=f"/api{bp.url_prefix if bp.url_prefix else ''}")
|
||||
|
||||
|
||||
def register_error_handler(app):
|
||||
app.register_error_handler(404, page_not_found)
|
||||
app.register_error_handler(405, method_not_allowed)
|
||||
app.register_error_handler(400, exception_400)
|
||||
# app.register_error_handler(500, exception_500)
|
||||
|
||||
|
||||
def register_cmds(app):
|
||||
pass
|
||||
|
||||
|
||||
def register_log(app):
|
||||
logging.root.handlers = []
|
||||
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s', level=logging.INFO, filename='ex.log')
|
||||
|
||||
# set up logging to console
|
||||
console = logging.StreamHandler()
|
||||
console.setLevel(logging.ERROR)
|
||||
# set a format which is simpler for console use
|
||||
formatter = logging.Formatter('%(asctime)s : %(levelname)s : %(message)s')
|
||||
console.setFormatter(formatter)
|
||||
logging.getLogger("").addHandler(console)
|
||||
# logging.debug('debug')
|
||||
# logging.info('info')
|
||||
# logging.warning('warning')
|
||||
# logging.error('error')
|
||||
# logging.exception('exp')
|
||||
|
||||
|
||||
def register_redis(app):
|
||||
redis_client.init_redis_connect()
|
||||
|
||||
|
||||
# socketio = SocketIO()
|
||||
|
||||
|
||||
def create_app():
|
||||
app = Flask(__name__, instance_relative_config=True)
|
||||
app.config.from_object('app.configs.{}'.format(get_env()))
|
||||
app.debug = False
|
||||
# app.json_encoder = CustomJSONEncoder
|
||||
with app.app_context():
|
||||
register_extensions(app)
|
||||
register_blueprints(app)
|
||||
register_error_handler(app)
|
||||
db.create_all()
|
||||
register_cmds(app)
|
||||
register_log(app)
|
||||
register_redis(app)
|
||||
|
||||
@app.before_request
|
||||
def log_request_info():
|
||||
logger = logging.getLogger('werkzeug')
|
||||
if request.method in ['POST', 'PUT']:
|
||||
logger.info('Request Body: %s', request.get_data())
|
||||
|
||||
return app
|
||||
|
||||
|
||||
app = create_app()
|
||||
sockets = Sockets(app)
|
||||
|
||||
|
||||
@sockets.route('/echo/<id>')
|
||||
def echo_socket(ws, id: str):
|
||||
# 保存ws对象,根据
|
||||
manager.connect(ws=ws, id=id)
|
||||
logger.info('------进入websocket')
|
||||
while not ws.closed:
|
||||
msg = ws.receive()
|
||||
print(msg)
|
||||
res = {'code': 1, 'type': 'init', 'msg': '建立连接成功', 'data': '1'}
|
||||
try:
|
||||
ws.send(json.dumps(res), callable(success())) # 发送数据
|
||||
except:
|
||||
manager.disconnect(ws=ws, id=id)
|
||||
# ws.send(now) # 发送数据
|
||||
|
||||
|
||||
def success():
|
||||
logger.info('-----------回调消息成功------------')
|
||||
|
||||
|
||||
@app.route('/')
|
||||
def hello_world():
|
||||
return 'Hello World!'
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
from gevent import pywsgi
|
||||
from geventwebsocket.handler import WebSocketHandler
|
||||
|
||||
#8080 6913 '192.168.0.20'
|
||||
server = pywsgi.WSGIServer(('192.168.2.118', 6914), app, handler_class=WebSocketHandler)
|
||||
server.serve_forever()
|
64
app/schemas/TrainResult.py
Normal file
64
app/schemas/TrainResult.py
Normal file
@ -0,0 +1,64 @@
|
||||
"""
|
||||
@Time : 2022/9/29 11:39
|
||||
@Auth : 东
|
||||
@File :TrainResult.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:训练报告结果类
|
||||
|
||||
"""
|
||||
import datetime
|
||||
from typing import List, Dict
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
|
||||
class ProcessValueList(BaseModel):
|
||||
name: str = Field(..., description='名称')
|
||||
value: List[int] = Field(..., description='过程值,如损失值,精度等')
|
||||
|
||||
|
||||
class Report(BaseModel):
|
||||
"""
|
||||
训练算法返回值规范
|
||||
"""
|
||||
id: str = Field(..., description='唯一值')
|
||||
rate_of_progess: float = Field(..., description='进度,保留一位小数')
|
||||
precision: List[ProcessValueList] = Field(..., description="过程值列表")
|
||||
sum: int = Field(..., description='总轮次')
|
||||
progress: int = Field(..., description='当前轮次')
|
||||
isfinish: int = Field(0, description="是否结束")
|
||||
num_train_img: int = Field(..., description="参与训练图像数量")
|
||||
train_mod_savepath: str = Field(..., description="模型保存路径")
|
||||
start_time: datetime.date = Field(datetime.datetime.now(), description="开始时间")
|
||||
end_time: datetime.date = Field(datetime.datetime.now(), description="结束时间")
|
||||
|
||||
|
||||
class ReportDict(BaseModel):
|
||||
"""
|
||||
验证算法返回值规范
|
||||
"""
|
||||
id: str = Field(..., description='唯一值')
|
||||
rate_of_progess: float = Field(..., description='进度,保留一位小数')
|
||||
precision: List[Dict] = Field(..., description="过程值列表")
|
||||
start_time: datetime.date = Field(datetime.datetime.now(), description="开始时间")
|
||||
end_time: datetime.date = Field(datetime.datetime.now(), description="结束时间")
|
||||
|
||||
|
||||
class DetectProcessValueDice(BaseModel):
|
||||
"""
|
||||
检测算法中间值
|
||||
"""
|
||||
ori_img: str = Field(..., description='原时图片路径, 绝对路径')
|
||||
res_img: str = Field(..., description='结果图片路径, 绝对路径')
|
||||
|
||||
|
||||
class DetectReport(BaseModel):
|
||||
"""
|
||||
检测算法返回值规范
|
||||
"""
|
||||
id: str = Field(..., description='唯一值')
|
||||
rate_of_progess: float = Field(..., description='进度,保留一位小数')
|
||||
precision: List[DetectProcessValueDice] = Field(..., description="过程值列表")
|
||||
start_time: datetime.date = Field(datetime.datetime.now(), description="开始时间")
|
||||
end_time: datetime.date = Field(datetime.datetime.now(), description="结束时间")
|
5
app/schemas/__init__.py
Normal file
5
app/schemas/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
from app.core.common_utils import import_subs
|
||||
|
||||
__all__ = import_subs(locals())
|
||||
|
||||
|
46
app/services/RedisClient.py
Normal file
46
app/services/RedisClient.py
Normal file
@ -0,0 +1,46 @@
|
||||
"""
|
||||
@Time : 2022/10/9 11:53
|
||||
@Auth : 东
|
||||
@File :RedisClient.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
# coding:utf-8
|
||||
|
||||
import time
|
||||
import redis
|
||||
def redisClient():
|
||||
rc = redis.StrictRedis(host="localhost", port="6379", db=0, password="sdust2020")
|
||||
ps = rc.pubsub()
|
||||
ps.subscribe("liao") # 订阅消息
|
||||
a = 0
|
||||
|
||||
for item in ps.listen(): # 监听状态:有消息发布了就拿过来
|
||||
print(item)
|
||||
data = item['data']
|
||||
if type(data) == bytes:
|
||||
data = item['data'].decode()
|
||||
print(data)
|
||||
if data == '300030 -1':
|
||||
ps.unsubscribe("liao")
|
||||
|
||||
print(1)
|
||||
|
||||
|
||||
class Task(object):
|
||||
|
||||
def __init__(self, redis_conn, channel):
|
||||
self.rcon = redis_conn
|
||||
self.ps = self.rcon.pubsub()
|
||||
self.key = 'task:pubsub:%s' % channel
|
||||
self.ps.subscribe(self.key)
|
||||
|
||||
def listen_task(self):
|
||||
for i in self.ps.listen():
|
||||
if i['type'] == 'message':
|
||||
print("Task get ", i["data"])
|
||||
|
||||
def del_listen(self):
|
||||
self.ps.unsubscribe(self.key)
|
21
app/services/RedisService.py
Normal file
21
app/services/RedisService.py
Normal file
@ -0,0 +1,21 @@
|
||||
"""
|
||||
@Time : 2022/10/9 11:53
|
||||
@Auth : 东
|
||||
@File :RedisService.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
# coding:utf-8
|
||||
import json
|
||||
import time
|
||||
import redis
|
||||
|
||||
number_list = ['300033', '300032', '300031', '300030']
|
||||
signal = ['1', '-1', '1', '-1']
|
||||
|
||||
# rc = redis.StrictRedis(host='127.0.0.1', port='6379', db=3, password='sdust2020')
|
||||
# for i in range(len(number_list)):
|
||||
# value_new = {"ceshi": "测试"}
|
||||
# rc.publish("liao", json.dumps(value_new)) # 发布消息到liao
|
54
app/services/RpcClient.py
Normal file
54
app/services/RpcClient.py
Normal file
@ -0,0 +1,54 @@
|
||||
"""
|
||||
@Time : 2022/9/30 17:09
|
||||
@Auth : 东
|
||||
@File :RpcClient.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:RPC客户端
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
|
||||
|
||||
class TCPClient(object):
|
||||
def __init__(self):
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
def connect(self, host, port):
|
||||
"""链接Server端"""
|
||||
self.sock.connect((host, port))
|
||||
|
||||
def send(self, data):
|
||||
"""将数据发送到Server端"""
|
||||
self.sock.send(data)
|
||||
|
||||
def recv(self, length):
|
||||
"""接受Server端回传的数据"""
|
||||
return self.sock.recv(length)
|
||||
|
||||
|
||||
class RPCStub(object):
|
||||
|
||||
def __getattr__(self, function):
|
||||
def _func(*args, **kwargs):
|
||||
d = {'method_name': function, 'method_args': args, 'method_kwargs': kwargs}
|
||||
self.send(json.dumps(d).encode('utf-8')) # 发送数据
|
||||
data = self.recv(1024) # 接收方法执行后返回的结果
|
||||
return data.decode('utf-8')
|
||||
|
||||
setattr(self, function, _func)
|
||||
return _func
|
||||
|
||||
|
||||
class RPCClient(TCPClient, RPCStub):
|
||||
pass
|
||||
|
||||
|
||||
# c = RPCClient()
|
||||
# c.connect('127.0.0.1', 5003)
|
||||
# print(c.add(1, 2, 3))
|
||||
# print(c.setData({"sss": "ssss", "list": [5, 2, 3, 4]}))
|
||||
|
55
app/services/RpcClient2.py
Normal file
55
app/services/RpcClient2.py
Normal file
@ -0,0 +1,55 @@
|
||||
"""
|
||||
@Time : 2022/9/30 17:09
|
||||
@Auth : 东
|
||||
@File :RpcClient.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:RPC客户端
|
||||
|
||||
"""
|
||||
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
|
||||
|
||||
class TCPClient(object):
|
||||
def __init__(self):
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
|
||||
def connect(self, host, port):
|
||||
"""链接Server端"""
|
||||
self.sock.connect((host, port))
|
||||
|
||||
def send(self, data):
|
||||
"""将数据发送到Server端"""
|
||||
self.sock.send(data)
|
||||
|
||||
def recv(self, length):
|
||||
"""接受Server端回传的数据"""
|
||||
return self.sock.recv(length)
|
||||
|
||||
|
||||
class RPCStub(object):
|
||||
|
||||
def __getattr__(self, function):
|
||||
def _func(*args, **kwargs):
|
||||
d = {'method_name': function, 'method_args': args, 'method_kwargs': kwargs}
|
||||
self.send(json.dumps(d).encode('utf-8')) # 发送数据
|
||||
data = self.recv(1024) # 接收方法执行后返回的结果
|
||||
return data.decode('utf-8')
|
||||
|
||||
setattr(self, function, _func)
|
||||
return _func
|
||||
|
||||
|
||||
class RPCClient(TCPClient, RPCStub):
|
||||
pass
|
||||
|
||||
|
||||
# c = RPCClient()
|
||||
# c.connect('127.0.0.1', 5003)
|
||||
# print(c.start('1'))
|
||||
# print(c.add(1, 2, 3))
|
||||
# print(c.setData({"sss": "ssss", "list": [1, 2, 3, 4]}))
|
||||
|
154
app/services/RpcService.py
Normal file
154
app/services/RpcService.py
Normal file
@ -0,0 +1,154 @@
|
||||
"""
|
||||
@Time : 2022/9/30 11:28
|
||||
@Auth : 东
|
||||
@File :RpcService.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:RPC服务端
|
||||
|
||||
"""
|
||||
import asyncio
|
||||
import json
|
||||
import socket
|
||||
from functools import wraps
|
||||
|
||||
from app.schemas.TrainResult import ProcessValueList, Report
|
||||
from app.utils.RedisMQTool import Task
|
||||
from app.utils.StandardizedOutput import output_wrapped
|
||||
from app.utils.redis_config import redis_client
|
||||
|
||||
funcs = {}
|
||||
|
||||
|
||||
def register_function(func):
|
||||
"""
|
||||
server端方法注册,client端只能调用注册的方法
|
||||
"""
|
||||
name = func.__name__
|
||||
funcs[name] = func
|
||||
|
||||
|
||||
def mq_send(func, *args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
print(data)
|
||||
|
||||
|
||||
|
||||
class TCPServer(object):
|
||||
|
||||
def __init__(self):
|
||||
self.sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
|
||||
self.client_socket = None
|
||||
|
||||
def bind_listen(self, port=4999):
|
||||
self.sock.bind(('0.0.0.0', port))
|
||||
self.sock.listen(5)
|
||||
|
||||
def accept_receive_close(self):
|
||||
"""
|
||||
接收client的消息
|
||||
"""
|
||||
if self.client_socket is None:
|
||||
(self.client_socket, address) = self.sock.accept()
|
||||
if self.client_socket:
|
||||
msg = self.client_socket.recv(1024)
|
||||
data = self.on_msg(msg)
|
||||
self.client_socket.send(data)
|
||||
|
||||
def on_msg(self, msg):
|
||||
pass
|
||||
|
||||
|
||||
class RPCStub(object):
|
||||
def __init__(self):
|
||||
self.data = None
|
||||
|
||||
def call_method(self, data):
|
||||
"""
|
||||
解析函数,调用对应的方法便将该方法的执行结果返回
|
||||
"""
|
||||
if len(data) == 0:
|
||||
return json.dumps("something wrong").encode('utf-8')
|
||||
self.data = json.loads(data.decode('utf-8'))
|
||||
method_name = self.data['method_name']
|
||||
method_args = self.data['method_args']
|
||||
method_kwargs = self.data['method_kwargs']
|
||||
res = funcs[method_name](*method_args, **method_kwargs)
|
||||
return json.dumps(res).encode('utf-8')
|
||||
|
||||
|
||||
class RPCServer(TCPServer, RPCStub):
|
||||
def __init__(self):
|
||||
TCPServer.__init__(self)
|
||||
RPCStub.__init__(self)
|
||||
|
||||
def loop(self, port):
|
||||
"""
|
||||
循环监听 4999端口
|
||||
"""
|
||||
self.bind_listen(port)
|
||||
while True:
|
||||
try:
|
||||
self.accept_receive_close()
|
||||
except Exception:
|
||||
self.client_socket.close()
|
||||
self.client_socket = None
|
||||
print(Exception)
|
||||
continue
|
||||
|
||||
def on_msg(self, data):
|
||||
return self.call_method(data)
|
||||
|
||||
|
||||
def redisMQSend():
|
||||
def wrapTheFunction(func):
|
||||
@wraps(func)
|
||||
def wrapped_function(*args, **kwargs):
|
||||
data = func(*args, **kwargs)
|
||||
print(data)
|
||||
Task(redis_conn=redis_client.get_redis(), channel="ceshi").publish_task(data=output_wrapped(0, 'success', data))
|
||||
|
||||
return wrapped_function
|
||||
|
||||
return wrapTheFunction
|
||||
|
||||
|
||||
@register_function
|
||||
def add(a, b, c=10):
|
||||
sum = a + b + c
|
||||
print(sum)
|
||||
return sum
|
||||
|
||||
|
||||
@register_function
|
||||
def start(param: str):
|
||||
"""
|
||||
例子
|
||||
"""
|
||||
print(param)
|
||||
process_value_list = ProcessValueList(name='1', value=[])
|
||||
report = Report(rate_of_progess=0, process_value=[process_value_list])
|
||||
|
||||
@mq_send
|
||||
def process(v: int):
|
||||
print(v)
|
||||
report.rate_of_progess = ((v + 1) / 10) * 100
|
||||
report.process_value[0].value.append(v)
|
||||
|
||||
for i in range(10):
|
||||
process(i)
|
||||
print(report.dict())
|
||||
return report.dict()
|
||||
|
||||
|
||||
@register_function
|
||||
def setData(data):
|
||||
print(data)
|
||||
return data
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
# 开启redis连接
|
||||
redis_client.init_redis_connect()
|
||||
s = RPCServer()
|
||||
s.loop(5003) # 传入要监听的端口
|
134
app/services/TokenAuthService.py
Normal file
134
app/services/TokenAuthService.py
Normal file
@ -0,0 +1,134 @@
|
||||
import datetime
|
||||
from functools import wraps
|
||||
|
||||
from flask import g, jsonify, request
|
||||
|
||||
import jwt
|
||||
from app.configs.default import SECRET_KEY
|
||||
from flask_httpauth import HTTPTokenAuth, HTTPAuth
|
||||
|
||||
# 生成token,有效时间为 60*60 秒
|
||||
from app.exts import db
|
||||
|
||||
|
||||
def generate_auth_token(user_name, expiration=3600):
|
||||
reset_token = jwt.encode(
|
||||
{
|
||||
"user_name": user_name,
|
||||
"exp": datetime.datetime.now(tz=datetime.timezone.utc) + datetime.timedelta(seconds=expiration)
|
||||
},
|
||||
SECRET_KEY,
|
||||
algorithm="HS256"
|
||||
)
|
||||
return reset_token
|
||||
|
||||
|
||||
# 重写 HTTPTokenAuth
|
||||
class HTTPTokenAuthReReturn(HTTPTokenAuth):
|
||||
def __init__(self, scheme=None, realm=None, header=None):
|
||||
super().__init__(scheme, realm, header)
|
||||
|
||||
# 重写default_auth_error, 或者也可以重新定义一个函数
|
||||
# def default_auth_error(status):
|
||||
# return jsonify(data={}, message="token 错误!", code=status), status
|
||||
|
||||
def default_auth_error(status, message):
|
||||
return jsonify(data={}, message=message, code=status), status
|
||||
|
||||
# 如果重新定义函数的话,这里就传入新定义的函数名
|
||||
super().error_handler(default_auth_error)
|
||||
# 重写 login_required
|
||||
|
||||
def login_required(self, f=None, role=None, optional=None):
|
||||
if f is not None and \
|
||||
(role is not None or optional is not None): # pragma: no cover
|
||||
raise ValueError(
|
||||
'role and optional are the only supported arguments')
|
||||
|
||||
def login_required_internal(f):
|
||||
@wraps(f)
|
||||
def decorated(*args, **kwargs):
|
||||
auth = self.get_auth()
|
||||
|
||||
if request.method != 'OPTIONS':
|
||||
password = self.get_auth_password(auth)
|
||||
|
||||
status = None # 添加状态信息
|
||||
message = None
|
||||
user = self.authenticate(auth, password)
|
||||
# 这里判断verify_token的返回值是否是这里的一员
|
||||
if user in (False, None, 'BadSignature', 'SignatureExpired'):
|
||||
status = 401
|
||||
if user == 'BadSignature':
|
||||
message = "Bad Signature"
|
||||
elif user == 'SignatureExpired':
|
||||
message = "Signature Expired"
|
||||
elif not self.authorize(role, user, auth):
|
||||
status = 403
|
||||
message = "Forbidden"
|
||||
if not optional and status:
|
||||
# Clear TCP receive buffer of any pending data
|
||||
request.data
|
||||
try:
|
||||
# 因为之前重写了default_auth_error所以多传入一个message
|
||||
return self.auth_error_callback(status, message)
|
||||
except TypeError:
|
||||
return self.auth_error_callback()
|
||||
|
||||
g.flask_httpauth_user = user if user is not True \
|
||||
else auth.username if auth else None
|
||||
return f(*args, **kwargs)
|
||||
|
||||
return decorated
|
||||
|
||||
if f:
|
||||
return login_required_internal(f)
|
||||
return login_required_internal
|
||||
|
||||
|
||||
auth = HTTPTokenAuthReReturn(scheme="Bearer")
|
||||
|
||||
|
||||
# 获取用户权限
|
||||
@auth.get_user_roles
|
||||
def get_user_roles(user):
|
||||
the_role = get_role_token(user["token"])
|
||||
return the_role.role_key
|
||||
|
||||
|
||||
# 验证token
|
||||
@auth.verify_token
|
||||
def verify_token(token):
|
||||
try:
|
||||
print(token)
|
||||
data = jwt.decode(token, SECRET_KEY, algorithms=["HS256"])
|
||||
print(data)
|
||||
except jwt.ExpiredSignatureError:
|
||||
print("token过期")
|
||||
# 这里不用False,而是用自定义字符串
|
||||
return "SignatureExpired"
|
||||
except jwt.PyJWTError:
|
||||
print("token错误")
|
||||
# 这里不用False,而是用自定义字符串
|
||||
return "BadSignature"
|
||||
return True
|
||||
|
||||
|
||||
# 解析token不加密部分
|
||||
def token_parse(token):
|
||||
the_token = str.replace(str(token), 'Bearer ', '')
|
||||
decoded = jwt.decode(the_token, options={"verify_signature": False})
|
||||
return decoded
|
||||
|
||||
|
||||
# 根据 username 获取角色
|
||||
def get_role_username(username: str):
|
||||
return []
|
||||
|
||||
|
||||
# 根据 username 获取角色
|
||||
def get_role_token(token: str):
|
||||
user_info = token_parse(token)
|
||||
username = user_info["user_name"]
|
||||
the_role = get_role_username(username)
|
||||
return the_role
|
5
app/services/__init__.py
Normal file
5
app/services/__init__.py
Normal file
@ -0,0 +1,5 @@
|
||||
from app.core.common_utils import import_subs
|
||||
|
||||
__all__ = import_subs(locals())
|
||||
|
||||
|
125
app/utils/DateTimeUtil.py
Normal file
125
app/utils/DateTimeUtil.py
Normal file
@ -0,0 +1,125 @@
|
||||
# coding:utf-8
|
||||
import time
|
||||
import datetime
|
||||
|
||||
|
||||
def gap_day(time_str, date=None, format="%Y-%m-%d"):
|
||||
"""
|
||||
:判断自然日差几天
|
||||
:param time_str: 2019-02-19 21:49:20
|
||||
:return:
|
||||
"""
|
||||
if not date:
|
||||
date = time.strftime(format)
|
||||
now_day_stamps = time.mktime(time.strptime(date, format))
|
||||
if " " in format:
|
||||
format = format.split(" ")[0]
|
||||
input_stamps = time.mktime(time.strptime(time_str.split(" ")[0], format))
|
||||
return int(abs((now_day_stamps - input_stamps)) // 86400)
|
||||
|
||||
|
||||
def gap_stamps_day(time_str, now_day_stamps=None):
|
||||
"""
|
||||
:判断绝对时间差几天
|
||||
:param time_str: 2019-02-19 21:49:20
|
||||
:return:
|
||||
"""
|
||||
if not now_day_stamps:
|
||||
now_day_stamps = time.time()
|
||||
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
|
||||
return int(abs((now_day_stamps - input_stamps)) // 86400)
|
||||
|
||||
|
||||
def gap_stamps_hour(time_str):
|
||||
"""
|
||||
:判断绝对上差几个小时
|
||||
:param time_str: 2019-02-19 21:49:20
|
||||
:return:
|
||||
"""
|
||||
now = int(time.time())
|
||||
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
|
||||
return int(abs((now - input_stamps)) // 3600)
|
||||
|
||||
|
||||
def gap_stamps_minute(time_str):
|
||||
"""
|
||||
:判断绝对上差几个分钟
|
||||
:param time_str: 2019-02-19 21:49:20
|
||||
:return:
|
||||
"""
|
||||
now = int(time.time())
|
||||
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
|
||||
return int(abs((now - input_stamps)) // 60)
|
||||
|
||||
|
||||
def get_now():
|
||||
"""
|
||||
获取当前时间 YYYY-MM-DD HH:mm:ss
|
||||
:param
|
||||
:return:
|
||||
"""
|
||||
current_time = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
|
||||
return current_time
|
||||
|
||||
|
||||
def get_time_stamp(timeStr, format="%Y-%m-%d %H:%M:%S"):
|
||||
"""
|
||||
获取时间戳
|
||||
:param timeStr: 2019-05-12 09:00:00
|
||||
:param format: "%Y-%m-%d %H:%M:%S"
|
||||
:return:
|
||||
"""
|
||||
timeArray = time.strptime(timeStr, format)
|
||||
timestamp = time.mktime(timeArray)
|
||||
return int(timestamp)
|
||||
|
||||
|
||||
def gap_stamps_sec(time_str):
|
||||
"""
|
||||
:判断绝对上差几秒
|
||||
:param time_str: 2019-02-19 21:49:20
|
||||
:return:
|
||||
"""
|
||||
|
||||
now = int(time.time())
|
||||
input_stamps = time.mktime(time.strptime(time_str, "%Y-%m-%d %H:%M:%S"))
|
||||
return int(abs((now - input_stamps)))
|
||||
|
||||
|
||||
def get_day_jia(date, n, format='%Y-%m-%d'):
|
||||
"""
|
||||
时间加n天
|
||||
:param date:
|
||||
:param n:
|
||||
:return:
|
||||
"""
|
||||
jia_date = datetime.datetime.strptime(date, format)
|
||||
jia_date = jia_date + datetime.timedelta(days=n)
|
||||
return jia_date.strftime(format)
|
||||
|
||||
|
||||
def get_sec_jia(seconds, format="%Y-%m-%d %H:%M:%S"):
|
||||
"""
|
||||
当前时间加多少秒
|
||||
:param seconds:
|
||||
:param format:
|
||||
:return: 2019-12-30 19:25:30
|
||||
"""
|
||||
return (datetime.datetime.now() + datetime.timedelta(seconds=seconds)).strftime(format)
|
||||
|
||||
|
||||
def get_ts_to_time(ts):
|
||||
"""时间戳转字符串"""
|
||||
return time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(ts))
|
||||
|
||||
|
||||
def day_long(time1, time2):
|
||||
"""
|
||||
计算时间差
|
||||
:return: 相差的天数
|
||||
"""
|
||||
ts1 = get_time_stamp(time1)
|
||||
ts2 = get_time_stamp(time2)
|
||||
date1 = datetime.datetime.fromtimestamp(ts1)
|
||||
date2 = datetime.datetime.fromtimestamp(ts2)
|
||||
return abs(int((date2 - date1).days))
|
24
app/utils/EncryptionTool.py
Normal file
24
app/utils/EncryptionTool.py
Normal file
@ -0,0 +1,24 @@
|
||||
import hashlib
|
||||
import uuid
|
||||
|
||||
|
||||
def sha256_encode(contents: str):
|
||||
res = hashlib.sha256(b"%b" % contents.encode("utf8")).hexdigest()
|
||||
return res
|
||||
|
||||
|
||||
def sha3_256_encode(contents: str):
|
||||
res = hashlib.sha3_256(b"%b" % contents.encode("utf8")).hexdigest()
|
||||
return res
|
||||
|
||||
|
||||
def generate_uuid():
|
||||
return uuid.uuid4()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(hashlib.algorithms_guaranteed)
|
||||
print(hashlib.algorithms_available)
|
||||
print(sha256("res"))
|
||||
print(sha3_256("res" + generate_uuid().hex))
|
||||
print(generate_uuid().hex)
|
21
app/utils/JSONEncodeTools.py
Normal file
21
app/utils/JSONEncodeTools.py
Normal file
@ -0,0 +1,21 @@
|
||||
"""
|
||||
@Time : 2022/10/17 10:12
|
||||
@Auth : 东
|
||||
@File :JSONEncodeTools.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
import datetime
|
||||
import json
|
||||
|
||||
|
||||
class MyEncoder(json.JSONEncoder):
|
||||
def default(self, obj):
|
||||
if isinstance(obj, bytes):
|
||||
return str(obj, encoding='utf-8')
|
||||
if isinstance(obj, datetime.datetime):
|
||||
return str(obj)
|
||||
|
||||
return json.JSONEncoder.default(self, obj)
|
42
app/utils/RedisMQTool.py
Normal file
42
app/utils/RedisMQTool.py
Normal file
@ -0,0 +1,42 @@
|
||||
"""
|
||||
@Time : 2022/10/9 17:50
|
||||
@Auth : 东
|
||||
@File :RedisMQTool.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
import json
|
||||
|
||||
import redis
|
||||
|
||||
|
||||
class Task(object):
|
||||
|
||||
def __init__(self, redis_conn, channel):
|
||||
self.rcon = redis_conn
|
||||
self.ps = self.rcon.pubsub()
|
||||
self.key = 'task:pubsub:%s' % channel
|
||||
self.ps.subscribe(self.key)
|
||||
|
||||
def listen_task(self):
|
||||
for i in self.ps.listen():
|
||||
if i['type'] == 'message':
|
||||
print("Task get ", i["data"])
|
||||
|
||||
def publish_task(self, data):
|
||||
self.rcon.publish(self.key, json.dumps(data))
|
||||
|
||||
def del_listen(self):
|
||||
self.ps.unsubscribe(self.key)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
print("listen task channel")
|
||||
|
||||
pool = redis.ConnectionPool(host='127.0.0.1',
|
||||
port=6379, db=5,)
|
||||
|
||||
redis_conn = redis.StrictRedis(connection_pool=pool)
|
||||
Task(redis_conn, 'channel').listen_task()
|
95
app/utils/SimpleSqlite3Tool.py
Normal file
95
app/utils/SimpleSqlite3Tool.py
Normal file
@ -0,0 +1,95 @@
|
||||
# coding: utf-8
|
||||
# Author:tajochen
|
||||
|
||||
import sqlite3
|
||||
import os
|
||||
|
||||
|
||||
class SimpleSQLite3Tool:
|
||||
"""
|
||||
simpleToolSql for sqlite3
|
||||
简单数据库工具类
|
||||
编写这个类主要是为了封装sqlite,继承此类复用方法
|
||||
"""
|
||||
|
||||
|
||||
def __init__(self, filename="stsql"):
|
||||
"""
|
||||
初始化数据库,默认文件名 stsql.db
|
||||
filename:文件名
|
||||
"""
|
||||
self.filename = filename
|
||||
self.db = sqlite3.connect(self.filename)
|
||||
self.c = self.db.cursor()
|
||||
|
||||
|
||||
def close(self):
|
||||
"""
|
||||
关闭数据库
|
||||
"""
|
||||
self.c.close()
|
||||
self.db.close()
|
||||
|
||||
|
||||
def execute(self, sql, param=None):
|
||||
"""
|
||||
执行数据库的增、删、改
|
||||
sql:sql语句
|
||||
param:数据,可以是list或tuple,亦可是None
|
||||
return:成功返回True
|
||||
"""
|
||||
try:
|
||||
if param is None:
|
||||
self.c.execute(sql)
|
||||
else:
|
||||
if type(param) is list:
|
||||
self.c.executemany(sql, param)
|
||||
else:
|
||||
self.c.execute(sql, param)
|
||||
count = self.db.total_changes
|
||||
self.db.commit()
|
||||
except Exception as e:
|
||||
print(e)
|
||||
return False, e
|
||||
if count > 0:
|
||||
return True
|
||||
else:
|
||||
return False
|
||||
|
||||
|
||||
def query(self, sql, param=None):
|
||||
"""
|
||||
查询语句
|
||||
sql:sql语句
|
||||
param:参数,可为None
|
||||
return:成功返回True
|
||||
"""
|
||||
if param is None:
|
||||
self.c.execute(sql)
|
||||
else:
|
||||
self.c.execute(sql, param)
|
||||
return self.c.fetchall()
|
||||
|
||||
|
||||
# def set(self,table,field=" * ",where="",isWhere=False):
|
||||
# self.table = table
|
||||
# self.filed = field
|
||||
# if where != "" :
|
||||
# self.where = where
|
||||
# self.isWhere = True
|
||||
# return True
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 数据库文件位置
|
||||
sql = SimpleSQLite3Tool("../test.db")
|
||||
f = sql.execute("create table test (id int not null,name text not null,age int);")
|
||||
print("ok")
|
||||
sql.execute("insert into test (id,name,age) values (?,?,?);", [(1, 'abc', 15), (2, 'bca', 16)])
|
||||
res = sql.query("select * from test;")
|
||||
print(res)
|
||||
sql.execute("insert into test (id,name) values (?,?);", (3, 'bac'))
|
||||
res = sql.query("select * from test where id=?;", (3,))
|
||||
res = sql.query("select * from data_collection_info;")
|
||||
print(res)
|
||||
sql.close()
|
82
app/utils/SnowflakeTool.py
Normal file
82
app/utils/SnowflakeTool.py
Normal file
@ -0,0 +1,82 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@author: cxyfreedom
|
||||
@desc: 基于 snowflake 生成分布式ID
|
||||
"""
|
||||
import time
|
||||
|
||||
# 每一部分占用的位数
|
||||
TIMESTAMP_BIT = 41 # 时间戳占用位数
|
||||
MACHINE_BIT = 5 # 机器标识占用的位数
|
||||
DATACENTER_BIT = 5 # 数据中心占用的位数
|
||||
SEQUENCE_BIT = 12 # 序列号占用的位数
|
||||
|
||||
# 每一部分的最大值
|
||||
MAX_DATACENTER_NUM = -1 ^ (-1 << DATACENTER_BIT)
|
||||
MAX_MACHINE_NUM = -1 ^ (-1 << MACHINE_BIT)
|
||||
MAX_SEQUENCE = -1 ^ (-1 << SEQUENCE_BIT)
|
||||
|
||||
# 每一部分向左的位移
|
||||
MACHINE_LEFT = SEQUENCE_BIT
|
||||
DATACENTER_LEFT = MACHINE_BIT + SEQUENCE_BIT
|
||||
TIMESTAMP_LEFT = DATACENTER_LEFT + DATACENTER_BIT
|
||||
|
||||
|
||||
class SnowFlake:
|
||||
class OverflowError(TypeError):
|
||||
"""
|
||||
分布式ID生成算法占位符溢出异常,会导致生成ID为负数
|
||||
"""
|
||||
pass
|
||||
|
||||
class RuntimeError(TypeError):
|
||||
"""
|
||||
运行时间错误,在此项目中当前运行时间小于上一次运行时间。
|
||||
"""
|
||||
pass
|
||||
|
||||
def __init__(self):
|
||||
if TIMESTAMP_BIT + SEQUENCE_BIT + MACHINE_BIT + DATACENTER_BIT != 63:
|
||||
raise self.OverflowError(
|
||||
"TIMESTAMP_BIT + SEQUENCE_BIT + MACHINE_BIT + DATACENTER_BIT not equal to 63bit")
|
||||
self.datacenter_id = 0 # 数据中心编号
|
||||
self.machineId = 0 # 机器标识编号
|
||||
self.sequence = 0 # 序列号
|
||||
self.last_stamp = -1 # 上一次时间戳
|
||||
|
||||
def nextId(self):
|
||||
"""生成下一个ID"""
|
||||
cur_stamp = self.get_new_stamp()
|
||||
if cur_stamp < self.last_stamp:
|
||||
raise self.RuntimeError(
|
||||
"Clock moved backwards. Refusing to generate id")
|
||||
|
||||
if cur_stamp == self.last_stamp:
|
||||
# 相同毫秒内,序列号自增
|
||||
self.sequence = (self.sequence + 1) & MAX_SEQUENCE
|
||||
# 同一秒的序列数已经达到最大
|
||||
if self.sequence == 0:
|
||||
cur_stamp = self.get_next_mill()
|
||||
else:
|
||||
# 不同秒内,序列号为0
|
||||
self.sequence = 0
|
||||
|
||||
self.last_stamp = cur_stamp
|
||||
return (cur_stamp << TIMESTAMP_LEFT) | (
|
||||
self.datacenter_id << DATACENTER_LEFT) | (
|
||||
self.machineId << MACHINE_LEFT) | self.sequence
|
||||
|
||||
def get_next_mill(self):
|
||||
mill = self.get_new_stamp()
|
||||
while mill <= self.last_stamp:
|
||||
mill = self.get_new_stamp()
|
||||
return mill
|
||||
|
||||
@staticmethod
|
||||
def get_new_stamp():
|
||||
now = lambda: int(time.time() * 1000)
|
||||
return now()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
print(SnowFlake().nextId())
|
5
app/utils/StandardizedOutput.py
Normal file
5
app/utils/StandardizedOutput.py
Normal file
@ -0,0 +1,5 @@
|
||||
from flask import jsonify
|
||||
|
||||
|
||||
def output_wrapped(status: int = 0, message: str = "", data: object = None):
|
||||
return jsonify(code=status, message=message, data=data)
|
53
app/utils/UDPReceive.py
Normal file
53
app/utils/UDPReceive.py
Normal file
@ -0,0 +1,53 @@
|
||||
#!/usr/bin/python3
|
||||
# coding= utf-8
|
||||
|
||||
import socket
|
||||
import sys
|
||||
import struct
|
||||
import json
|
||||
|
||||
# 本机信息
|
||||
import time
|
||||
|
||||
host_ip = socket.gethostbyname(socket.gethostname())
|
||||
# 组播组IP和端口
|
||||
mcast_group_ip = '224.1.1.1'
|
||||
mcast_group_port = 2234
|
||||
|
||||
|
||||
def receiver():
|
||||
# 建立接收 udp socket
|
||||
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
# linux能绑定网卡这里绑定组播IP地址不会服错,windows没法绑定网卡只能绑定本网卡IP地址
|
||||
if "linux" in sys.platform:
|
||||
# 绑定到的网卡名,如果自己的不是eth0则修改
|
||||
nic_name = 0
|
||||
# 监听的组播地址
|
||||
sock.setsockopt(socket.SOL_SOCKET, 25, nic_name)
|
||||
sock.bind((mcast_group_ip, mcast_group_port))
|
||||
else:
|
||||
sock.bind((host_ip, mcast_group_port))
|
||||
# 加入组播组
|
||||
mq_request = struct.pack("=4sl", socket.inet_aton(mcast_group_ip), socket.INADDR_ANY)
|
||||
sock.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, mq_request)
|
||||
# 设置非阻塞
|
||||
sock.setblocking(True)
|
||||
while True:
|
||||
try:
|
||||
data, address = sock.recvfrom(4096)
|
||||
data2 = json.loads(data)
|
||||
# 若组播数据不正确
|
||||
if len(data2) < 3:
|
||||
return
|
||||
except socket.error as e:
|
||||
print(f"while receive message error occur:{e}")
|
||||
else:
|
||||
print("Receive Data!")
|
||||
print("FROM: ", address)
|
||||
print("DATA: ", data.decode('utf-8'))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
receiver()
|
32
app/utils/UDPSender.py
Normal file
32
app/utils/UDPSender.py
Normal file
@ -0,0 +1,32 @@
|
||||
#!/usr/bin/python3
|
||||
# coding= utf-8
|
||||
|
||||
import time
|
||||
import struct
|
||||
import socket
|
||||
|
||||
# 本机信息
|
||||
host_ip = socket.gethostname()
|
||||
host_port = 6501
|
||||
# 组播组IP和端口
|
||||
mcast_group_ip = '239.255.255.252'
|
||||
mcast_group_port = 5678
|
||||
|
||||
|
||||
def sender():
|
||||
send_sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)
|
||||
send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_BROADCAST, 1)
|
||||
send_sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
|
||||
send_sock.bind((host_ip, host_port))
|
||||
# 设置存活时长
|
||||
ttl_bin = struct.pack('@i', 255)
|
||||
send_sock.setsockopt(socket.IPPROTO_IP, socket.IP_MULTICAST_TTL, ttl_bin)
|
||||
while True:
|
||||
data = '12345 english 汉字#测试'
|
||||
send_sock.sendto(str(data).encode('utf-8'), (mcast_group_ip, mcast_group_port))
|
||||
print(f'{time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())}: send finish.')
|
||||
time.sleep(10)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sender()
|
29
app/utils/WebsocketClient.py
Normal file
29
app/utils/WebsocketClient.py
Normal file
@ -0,0 +1,29 @@
|
||||
"""
|
||||
@Time : 2022/10/11 16:43
|
||||
@Auth : 东
|
||||
@File :WebsocketClient.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
from threading import Thread
|
||||
|
||||
import websocket
|
||||
|
||||
def connect(self, apiKey, secretKey, trace=False):
|
||||
self.host = OKEX_USD_CONTRACT
|
||||
self.apiKey = apiKey
|
||||
self.secretKey = secretKey
|
||||
self.trace = trace
|
||||
|
||||
websocket.enableTrace(trace)
|
||||
|
||||
self.ws = websocket.WebSocketApp(self.host,
|
||||
on_message=self.onMessage,
|
||||
on_error=self.onError,
|
||||
on_close=self.onClose,
|
||||
on_open=self.onOpen)
|
||||
|
||||
self.thread = Thread(target=self.ws.run_forever, args=(None, None, 60, 30))
|
||||
self.thread.start()
|
40
app/utils/YamlTool.py
Normal file
40
app/utils/YamlTool.py
Normal file
@ -0,0 +1,40 @@
|
||||
import yaml
|
||||
import os
|
||||
|
||||
|
||||
# 单个文档
|
||||
def get_yaml_data(yaml_file):
|
||||
# 打开yaml文件
|
||||
file = open(yaml_file, 'r', encoding='utf-8')
|
||||
file_data = file.read()
|
||||
file.close()
|
||||
# 将字符串转化为字典或列表
|
||||
data = yaml.safe_load(file_data) # safe_load,safe_load,unsafe_load
|
||||
return data
|
||||
|
||||
|
||||
# yaml文件中含多个文档时,分别获取文档中数据
|
||||
def get_yaml_load_all(yaml_file):
|
||||
# 打开文件
|
||||
file = open(yaml_file, 'r', encoding='utf-8')
|
||||
file_data = file.read()
|
||||
file.close()
|
||||
|
||||
all_data = yaml.load_all(file_data, Loader=yaml.FullLoader)
|
||||
for data in all_data:
|
||||
print('data-----', data)
|
||||
|
||||
|
||||
# 生成yaml文档
|
||||
def generate_yaml_doc(yaml_file):
|
||||
py_ob = {"school": "zhang", "students": ['a', 'b']}
|
||||
file = open(yaml_file, 'w', encoding='utf-8')
|
||||
yaml.dump(py_ob, file)
|
||||
file.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
current_path = os.path.abspath("../../")
|
||||
yaml_path = os.path.join(current_path, "config.yaml")
|
||||
print('--------------------', yaml_path)
|
||||
get_yaml_data(yaml_path)
|
0
app/utils/__init__.py
Normal file
0
app/utils/__init__.py
Normal file
66
app/utils/redis_config.py
Normal file
66
app/utils/redis_config.py
Normal file
@ -0,0 +1,66 @@
|
||||
"""
|
||||
redis 配置类
|
||||
"""
|
||||
import sys
|
||||
|
||||
import redis
|
||||
|
||||
from ..configs import default
|
||||
|
||||
|
||||
class RedisCli(object):
|
||||
|
||||
def __init__(self, *, host: str, port: str, password: str, db: int, socket_timeout=5):
|
||||
# redis对象,在 @app.on_event('startup') 中连接创建
|
||||
self._redis_client = None
|
||||
self.host = host
|
||||
self.port = port
|
||||
self.password = password
|
||||
self.db = db
|
||||
self.socket_timeout = socket_timeout
|
||||
|
||||
def init_redis_connect(self) -> None:
|
||||
"""
|
||||
初始化链接
|
||||
:return:
|
||||
"""
|
||||
try:
|
||||
r = redis.ConnectionPool(
|
||||
host=self.host,
|
||||
port=self.port,
|
||||
password=self.password,
|
||||
db=self.db,
|
||||
socket_timeout=self.socket_timeout,
|
||||
decode_responses=True # 解码
|
||||
)
|
||||
self._redis_client = redis.StrictRedis(connection_pool=r)
|
||||
if not self._redis_client.ping():
|
||||
print('连接超时')
|
||||
sys.exit()
|
||||
except (redis.AuthenticationError, Exception) as e:
|
||||
print('连接redis异常')
|
||||
sys.exit()
|
||||
|
||||
def get_redis(self):
|
||||
return self._redis_client
|
||||
|
||||
# 使实例化后的对象,赋予redis对象的方法和属性
|
||||
def __getattr__(self, item):
|
||||
return self._redis_client.has_key(item)
|
||||
|
||||
def __getitem__(self, item):
|
||||
return self._redis_client[item]
|
||||
|
||||
def __setitem__(self, key, value):
|
||||
self._redis_client[key] = value
|
||||
|
||||
def __delitem__(self, key):
|
||||
del self._redis_client[key]
|
||||
|
||||
|
||||
redis_client = RedisCli(
|
||||
host=default.db['host'],
|
||||
port=default.db['port'],
|
||||
password=default.db['password'],
|
||||
db=default.db['db'],
|
||||
)
|
60
app/utils/websocket_tool.py
Normal file
60
app/utils/websocket_tool.py
Normal file
@ -0,0 +1,60 @@
|
||||
"""
|
||||
@Time : 2022/10/12 17:55
|
||||
@Auth : 东
|
||||
@File :websocket_tool.py
|
||||
@IDE :PyCharm
|
||||
@Motto:ABC(Always Be Coding)
|
||||
@Desc:
|
||||
|
||||
"""
|
||||
import json
|
||||
from typing import Union, List, Dict
|
||||
|
||||
from app.core.common_utils import logger
|
||||
from app.utils.JSONEncodeTools import MyEncoder
|
||||
|
||||
|
||||
class WebsocketUtil:
|
||||
def __init__(self):
|
||||
self.active_connections: List = []
|
||||
self.active_connections_dist: Dict = {}
|
||||
|
||||
def connect(self, ws, id: str):
|
||||
# 等待连接
|
||||
msg = ws.receive()
|
||||
# 存储ws连接对象
|
||||
self.active_connections.append(ws)
|
||||
if id in self.active_connections_dist:
|
||||
self.active_connections_dist[id].append(ws)
|
||||
else:
|
||||
ws_list = [ws, ]
|
||||
self.active_connections_dist[id] = ws_list
|
||||
|
||||
def disconnect(self, ws, id):
|
||||
# ws关闭时 移除ws对象
|
||||
if ws.closed:
|
||||
if ws in self.active_connections_dist.values():
|
||||
self.active_connections.remove(ws)
|
||||
self.active_connections_dist[id].pop(ws)
|
||||
|
||||
@staticmethod
|
||||
async def send_personal_message(message: str, ws):
|
||||
# 发送个人消息
|
||||
await ws.send(message)
|
||||
|
||||
def broadcast(self, message: str):
|
||||
# 广播消息
|
||||
for connection in self.active_connections:
|
||||
connection.send(message)
|
||||
|
||||
def send_message_proj_json(self, message: Union[str, int, List, Dict], id: str):
|
||||
# 广播该项目的消息
|
||||
for connection in self.active_connections_dist[id]:
|
||||
try:
|
||||
connection.send(json.dumps(message, cls=MyEncoder, indent=4), )
|
||||
except Exception as e:
|
||||
logger.error("websocket异常断开,{}", e)
|
||||
self.disconnect(ws=connection, id=id)
|
||||
|
||||
|
||||
manager = WebsocketUtil()
|
222
app/yolov5/.dockerignore
Normal file
222
app/yolov5/.dockerignore
Normal file
@ -0,0 +1,222 @@
|
||||
# Repo-specific DockerIgnore -------------------------------------------------------------------------------------------
|
||||
.git
|
||||
.cache
|
||||
.idea
|
||||
runs
|
||||
output
|
||||
coco
|
||||
storage.googleapis.com
|
||||
|
||||
data/samples/*
|
||||
**/results*.csv
|
||||
*.jpg
|
||||
|
||||
# Neural Network weights -----------------------------------------------------------------------------------------------
|
||||
**/*.pt
|
||||
**/*.pth
|
||||
**/*.onnx
|
||||
**/*.engine
|
||||
**/*.mlmodel
|
||||
**/*.torchscript
|
||||
**/*.torchscript.pt
|
||||
**/*.tflite
|
||||
**/*.h5
|
||||
**/*.pb
|
||||
*_saved_model/
|
||||
*_web_model/
|
||||
*_openvino_model/
|
||||
|
||||
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
||||
# Below Copied From .gitignore -----------------------------------------------------------------------------------------
|
||||
|
||||
|
||||
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
wandb/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# dotenv
|
||||
.env
|
||||
|
||||
# virtualenv
|
||||
.venv*
|
||||
venv*/
|
||||
ENV*/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
|
||||
|
||||
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
||||
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
Icon?
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
|
||||
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff:
|
||||
.idea/*
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/dictionaries
|
||||
.html # Bokeh Plots
|
||||
.pg # TensorFlow Frozen Graphs
|
||||
.avi # videos
|
||||
|
||||
# Sensitive or high-churn files:
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
|
||||
# Gradle:
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# CMake
|
||||
cmake-build-debug/
|
||||
cmake-build-release/
|
||||
|
||||
# Mongo Explorer plugin:
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
## File-based project format:
|
||||
*.iws
|
||||
|
||||
## Plugin-specific files:
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
2
app/yolov5/.gitattributes
vendored
Normal file
2
app/yolov5/.gitattributes
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
# this drop notebooks from GitHub language stats
|
||||
*.ipynb linguist-vendored
|
128
app/yolov5/.github/CODE_OF_CONDUCT.md
vendored
Normal file
128
app/yolov5/.github/CODE_OF_CONDUCT.md
vendored
Normal file
@ -0,0 +1,128 @@
|
||||
# YOLOv5 🚀 Contributor Covenant Code of Conduct
|
||||
|
||||
## Our Pledge
|
||||
|
||||
We as members, contributors, and leaders pledge to make participation in our
|
||||
community a harassment-free experience for everyone, regardless of age, body
|
||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
||||
identity and expression, level of experience, education, socio-economic status,
|
||||
nationality, personal appearance, race, religion, or sexual identity
|
||||
and orientation.
|
||||
|
||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
||||
diverse, inclusive, and healthy community.
|
||||
|
||||
## Our Standards
|
||||
|
||||
Examples of behavior that contributes to a positive environment for our
|
||||
community include:
|
||||
|
||||
- Demonstrating empathy and kindness toward other people
|
||||
- Being respectful of differing opinions, viewpoints, and experiences
|
||||
- Giving and gracefully accepting constructive feedback
|
||||
- Accepting responsibility and apologizing to those affected by our mistakes,
|
||||
and learning from the experience
|
||||
- Focusing on what is best not just for us as individuals, but for the
|
||||
overall community
|
||||
|
||||
Examples of unacceptable behavior include:
|
||||
|
||||
- The use of sexualized language or imagery, and sexual attention or
|
||||
advances of any kind
|
||||
- Trolling, insulting or derogatory comments, and personal or political attacks
|
||||
- Public or private harassment
|
||||
- Publishing others' private information, such as a physical or email
|
||||
address, without their explicit permission
|
||||
- Other conduct which could reasonably be considered inappropriate in a
|
||||
professional setting
|
||||
|
||||
## Enforcement Responsibilities
|
||||
|
||||
Community leaders are responsible for clarifying and enforcing our standards of
|
||||
acceptable behavior and will take appropriate and fair corrective action in
|
||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
||||
or harmful.
|
||||
|
||||
Community leaders have the right and responsibility to remove, edit, or reject
|
||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
||||
decisions when appropriate.
|
||||
|
||||
## Scope
|
||||
|
||||
This Code of Conduct applies within all community spaces, and also applies when
|
||||
an individual is officially representing the community in public spaces.
|
||||
Examples of representing our community include using an official e-mail address,
|
||||
posting via an official social media account, or acting as an appointed
|
||||
representative at an online or offline event.
|
||||
|
||||
## Enforcement
|
||||
|
||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
||||
reported to the community leaders responsible for enforcement at
|
||||
hello@ultralytics.com.
|
||||
All complaints will be reviewed and investigated promptly and fairly.
|
||||
|
||||
All community leaders are obligated to respect the privacy and security of the
|
||||
reporter of any incident.
|
||||
|
||||
## Enforcement Guidelines
|
||||
|
||||
Community leaders will follow these Community Impact Guidelines in determining
|
||||
the consequences for any action they deem in violation of this Code of Conduct:
|
||||
|
||||
### 1. Correction
|
||||
|
||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
||||
unprofessional or unwelcome in the community.
|
||||
|
||||
**Consequence**: A private, written warning from community leaders, providing
|
||||
clarity around the nature of the violation and an explanation of why the
|
||||
behavior was inappropriate. A public apology may be requested.
|
||||
|
||||
### 2. Warning
|
||||
|
||||
**Community Impact**: A violation through a single incident or series
|
||||
of actions.
|
||||
|
||||
**Consequence**: A warning with consequences for continued behavior. No
|
||||
interaction with the people involved, including unsolicited interaction with
|
||||
those enforcing the Code of Conduct, for a specified period of time. This
|
||||
includes avoiding interactions in community spaces as well as external channels
|
||||
like social media. Violating these terms may lead to a temporary or
|
||||
permanent ban.
|
||||
|
||||
### 3. Temporary Ban
|
||||
|
||||
**Community Impact**: A serious violation of community standards, including
|
||||
sustained inappropriate behavior.
|
||||
|
||||
**Consequence**: A temporary ban from any sort of interaction or public
|
||||
communication with the community for a specified period of time. No public or
|
||||
private interaction with the people involved, including unsolicited interaction
|
||||
with those enforcing the Code of Conduct, is allowed during this period.
|
||||
Violating these terms may lead to a permanent ban.
|
||||
|
||||
### 4. Permanent Ban
|
||||
|
||||
**Community Impact**: Demonstrating a pattern of violation of community
|
||||
standards, including sustained inappropriate behavior, harassment of an
|
||||
individual, or aggression toward or disparagement of classes of individuals.
|
||||
|
||||
**Consequence**: A permanent ban from any sort of public interaction within
|
||||
the community.
|
||||
|
||||
## Attribution
|
||||
|
||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
||||
version 2.0, available at
|
||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
||||
|
||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
||||
enforcement ladder](https://github.com/mozilla/diversity).
|
||||
|
||||
For answers to common questions about this code of conduct, see the FAQ at
|
||||
https://www.contributor-covenant.org/faq. Translations are available at
|
||||
https://www.contributor-covenant.org/translations.
|
||||
|
||||
[homepage]: https://www.contributor-covenant.org
|
85
app/yolov5/.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
85
app/yolov5/.github/ISSUE_TEMPLATE/bug-report.yml
vendored
Normal file
@ -0,0 +1,85 @@
|
||||
name: 🐛 Bug Report
|
||||
# title: " "
|
||||
description: Problems with YOLOv5
|
||||
labels: [bug, triage]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for submitting a YOLOv5 🐛 Bug Report!
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Search before asking
|
||||
description: >
|
||||
Please search the [issues](https://github.com/ultralytics/yolov5/issues) to see if a similar bug report already exists.
|
||||
options:
|
||||
- label: >
|
||||
I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and found no similar bug report.
|
||||
required: true
|
||||
|
||||
- type: dropdown
|
||||
attributes:
|
||||
label: YOLOv5 Component
|
||||
description: |
|
||||
Please select the part of YOLOv5 where you found the bug.
|
||||
multiple: true
|
||||
options:
|
||||
- "Training"
|
||||
- "Validation"
|
||||
- "Detection"
|
||||
- "Export"
|
||||
- "PyTorch Hub"
|
||||
- "Multi-GPU"
|
||||
- "Evolution"
|
||||
- "Integrations"
|
||||
- "Other"
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Bug
|
||||
description: Provide console output with error messages and/or screenshots of the bug.
|
||||
placeholder: |
|
||||
💡 ProTip! Include as much information as possible (screenshots, logs, tracebacks etc.) to receive the most helpful response.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Environment
|
||||
description: Please specify the software and hardware you used to produce the bug.
|
||||
placeholder: |
|
||||
- YOLO: YOLOv5 🚀 v6.0-67-g60e42e1 torch 1.9.0+cu111 CUDA:0 (A100-SXM4-40GB, 40536MiB)
|
||||
- OS: Ubuntu 20.04
|
||||
- Python: 3.9.0
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Minimal Reproducible Example
|
||||
description: >
|
||||
When asking a question, people will be better able to provide help if you provide code that they can easily understand and use to **reproduce** the problem.
|
||||
This is referred to by community members as creating a [minimal reproducible example](https://stackoverflow.com/help/minimal-reproducible-example).
|
||||
placeholder: |
|
||||
```
|
||||
# Code to reproduce your issue here
|
||||
```
|
||||
validations:
|
||||
required: false
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional
|
||||
description: Anything else you would like to share?
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Are you willing to submit a PR?
|
||||
description: >
|
||||
(Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov5/pulls) (PR) to help improve YOLOv5 for everyone, especially if you have a good understanding of how to implement a fix or feature.
|
||||
See the YOLOv5 [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) to get started.
|
||||
options:
|
||||
- label: Yes I'd like to help by submitting a PR!
|
8
app/yolov5/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
8
app/yolov5/.github/ISSUE_TEMPLATE/config.yml
vendored
Normal file
@ -0,0 +1,8 @@
|
||||
blank_issues_enabled: true
|
||||
contact_links:
|
||||
- name: 💬 Forum
|
||||
url: https://community.ultralytics.com/
|
||||
about: Ask on Ultralytics Community Forum
|
||||
- name: Stack Overflow
|
||||
url: https://stackoverflow.com/search?q=YOLOv5
|
||||
about: Ask on Stack Overflow with 'YOLOv5' tag
|
50
app/yolov5/.github/ISSUE_TEMPLATE/feature-request.yml
vendored
Normal file
50
app/yolov5/.github/ISSUE_TEMPLATE/feature-request.yml
vendored
Normal file
@ -0,0 +1,50 @@
|
||||
name: 🚀 Feature Request
|
||||
description: Suggest a YOLOv5 idea
|
||||
# title: " "
|
||||
labels: [enhancement]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for submitting a YOLOv5 🚀 Feature Request!
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Search before asking
|
||||
description: >
|
||||
Please search the [issues](https://github.com/ultralytics/yolov5/issues) to see if a similar feature request already exists.
|
||||
options:
|
||||
- label: >
|
||||
I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and found no similar feature requests.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Description
|
||||
description: A short description of your feature.
|
||||
placeholder: |
|
||||
What new feature would you like to see in YOLOv5?
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Use case
|
||||
description: |
|
||||
Describe the use case of your feature request. It will help us understand and prioritize the feature request.
|
||||
placeholder: |
|
||||
How would this feature be used, and who would use it?
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional
|
||||
description: Anything else you would like to share?
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Are you willing to submit a PR?
|
||||
description: >
|
||||
(Optional) We encourage you to submit a [Pull Request](https://github.com/ultralytics/yolov5/pulls) (PR) to help improve YOLOv5 for everyone, especially if you have a good understanding of how to implement a fix or feature.
|
||||
See the YOLOv5 [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) to get started.
|
||||
options:
|
||||
- label: Yes I'd like to help by submitting a PR!
|
33
app/yolov5/.github/ISSUE_TEMPLATE/question.yml
vendored
Normal file
33
app/yolov5/.github/ISSUE_TEMPLATE/question.yml
vendored
Normal file
@ -0,0 +1,33 @@
|
||||
name: ❓ Question
|
||||
description: Ask a YOLOv5 question
|
||||
# title: " "
|
||||
labels: [question]
|
||||
body:
|
||||
- type: markdown
|
||||
attributes:
|
||||
value: |
|
||||
Thank you for asking a YOLOv5 ❓ Question!
|
||||
|
||||
- type: checkboxes
|
||||
attributes:
|
||||
label: Search before asking
|
||||
description: >
|
||||
Please search the [issues](https://github.com/ultralytics/yolov5/issues) and [discussions](https://github.com/ultralytics/yolov5/discussions) to see if a similar question already exists.
|
||||
options:
|
||||
- label: >
|
||||
I have searched the YOLOv5 [issues](https://github.com/ultralytics/yolov5/issues) and [discussions](https://github.com/ultralytics/yolov5/discussions) and found no similar questions.
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Question
|
||||
description: What is your question?
|
||||
placeholder: |
|
||||
💡 ProTip! Include as much information as possible (screenshots, logs, tracebacks etc.) to receive the most helpful response.
|
||||
validations:
|
||||
required: true
|
||||
|
||||
- type: textarea
|
||||
attributes:
|
||||
label: Additional
|
||||
description: Anything else you would like to share?
|
9
app/yolov5/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
9
app/yolov5/.github/PULL_REQUEST_TEMPLATE.md
vendored
Normal file
@ -0,0 +1,9 @@
|
||||
<!--
|
||||
Thank you for submitting a YOLOv5 🚀 Pull Request! We want to make contributing to YOLOv5 as easy and transparent as possible. A few tips to get you started:
|
||||
|
||||
- Search existing YOLOv5 [PRs](https://github.com/ultralytics/yolov5/pull) to see if a similar PR already exists.
|
||||
- Link this PR to a YOLOv5 [issue](https://github.com/ultralytics/yolov5/issues) to help us understand what bug fix or feature is being implemented.
|
||||
- Provide before and after profiling/inference/training results to help us quantify the improvement your PR provides (if applicable).
|
||||
|
||||
Please see our ✅ [Contributing Guide](https://github.com/ultralytics/yolov5/blob/master/CONTRIBUTING.md) for more details.
|
||||
-->
|
356
app/yolov5/.github/README_cn.md
vendored
Normal file
356
app/yolov5/.github/README_cn.md
vendored
Normal file
@ -0,0 +1,356 @@
|
||||
<div align="center">
|
||||
<p>
|
||||
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
||||
<img width="850" src="https://github.com/ultralytics/assets/raw/master/yolov5/v62/splash_readme.png"></a>
|
||||
<br><br>
|
||||
<a href="https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app" style="text-decoration:none;">
|
||||
<img src="https://raw.githubusercontent.com/ultralytics/assets/master/app/google-play.svg" width="15%" alt="" /></a>
|
||||
<a href="https://apps.apple.com/xk/app/ultralytics/id1583935240" style="text-decoration:none;">
|
||||
<img src="https://raw.githubusercontent.com/ultralytics/assets/master/app/app-store.svg" width="15%" alt="" /></a>
|
||||
</p>
|
||||
|
||||
[English](../README.md) | 简体中文
|
||||
<br>
|
||||
<div>
|
||||
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="CI CPU testing"></a>
|
||||
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
|
||||
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
||||
<br>
|
||||
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
||||
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
||||
<a href="https://join.slack.com/t/ultralytics/shared_invite/zt-w29ei8bp-jczz7QYUmDtgo6r6KcMIAg"><img src="https://img.shields.io/badge/Slack-Join_Forum-blue.svg?logo=slack" alt="Join Forum"></a>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
<p>
|
||||
YOLOv5🚀是一个在COCO数据集上预训练的物体检测架构和模型系列,它代表了<a href="https://ultralytics.com">Ultralytics</a>对未来视觉AI方法的公开研究,其中包含了在数千小时的研究和开发中所获得的经验和最佳实践。
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://github.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="2%" alt="" /></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
## <div align="center">文件</div>
|
||||
|
||||
请参阅[YOLOv5 Docs](https://docs.ultralytics.com),了解有关训练、测试和部署的完整文件。
|
||||
|
||||
## <div align="center">快速开始案例</div>
|
||||
|
||||
<details open>
|
||||
<summary>安装</summary>
|
||||
|
||||
在[**Python>=3.7.0**](https://www.python.org/) 的环境中克隆版本仓并安装 [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt),包括[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/)。
|
||||
```bash
|
||||
git clone https://github.com/ultralytics/yolov5 # 克隆
|
||||
cd yolov5
|
||||
pip install -r requirements.txt # 安装
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details open>
|
||||
<summary>推理</summary>
|
||||
|
||||
YOLOv5 [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) 推理. [模型](https://github.com/ultralytics/yolov5/tree/master/models) 自动从最新YOLOv5 [版本](https://github.com/ultralytics/yolov5/releases)下载。
|
||||
|
||||
```python
|
||||
import torch
|
||||
|
||||
# 模型
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5n - yolov5x6, custom
|
||||
|
||||
# 图像
|
||||
img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
|
||||
|
||||
# 推理
|
||||
results = model(img)
|
||||
|
||||
# 结果
|
||||
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>用 detect.py 进行推理</summary>
|
||||
|
||||
`detect.py` 在各种数据源上运行推理, 其会从最新的 YOLOv5 [版本](https://github.com/ultralytics/yolov5/releases) 中自动下载 [模型](https://github.com/ultralytics/yolov5/tree/master/models) 并将检测结果保存到 `runs/detect` 目录。
|
||||
|
||||
```bash
|
||||
python detect.py --source 0 # 网络摄像头
|
||||
img.jpg # 图像
|
||||
vid.mp4 # 视频
|
||||
path/ # 文件夹
|
||||
'path/*.jpg' # glob
|
||||
'https://youtu.be/Zgi9g1ksQHc' # YouTube
|
||||
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP 流
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>训练</summary>
|
||||
|
||||
以下指令再现了 YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)
|
||||
数据集结果. [模型](https://github.com/ultralytics/yolov5/tree/master/models) 和 [数据集](https://github.com/ultralytics/yolov5/tree/master/data) 自动从最新的YOLOv5 [版本](https://github.com/ultralytics/yolov5/releases) 中下载。YOLOv5n/s/m/l/x的训练时间在V100 GPU上是 1/2/4/6/8天(多GPU倍速). 尽可能使用最大的 `--batch-size`, 或通过 `--batch-size -1` 来实现 YOLOv5 [自动批处理](https://github.com/ultralytics/yolov5/pull/5092). 批量大小显示为 V100-16GB。
|
||||
|
||||
```bash
|
||||
python train.py --data coco.yaml --cfg yolov5n.yaml --weights '' --batch-size 128
|
||||
yolov5s 64
|
||||
yolov5m 40
|
||||
yolov5l 24
|
||||
yolov5x 16
|
||||
```
|
||||
|
||||
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
|
||||
|
||||
</details>
|
||||
|
||||
<details open>
|
||||
<summary>教程</summary>
|
||||
|
||||
- [训练自定义数据集](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 🚀 推荐
|
||||
- [获得最佳训练效果的技巧](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results) ☘️
|
||||
推荐
|
||||
- [多GPU训练](https://github.com/ultralytics/yolov5/issues/475)
|
||||
- [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) 🌟 新
|
||||
- [TFLite, ONNX, CoreML, TensorRT 输出](https://github.com/ultralytics/yolov5/issues/251) 🚀
|
||||
- [测试时数据增强 (TTA)](https://github.com/ultralytics/yolov5/issues/303)
|
||||
- [模型集成](https://github.com/ultralytics/yolov5/issues/318)
|
||||
- [模型剪枝/稀疏性](https://github.com/ultralytics/yolov5/issues/304)
|
||||
- [超参数进化](https://github.com/ultralytics/yolov5/issues/607)
|
||||
- [带有冻结层的迁移学习](https://github.com/ultralytics/yolov5/issues/1314)
|
||||
- [架构概要](https://github.com/ultralytics/yolov5/issues/6998) 🌟 新
|
||||
- [使用Weights & Biases 记录实验](https://github.com/ultralytics/yolov5/issues/1289)
|
||||
- [Roboflow:数据集,标签和主动学习](https://github.com/ultralytics/yolov5/issues/4975) 🌟 新
|
||||
- [使用ClearML 记录实验](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/clearml) 🌟 新
|
||||
- [Deci 平台](https://github.com/ultralytics/yolov5/wiki/Deci-Platform) 🌟 新
|
||||
|
||||
</details>
|
||||
|
||||
## <div align="center">环境</div>
|
||||
|
||||
使用经过我们验证的环境,几秒钟就可以开始。点击下面的每个图标了解详情。
|
||||
|
||||
<div align="center">
|
||||
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-colab-small.png" width="15%"/>
|
||||
</a>
|
||||
<a href="https://www.kaggle.com/ultralytics/yolov5">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-kaggle-small.png" width="15%"/>
|
||||
</a>
|
||||
<a href="https://hub.docker.com/r/ultralytics/yolov5">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-docker-small.png" width="15%"/>
|
||||
</a>
|
||||
<a href="https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-aws-small.png" width="15%"/>
|
||||
</a>
|
||||
<a href="https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gcp-small.png" width="15%"/>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
## <div align="center">如何与第三方集成</div>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://bit.ly/yolov5-deci-platform">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-deci.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://cutt.ly/yolov5-readme-clearml">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-clearml.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://roboflow.com/?ref=ultralytics">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-roboflow.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://wandb.ai/site?utm_campaign=repo_yolo_readme">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-wb.png" width="10%" /></a>
|
||||
</div>
|
||||
|
||||
|Deci ⭐ NEW|ClearML ⭐ NEW|Roboflow|Weights & Biases
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|在[Deci](https://bit.ly/yolov5-deci-platform)一键自动编译和量化YOLOv5以提高推理性能|使用[ClearML](https://cutt.ly/yolov5-readme-clearml) (开源!)自动追踪,可视化,以及远程训练YOLOv5|标记并将您的自定义数据直接导出到YOLOv5后,用[Roboflow](https://roboflow.com/?ref=ultralytics)进行训练 |通过[Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme)自动跟踪以及可视化你在云端所有的YOLOv5训练运行情况
|
||||
|
||||
|
||||
## <div align="center">为什么选择 YOLOv5</div>
|
||||
|
||||
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
|
||||
<details>
|
||||
<summary>YOLOv5-P5 640 图像 (点击扩展)</summary>
|
||||
|
||||
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>图片注释 (点击扩展)</summary>
|
||||
|
||||
- **COCO AP val** 表示 mAP@0.5:0.95 在5000张图像的[COCO val2017](http://cocodataset.org)数据集上,在256到1536的不同推理大小上测量的指标。
|
||||
- **GPU Speed** 衡量的是在 [COCO val2017](http://cocodataset.org) 数据集上使用 [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100实例在批量大小为32时每张图像的平均推理时间。
|
||||
- **EfficientDet** 数据来自 [google/automl](https://github.com/google/automl) ,批量大小设置为 8。
|
||||
- 复现 mAP 方法: `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
|
||||
|
||||
</details>
|
||||
|
||||
### 预训练检查点
|
||||
|
||||
| 模型 | 规模<br><sup>(像素) | mAP<sup>验证<br>0.5:0.95 | mAP<sup>验证<br>0.5 | 速度<br><sup>CPU b1<br>(ms) | 速度<br><sup>V100 b1<br>(ms) | 速度<br><sup>V100 b32<br>(ms) | 参数<br><sup>(M) | 浮点运算<br><sup>@640 (B) |
|
||||
|------------------------------------------------------------------------------------------------------|-----------------------|-------------------------|--------------------|------------------------------|-------------------------------|--------------------------------|--------------------|------------------------|
|
||||
| [YOLOv5n](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n.pt) | 640 | 28.0 | 45.7 | **45** | **6.3** | **0.6** | **1.9** | **4.5** |
|
||||
| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s.pt) | 640 | 37.4 | 56.8 | 98 | 6.4 | 0.9 | 7.2 | 16.5 |
|
||||
| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m.pt) | 640 | 45.4 | 64.1 | 224 | 8.2 | 1.7 | 21.2 | 49.0 |
|
||||
| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5l.pt) | 640 | 49.0 | 67.3 | 430 | 10.1 | 2.7 | 46.5 | 109.1 |
|
||||
| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5x.pt) | 640 | 50.7 | 68.9 | 766 | 12.1 | 4.8 | 86.7 | 205.7 |
|
||||
| | | | | | | | | |
|
||||
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5n6.pt) | 1280 | 36.0 | 54.4 | 153 | 8.1 | 2.1 | 3.2 | 4.6 |
|
||||
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5s6.pt) | 1280 | 44.8 | 63.7 | 385 | 8.2 | 3.6 | 12.6 | 16.8 |
|
||||
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5m6.pt) | 1280 | 51.3 | 69.3 | 887 | 11.1 | 6.8 | 35.7 | 50.0 |
|
||||
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5l6.pt) | 1280 | 53.7 | 71.3 | 1784 | 15.8 | 10.5 | 76.8 | 111.4 |
|
||||
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v6.1/yolov5x6.pt)<br>+ [TTA][TTA] | 1280<br>1536 | 55.0<br>**55.8** | 72.7<br>**72.7** | 3136<br>- | 26.2<br>- | 19.4<br>- | 140.7<br>- | 209.8<br>- |
|
||||
|
||||
<details>
|
||||
<summary>表格注释 (点击扩展)</summary>
|
||||
|
||||
- 所有检查点都以默认设置训练到300个时期. Nano和Small模型用 [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, 其他模型使用 [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
|
||||
- **mAP<sup>val</sup>** 值是 [COCO val2017](http://cocodataset.org) 数据集上的单模型单尺度的值。
|
||||
<br>复现方法: `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
|
||||
- 使用 [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) 实例对COCO val图像的平均速度。不包括NMS时间(~1 ms/img)
|
||||
<br>复现方法: `python val.py --data coco.yaml --img 640 --task speed --batch 1`
|
||||
- **TTA** [测试时数据增强](https://github.com/ultralytics/yolov5/issues/303) 包括反射和比例增强.
|
||||
<br>复现方法: `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
|
||||
|
||||
</details>
|
||||
|
||||
|
||||
## <div align="center">分类 ⭐ 新</div>
|
||||
|
||||
YOLOv5发布的[v6.2版本](https://github.com/ultralytics/yolov5/releases) 支持训练,验证,预测和输出分类模型!这使得训练分类器模型非常简单。点击下面开始尝试!
|
||||
|
||||
<details>
|
||||
<summary>分类检查点 (点击展开)</summary>
|
||||
|
||||
<br>
|
||||
|
||||
我们在ImageNet上使用了4xA100的实例训练YOLOv5-cls分类模型90个epochs,并以相同的默认设置同时训练了ResNet和EfficientNet模型来进行比较。我们将所有的模型导出到ONNX FP32进行CPU速度测试,又导出到TensorRT FP16进行GPU速度测试。最后,为了方便重现,我们在[Google Colab Pro](https://colab.research.google.com/signup)上进行了所有的速度测试。
|
||||
|
||||
| 模型 | 规模<br><sup>(像素) | 准确度<br><sup>第一 | 准确度<br><sup>前五 | 训练<br><sup>90 epochs<br>4xA100 (小时) | 速度<br><sup>ONNX CPU<br>(ms) | 速度<br><sup>TensorRT V100<br>(ms) | 参数<br><sup>(M) | 浮点运算<br><sup>@224 (B) |
|
||||
|----------------------------------------------------------------------------------------------------|-----------------------|------------------|------------------|----------------------------------------------|--------------------------------|-------------------------------------|--------------------|------------------------|
|
||||
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n-cls.pt) | 224 | 64.6 | 85.4 | 7:59 | **3.3** | **0.5** | **2.5** | **0.5** |
|
||||
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s-cls.pt) | 224 | 71.5 | 90.2 | 8:09 | 6.6 | 0.6 | 5.4 | 1.4 |
|
||||
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m-cls.pt) | 224 | 75.9 | 92.9 | 10:06 | 15.5 | 0.9 | 12.9 | 3.9 |
|
||||
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l-cls.pt) | 224 | 78.0 | 94.0 | 11:56 | 26.9 | 1.4 | 26.5 | 8.5 |
|
||||
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x-cls.pt) | 224 | **79.0** | **94.4** | 15:04 | 54.3 | 1.8 | 48.1 | 15.9 |
|
||||
| |
|
||||
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet18.pt) | 224 | 70.3 | 89.5 | **6:47** | 11.2 | 0.5 | 11.7 | 3.7 |
|
||||
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet34.pt) | 224 | 73.9 | 91.8 | 8:33 | 20.6 | 0.9 | 21.8 | 7.4 |
|
||||
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet50.pt) | 224 | 76.8 | 93.4 | 11:10 | 23.4 | 1.0 | 25.6 | 8.5 |
|
||||
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet101.pt) | 224 | 78.5 | 94.3 | 17:10 | 42.1 | 1.9 | 44.5 | 15.9 |
|
||||
| |
|
||||
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b0.pt) | 224 | 75.1 | 92.4 | 13:03 | 12.5 | 1.3 | 5.3 | 1.0 |
|
||||
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b1.pt) | 224 | 76.4 | 93.2 | 17:04 | 14.9 | 1.6 | 7.8 | 1.5 |
|
||||
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b2.pt) | 224 | 76.6 | 93.4 | 17:10 | 15.9 | 1.6 | 9.1 | 1.7 |
|
||||
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b3.pt) | 224 | 77.7 | 94.0 | 19:19 | 18.9 | 1.9 | 12.2 | 2.4 |
|
||||
|
||||
<details>
|
||||
<summary>表格注释 (点击扩展)</summary>
|
||||
|
||||
- 所有检查点都被SGD优化器训练到90 epochs, `lr0=0.001` 和 `weight_decay=5e-5`, 图像大小为224,全为默认设置。<br>运行数据记录于 https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2。
|
||||
- **准确度** 值为[ImageNet-1k](https://www.image-net.org/index.php)数据集上的单模型单尺度。<br>通过`python classify/val.py --data ../datasets/imagenet --img 224`进行复制。
|
||||
- 使用Google [Colab Pro](https://colab.research.google.com/signup) V100 High-RAM实例得出的100张推理图像的平均**速度**。<br>通过 `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`进行复制。
|
||||
- 用`export.py`**导出**到FP32的ONNX和FP16的TensorRT。<br>通过 `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`进行复制。
|
||||
</details>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>分类使用实例 (点击展开)</summary>
|
||||
|
||||
### 训练
|
||||
YOLOv5分类训练支持自动下载MNIST, Fashion-MNIST, CIFAR10, CIFAR100, Imagenette, Imagewoof和ImageNet数据集,并使用`--data` 参数. 打个比方,在MNIST上使用`--data mnist`开始训练。
|
||||
|
||||
```bash
|
||||
# 单GPU
|
||||
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128
|
||||
|
||||
# 多-GPU DDP
|
||||
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
|
||||
```
|
||||
|
||||
### 验证
|
||||
在ImageNet-1k数据集上验证YOLOv5m-cl的准确性:
|
||||
```bash
|
||||
bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
||||
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate
|
||||
```
|
||||
|
||||
### 预测
|
||||
用提前训练好的YOLOv5s-cls.pt去预测bus.jpg:
|
||||
```bash
|
||||
python classify/predict.py --weights yolov5s-cls.pt --data data/images/bus.jpg
|
||||
```
|
||||
```python
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s-cls.pt') # load from PyTorch Hub
|
||||
```
|
||||
|
||||
### 导出
|
||||
导出一组训练好的YOLOv5s-cls, ResNet和EfficientNet模型到ONNX和TensorRT:
|
||||
```bash
|
||||
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
## <div align="center">贡献</div>
|
||||
|
||||
我们重视您的意见! 我们希望给大家提供尽可能的简单和透明的方式对 YOLOv5 做出贡献。开始之前请先点击并查看我们的 [贡献指南](CONTRIBUTING.md),填写[YOLOv5调查问卷](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) 来向我们发送您的经验反馈。真诚感谢我们所有的贡献者!
|
||||
|
||||
<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->
|
||||
<a href="https://github.com/ultralytics/yolov5/graphs/contributors"><img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/image-contributors-1280.png" /></a>
|
||||
|
||||
## <div align="center">联系</div>
|
||||
|
||||
关于YOLOv5的漏洞和功能问题,请访问 [GitHub Issues](https://github.com/ultralytics/yolov5/issues)。商业咨询或技术支持服务请访问[https://ultralytics.com/contact](https://ultralytics.com/contact)。
|
||||
|
||||
<br>
|
||||
<div align="center">
|
||||
<a href="https://github.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="3%" alt="" /></a>
|
||||
</div>
|
||||
|
||||
[assets]: https://github.com/ultralytics/yolov5/releases
|
||||
[tta]: https://github.com/ultralytics/yolov5/issues/303
|
7
app/yolov5/.github/SECURITY.md
vendored
Normal file
7
app/yolov5/.github/SECURITY.md
vendored
Normal file
@ -0,0 +1,7 @@
|
||||
# Security Policy
|
||||
|
||||
We aim to make YOLOv5 🚀 as secure as possible! If you find potential vulnerabilities or have any concerns please let us know so we can investigate and take corrective action if needed.
|
||||
|
||||
### Reporting a Vulnerability
|
||||
|
||||
To report vulnerabilities please email us at hello@ultralytics.com or visit https://ultralytics.com/contact. Thank you!
|
23
app/yolov5/.github/dependabot.yml
vendored
Normal file
23
app/yolov5/.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,23 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: pip
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
time: "04:00"
|
||||
open-pull-requests-limit: 10
|
||||
reviewers:
|
||||
- glenn-jocher
|
||||
labels:
|
||||
- dependencies
|
||||
|
||||
- package-ecosystem: github-actions
|
||||
directory: "/"
|
||||
schedule:
|
||||
interval: weekly
|
||||
time: "04:00"
|
||||
open-pull-requests-limit: 5
|
||||
reviewers:
|
||||
- glenn-jocher
|
||||
labels:
|
||||
- dependencies
|
140
app/yolov5/.github/workflows/ci-testing.yml
vendored
Normal file
140
app/yolov5/.github/workflows/ci-testing.yml
vendored
Normal file
@ -0,0 +1,140 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# YOLOv5 Continuous Integration (CI) GitHub Actions tests
|
||||
|
||||
name: YOLOv5 CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
schedule:
|
||||
- cron: '0 0 * * *' # runs at 00:00 UTC every day
|
||||
|
||||
jobs:
|
||||
Benchmarks:
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
matrix:
|
||||
os: [ ubuntu-latest ]
|
||||
python-version: [ '3.9' ] # requires python<=3.9
|
||||
model: [ yolov5n ]
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
#- name: Cache pip
|
||||
# uses: actions/cache@v3
|
||||
# with:
|
||||
# path: ~/.cache/pip
|
||||
# key: ${{ runner.os }}-Benchmarks-${{ hashFiles('requirements.txt') }}
|
||||
# restore-keys: ${{ runner.os }}-Benchmarks-
|
||||
- name: Install requirements
|
||||
run: |
|
||||
python -m pip install --upgrade pip wheel
|
||||
pip install -r requirements.txt coremltools openvino-dev tensorflow-cpu --extra-index-url https://download.pytorch.org/whl/cpu
|
||||
python --version
|
||||
pip --version
|
||||
pip list
|
||||
- name: Run benchmarks
|
||||
run: |
|
||||
python utils/benchmarks.py --weights ${{ matrix.model }}.pt --img 320 --hard-fail 0.29
|
||||
|
||||
Tests:
|
||||
timeout-minutes: 60
|
||||
runs-on: ${{ matrix.os }}
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
os: [ ubuntu-latest, windows-latest ] # macos-latest bug https://github.com/ultralytics/yolov5/pull/9049
|
||||
python-version: [ '3.10' ]
|
||||
model: [ yolov5n ]
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
python-version: '3.7' # '3.6.8' min
|
||||
model: yolov5n
|
||||
- os: ubuntu-latest
|
||||
python-version: '3.8'
|
||||
model: yolov5n
|
||||
- os: ubuntu-latest
|
||||
python-version: '3.9'
|
||||
model: yolov5n
|
||||
- os: ubuntu-latest
|
||||
python-version: '3.8' # torch 1.7.0 requires python >=3.6, <=3.8
|
||||
model: yolov5n
|
||||
torch: '1.7.0' # min torch version CI https://pypi.org/project/torchvision/
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/setup-python@v4
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
- name: Get cache dir
|
||||
# https://github.com/actions/cache/blob/master/examples.md#multiple-oss-in-a-workflow
|
||||
id: pip-cache
|
||||
run: echo "::set-output name=dir::$(pip cache dir)"
|
||||
- name: Cache pip
|
||||
uses: actions/cache@v3
|
||||
with:
|
||||
path: ${{ steps.pip-cache.outputs.dir }}
|
||||
key: ${{ runner.os }}-${{ matrix.python-version }}-pip-${{ hashFiles('requirements.txt') }}
|
||||
restore-keys: ${{ runner.os }}-${{ matrix.python-version }}-pip-
|
||||
- name: Install requirements
|
||||
run: |
|
||||
python -m pip install --upgrade pip wheel
|
||||
if [ "${{ matrix.torch }}" == "1.7.0" ]; then
|
||||
pip install -r requirements.txt torch==1.7.0 torchvision==0.8.1 --extra-index-url https://download.pytorch.org/whl/cpu
|
||||
else
|
||||
pip install -r requirements.txt --extra-index-url https://download.pytorch.org/whl/cpu
|
||||
fi
|
||||
shell: bash # for Windows compatibility
|
||||
- name: Check environment
|
||||
run: |
|
||||
python -c "import utils; utils.notebook_init()"
|
||||
echo "RUNNER_OS is ${{ runner.os }}"
|
||||
echo "GITHUB_EVENT_NAME is ${{ github.event_name }}"
|
||||
echo "GITHUB_WORKFLOW is ${{ github.workflow }}"
|
||||
echo "GITHUB_ACTOR is ${{ github.actor }}"
|
||||
echo "GITHUB_REPOSITORY is ${{ github.repository }}"
|
||||
echo "GITHUB_REPOSITORY_OWNER is ${{ github.repository_owner }}"
|
||||
python --version
|
||||
pip --version
|
||||
pip list
|
||||
- name: Test detection
|
||||
shell: bash # for Windows compatibility
|
||||
run: |
|
||||
# export PYTHONPATH="$PWD" # to run '$ python *.py' files in subdirectories
|
||||
m=${{ matrix.model }} # official weights
|
||||
b=runs/train/exp/weights/best # best.pt checkpoint
|
||||
python train.py --imgsz 64 --batch 32 --weights $m.pt --cfg $m.yaml --epochs 1 --device cpu # train
|
||||
for d in cpu; do # devices
|
||||
for w in $m $b; do # weights
|
||||
python val.py --imgsz 64 --batch 32 --weights $w.pt --device $d # val
|
||||
python detect.py --imgsz 64 --weights $w.pt --device $d # detect
|
||||
done
|
||||
done
|
||||
python hubconf.py --model $m # hub
|
||||
# python models/tf.py --weights $m.pt # build TF model
|
||||
python models/yolo.py --cfg $m.yaml # build PyTorch model
|
||||
python export.py --weights $m.pt --img 64 --include torchscript # export
|
||||
python - <<EOF
|
||||
import torch
|
||||
for path in '$m', '$b':
|
||||
model = torch.hub.load('.', 'custom', path=path, source='local')
|
||||
print(model('data/images/bus.jpg'))
|
||||
EOF
|
||||
- name: Test classification
|
||||
shell: bash # for Windows compatibility
|
||||
run: |
|
||||
m=${{ matrix.model }}-cls.pt # official weights
|
||||
b=runs/train-cls/exp/weights/best.pt # best.pt checkpoint
|
||||
python classify/train.py --imgsz 32 --model $m --data mnist2560 --epochs 1 # train
|
||||
python classify/val.py --imgsz 32 --weights $b --data ../datasets/mnist2560 # val
|
||||
python classify/predict.py --imgsz 32 --weights $b --source ../datasets/mnist2560/test/7/60.png # predict
|
||||
python classify/predict.py --imgsz 32 --weights $m --source data/images/bus.jpg # predict
|
||||
python export.py --weights $b --img 64 --imgsz 224 --include torchscript # export
|
||||
python - <<EOF
|
||||
import torch
|
||||
for path in '$m', '$b':
|
||||
model = torch.hub.load('.', 'custom', path=path, source='local')
|
||||
EOF
|
54
app/yolov5/.github/workflows/codeql-analysis.yml
vendored
Normal file
54
app/yolov5/.github/workflows/codeql-analysis.yml
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
# This action runs GitHub's industry-leading static analysis engine, CodeQL, against a repository's source code to find security vulnerabilities.
|
||||
# https://github.com/github/codeql-action
|
||||
|
||||
name: "CodeQL"
|
||||
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 1 * *' # Runs at 00:00 UTC on the 1st of every month
|
||||
|
||||
jobs:
|
||||
analyze:
|
||||
name: Analyze
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
language: ['python']
|
||||
# CodeQL supports [ 'cpp', 'csharp', 'go', 'java', 'javascript', 'python' ]
|
||||
# Learn more:
|
||||
# https://docs.github.com/en/free-pro-team@latest/github/finding-security-vulnerabilities-and-errors-in-your-code/configuring-code-scanning#changing-the-languages-that-are-analyzed
|
||||
|
||||
steps:
|
||||
- name: Checkout repository
|
||||
uses: actions/checkout@v3
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v2
|
||||
with:
|
||||
languages: ${{ matrix.language }}
|
||||
# If you wish to specify custom queries, you can do so here or in a config file.
|
||||
# By default, queries listed here will override any specified in a config file.
|
||||
# Prefix the list here with "+" to use these queries and those in the config file.
|
||||
# queries: ./path/to/local/query, your-org/your-repo/queries@main
|
||||
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below)
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 https://git.io/JvXDl
|
||||
|
||||
# ✏️ If the Autobuild fails above, remove it and uncomment the following three lines
|
||||
# and modify them (or add more) to build your code if your project
|
||||
# uses a compiled language
|
||||
|
||||
#- run: |
|
||||
# make bootstrap
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v2
|
54
app/yolov5/.github/workflows/docker.yml
vendored
Normal file
54
app/yolov5/.github/workflows/docker.yml
vendored
Normal file
@ -0,0 +1,54 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Builds ultralytics/yolov5:latest images on DockerHub https://hub.docker.com/r/ultralytics/yolov5
|
||||
|
||||
name: Publish Docker Images
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
|
||||
jobs:
|
||||
docker:
|
||||
if: github.repository == 'ultralytics/yolov5'
|
||||
name: Push Docker image to Docker Hub
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout repo
|
||||
uses: actions/checkout@v3
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v2
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v2
|
||||
|
||||
- name: Login to Docker Hub
|
||||
uses: docker/login-action@v2
|
||||
with:
|
||||
username: ${{ secrets.DOCKERHUB_USERNAME }}
|
||||
password: ${{ secrets.DOCKERHUB_TOKEN }}
|
||||
|
||||
- name: Build and push arm64 image
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
platforms: linux/arm64
|
||||
file: utils/docker/Dockerfile-arm64
|
||||
push: true
|
||||
tags: ultralytics/yolov5:latest-arm64
|
||||
|
||||
- name: Build and push CPU image
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
file: utils/docker/Dockerfile-cpu
|
||||
push: true
|
||||
tags: ultralytics/yolov5:latest-cpu
|
||||
|
||||
- name: Build and push GPU image
|
||||
uses: docker/build-push-action@v3
|
||||
with:
|
||||
context: .
|
||||
file: utils/docker/Dockerfile
|
||||
push: true
|
||||
tags: ultralytics/yolov5:latest
|
57
app/yolov5/.github/workflows/greetings.yml
vendored
Normal file
57
app/yolov5/.github/workflows/greetings.yml
vendored
Normal file
@ -0,0 +1,57 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
|
||||
name: Greetings
|
||||
|
||||
on:
|
||||
pull_request_target:
|
||||
types: [opened]
|
||||
issues:
|
||||
types: [opened]
|
||||
|
||||
jobs:
|
||||
greeting:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/first-interaction@v1
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
pr-message: |
|
||||
👋 Hello @${{ github.actor }}, thank you for submitting a YOLOv5 🚀 PR! To allow your work to be integrated as seamlessly as possible, we advise you to:
|
||||
|
||||
- ✅ Verify your PR is **up-to-date** with `ultralytics/yolov5` `master` branch. If your PR is behind you can update your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
|
||||
- ✅ Verify all YOLOv5 Continuous Integration (CI) **checks are passing**.
|
||||
- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
|
||||
|
||||
issue-message: |
|
||||
👋 Hello @${{ github.actor }}, thank you for your interest in YOLOv5 🚀! Please visit our ⭐️ [Tutorials](https://github.com/ultralytics/yolov5/wiki#tutorials) to get started, where you can find quickstart guides for simple tasks like [Custom Data Training](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) all the way to advanced concepts like [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607).
|
||||
|
||||
If this is a 🐛 Bug Report, please provide screenshots and **minimum viable code to reproduce your issue**, otherwise we can not help you.
|
||||
|
||||
If this is a custom training ❓ Question, please provide as much information as possible, including dataset images, training logs, screenshots, and a public link to online [W&B logging](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data#visualize) if available.
|
||||
|
||||
For business inquiries or professional support requests please visit https://ultralytics.com or email support@ultralytics.com.
|
||||
|
||||
## Requirements
|
||||
|
||||
[**Python>=3.7.0**](https://www.python.org/) with all [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) installed including [**PyTorch>=1.7**](https://pytorch.org/get-started/locally/). To get started:
|
||||
```bash
|
||||
git clone https://github.com/ultralytics/yolov5 # clone
|
||||
cd yolov5
|
||||
pip install -r requirements.txt # install
|
||||
```
|
||||
|
||||
## Environments
|
||||
|
||||
YOLOv5 may be run in any of the following up-to-date verified environments (with all dependencies including [CUDA](https://developer.nvidia.com/cuda)/[CUDNN](https://developer.nvidia.com/cudnn), [Python](https://www.python.org/) and [PyTorch](https://pytorch.org/) preinstalled):
|
||||
|
||||
- **Google Colab and Kaggle** notebooks with free GPU: <a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a> <a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
||||
- **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
|
||||
- **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)
|
||||
- **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) <a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
||||
|
||||
|
||||
## Status
|
||||
|
||||
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="CI CPU testing"></a>
|
||||
|
||||
If this badge is green, all [YOLOv5 GitHub Actions](https://github.com/ultralytics/yolov5/actions) Continuous Integration (CI) tests are currently passing. CI tests verify correct operation of YOLOv5 training ([train.py](https://github.com/ultralytics/yolov5/blob/master/train.py)), validation ([val.py](https://github.com/ultralytics/yolov5/blob/master/val.py)), inference ([detect.py](https://github.com/ultralytics/yolov5/blob/master/detect.py)) and export ([export.py](https://github.com/ultralytics/yolov5/blob/master/export.py)) on macOS, Windows, and Ubuntu every 24 hours and on every commit.
|
40
app/yolov5/.github/workflows/stale.yml
vendored
Normal file
40
app/yolov5/.github/workflows/stale.yml
vendored
Normal file
@ -0,0 +1,40 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
|
||||
name: Close stale issues
|
||||
on:
|
||||
schedule:
|
||||
- cron: '0 0 * * *' # Runs at 00:00 UTC every day
|
||||
|
||||
jobs:
|
||||
stale:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/stale@v5
|
||||
with:
|
||||
repo-token: ${{ secrets.GITHUB_TOKEN }}
|
||||
stale-issue-message: |
|
||||
👋 Hello, this issue has been automatically marked as stale because it has not had recent activity. Please note it will be closed if no further activity occurs.
|
||||
|
||||
Access additional [YOLOv5](https://ultralytics.com/yolov5) 🚀 resources:
|
||||
- **Wiki** – https://github.com/ultralytics/yolov5/wiki
|
||||
- **Tutorials** – https://github.com/ultralytics/yolov5#tutorials
|
||||
- **Docs** – https://docs.ultralytics.com
|
||||
|
||||
Access additional [Ultralytics](https://ultralytics.com) ⚡ resources:
|
||||
- **Ultralytics HUB** – https://ultralytics.com/hub
|
||||
- **Vision API** – https://ultralytics.com/yolov5
|
||||
- **About Us** – https://ultralytics.com/about
|
||||
- **Join Our Team** – https://ultralytics.com/work
|
||||
- **Contact Us** – https://ultralytics.com/contact
|
||||
|
||||
Feel free to inform us of any other **issues** you discover or **feature requests** that come to mind in the future. Pull Requests (PRs) are also always welcomed!
|
||||
|
||||
Thank you for your contributions to YOLOv5 🚀 and Vision AI ⭐!
|
||||
|
||||
stale-pr-message: 'This pull request has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions YOLOv5 🚀 and Vision AI ⭐.'
|
||||
days-before-issue-stale: 30
|
||||
days-before-issue-close: 10
|
||||
days-before-pr-stale: 90
|
||||
days-before-pr-close: 30
|
||||
exempt-issue-labels: 'documentation,tutorial,TODO'
|
||||
operations-per-run: 300 # The maximum number of operations per run, used to control rate limiting.
|
256
app/yolov5/.gitignore
vendored
Normal file
256
app/yolov5/.gitignore
vendored
Normal file
@ -0,0 +1,256 @@
|
||||
# Repo-specific GitIgnore ----------------------------------------------------------------------------------------------
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.png
|
||||
*.bmp
|
||||
*.tif
|
||||
*.tiff
|
||||
*.heic
|
||||
*.JPG
|
||||
*.JPEG
|
||||
*.PNG
|
||||
*.BMP
|
||||
*.TIF
|
||||
*.TIFF
|
||||
*.HEIC
|
||||
*.mp4
|
||||
*.mov
|
||||
*.MOV
|
||||
*.avi
|
||||
*.data
|
||||
*.json
|
||||
*.cfg
|
||||
!setup.cfg
|
||||
!cfg/yolov3*.cfg
|
||||
|
||||
storage.googleapis.com
|
||||
runs/*
|
||||
data/*
|
||||
data/images/*
|
||||
!data/*.yaml
|
||||
!data/hyps
|
||||
!data/scripts
|
||||
!data/images
|
||||
!data/images/zidane.jpg
|
||||
!data/images/bus.jpg
|
||||
!data/*.sh
|
||||
|
||||
results*.csv
|
||||
|
||||
# Datasets -------------------------------------------------------------------------------------------------------------
|
||||
coco/
|
||||
coco128/
|
||||
VOC/
|
||||
|
||||
# MATLAB GitIgnore -----------------------------------------------------------------------------------------------------
|
||||
*.m~
|
||||
*.mat
|
||||
!targets*.mat
|
||||
|
||||
# Neural Network weights -----------------------------------------------------------------------------------------------
|
||||
*.weights
|
||||
*.pt
|
||||
*.pb
|
||||
*.onnx
|
||||
*.engine
|
||||
*.mlmodel
|
||||
*.torchscript
|
||||
*.tflite
|
||||
*.h5
|
||||
*_saved_model/
|
||||
*_web_model/
|
||||
*_openvino_model/
|
||||
darknet53.conv.74
|
||||
yolov3-tiny.conv.15
|
||||
|
||||
# GitHub Python GitIgnore ----------------------------------------------------------------------------------------------
|
||||
# Byte-compiled / optimized / DLL files
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
|
||||
# C extensions
|
||||
*.so
|
||||
|
||||
# Distribution / packaging
|
||||
.Python
|
||||
env/
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
/wandb/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
|
||||
# PyInstaller
|
||||
# Usually these files are written by a python script from a template
|
||||
# before PyInstaller builds the exe, so as to inject date/other infos into it.
|
||||
*.manifest
|
||||
*.spec
|
||||
|
||||
# Installer logs
|
||||
pip-log.txt
|
||||
pip-delete-this-directory.txt
|
||||
|
||||
# Unit test / coverage reports
|
||||
htmlcov/
|
||||
.tox/
|
||||
.coverage
|
||||
.coverage.*
|
||||
.cache
|
||||
nosetests.xml
|
||||
coverage.xml
|
||||
*.cover
|
||||
.hypothesis/
|
||||
|
||||
# Translations
|
||||
*.mo
|
||||
*.pot
|
||||
|
||||
# Django stuff:
|
||||
*.log
|
||||
local_settings.py
|
||||
|
||||
# Flask stuff:
|
||||
instance/
|
||||
.webassets-cache
|
||||
|
||||
# Scrapy stuff:
|
||||
.scrapy
|
||||
|
||||
# Sphinx documentation
|
||||
docs/_build/
|
||||
|
||||
# PyBuilder
|
||||
target/
|
||||
|
||||
# Jupyter Notebook
|
||||
.ipynb_checkpoints
|
||||
|
||||
# pyenv
|
||||
.python-version
|
||||
|
||||
# celery beat schedule file
|
||||
celerybeat-schedule
|
||||
|
||||
# SageMath parsed files
|
||||
*.sage.py
|
||||
|
||||
# dotenv
|
||||
.env
|
||||
|
||||
# virtualenv
|
||||
.venv*
|
||||
venv*/
|
||||
ENV*/
|
||||
|
||||
# Spyder project settings
|
||||
.spyderproject
|
||||
.spyproject
|
||||
|
||||
# Rope project settings
|
||||
.ropeproject
|
||||
|
||||
# mkdocs documentation
|
||||
/site
|
||||
|
||||
# mypy
|
||||
.mypy_cache/
|
||||
|
||||
|
||||
# https://github.com/github/gitignore/blob/master/Global/macOS.gitignore -----------------------------------------------
|
||||
|
||||
# General
|
||||
.DS_Store
|
||||
.AppleDouble
|
||||
.LSOverride
|
||||
|
||||
# Icon must end with two \r
|
||||
Icon
|
||||
Icon?
|
||||
|
||||
# Thumbnails
|
||||
._*
|
||||
|
||||
# Files that might appear in the root of a volume
|
||||
.DocumentRevisions-V100
|
||||
.fseventsd
|
||||
.Spotlight-V100
|
||||
.TemporaryItems
|
||||
.Trashes
|
||||
.VolumeIcon.icns
|
||||
.com.apple.timemachine.donotpresent
|
||||
|
||||
# Directories potentially created on remote AFP share
|
||||
.AppleDB
|
||||
.AppleDesktop
|
||||
Network Trash Folder
|
||||
Temporary Items
|
||||
.apdisk
|
||||
|
||||
|
||||
# https://github.com/github/gitignore/blob/master/Global/JetBrains.gitignore
|
||||
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and WebStorm
|
||||
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839
|
||||
|
||||
# User-specific stuff:
|
||||
.idea/*
|
||||
.idea/**/workspace.xml
|
||||
.idea/**/tasks.xml
|
||||
.idea/dictionaries
|
||||
.html # Bokeh Plots
|
||||
.pg # TensorFlow Frozen Graphs
|
||||
.avi # videos
|
||||
|
||||
# Sensitive or high-churn files:
|
||||
.idea/**/dataSources/
|
||||
.idea/**/dataSources.ids
|
||||
.idea/**/dataSources.local.xml
|
||||
.idea/**/sqlDataSources.xml
|
||||
.idea/**/dynamic.xml
|
||||
.idea/**/uiDesigner.xml
|
||||
|
||||
# Gradle:
|
||||
.idea/**/gradle.xml
|
||||
.idea/**/libraries
|
||||
|
||||
# CMake
|
||||
cmake-build-debug/
|
||||
cmake-build-release/
|
||||
|
||||
# Mongo Explorer plugin:
|
||||
.idea/**/mongoSettings.xml
|
||||
|
||||
## File-based project format:
|
||||
*.iws
|
||||
|
||||
## Plugin-specific files:
|
||||
|
||||
# IntelliJ
|
||||
out/
|
||||
|
||||
# mpeltonen/sbt-idea plugin
|
||||
.idea_modules/
|
||||
|
||||
# JIRA plugin
|
||||
atlassian-ide-plugin.xml
|
||||
|
||||
# Cursive Clojure plugin
|
||||
.idea/replstate.xml
|
||||
|
||||
# Crashlytics plugin (for Android Studio and IntelliJ)
|
||||
com_crashlytics_export_strings.xml
|
||||
crashlytics.properties
|
||||
crashlytics-build.properties
|
||||
fabric.properties
|
64
app/yolov5/.pre-commit-config.yaml
Normal file
64
app/yolov5/.pre-commit-config.yaml
Normal file
@ -0,0 +1,64 @@
|
||||
# Define hooks for code formations
|
||||
# Will be applied on any updated commit files if a user has installed and linked commit hook
|
||||
|
||||
default_language_version:
|
||||
python: python3.8
|
||||
|
||||
# Define bot property if installed via https://github.com/marketplace/pre-commit-ci
|
||||
ci:
|
||||
autofix_prs: true
|
||||
autoupdate_commit_msg: '[pre-commit.ci] pre-commit suggestions'
|
||||
autoupdate_schedule: monthly
|
||||
# submodules: true
|
||||
|
||||
repos:
|
||||
- repo: https://github.com/pre-commit/pre-commit-hooks
|
||||
rev: v4.3.0
|
||||
hooks:
|
||||
# - id: end-of-file-fixer
|
||||
- id: trailing-whitespace
|
||||
- id: check-case-conflict
|
||||
- id: check-yaml
|
||||
- id: check-toml
|
||||
- id: pretty-format-json
|
||||
- id: check-docstring-first
|
||||
|
||||
- repo: https://github.com/asottile/pyupgrade
|
||||
rev: v2.37.3
|
||||
hooks:
|
||||
- id: pyupgrade
|
||||
name: Upgrade code
|
||||
args: [ --py37-plus ]
|
||||
|
||||
- repo: https://github.com/PyCQA/isort
|
||||
rev: 5.10.1
|
||||
hooks:
|
||||
- id: isort
|
||||
name: Sort imports
|
||||
|
||||
- repo: https://github.com/pre-commit/mirrors-yapf
|
||||
rev: v0.32.0
|
||||
hooks:
|
||||
- id: yapf
|
||||
name: YAPF formatting
|
||||
|
||||
- repo: https://github.com/executablebooks/mdformat
|
||||
rev: 0.7.14
|
||||
hooks:
|
||||
- id: mdformat
|
||||
name: MD formatting
|
||||
additional_dependencies:
|
||||
- mdformat-gfm
|
||||
- mdformat-black
|
||||
exclude: "README.md|README_cn.md"
|
||||
|
||||
- repo: https://github.com/asottile/yesqa
|
||||
rev: v1.3.0
|
||||
hooks:
|
||||
- id: yesqa
|
||||
|
||||
- repo: https://github.com/PyCQA/flake8
|
||||
rev: 5.0.2
|
||||
hooks:
|
||||
- id: flake8
|
||||
name: PEP8
|
93
app/yolov5/CONTRIBUTING.md
Normal file
93
app/yolov5/CONTRIBUTING.md
Normal file
@ -0,0 +1,93 @@
|
||||
## Contributing to YOLOv5 🚀
|
||||
|
||||
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible, whether it's:
|
||||
|
||||
- Reporting a bug
|
||||
- Discussing the current state of the code
|
||||
- Submitting a fix
|
||||
- Proposing a new feature
|
||||
- Becoming a maintainer
|
||||
|
||||
YOLOv5 works so well due to our combined community effort, and for every small improvement you contribute you will be
|
||||
helping push the frontiers of what's possible in AI 😃!
|
||||
|
||||
## Submitting a Pull Request (PR) 🛠️
|
||||
|
||||
Submitting a PR is easy! This example shows how to submit a PR for updating `requirements.txt` in 4 steps:
|
||||
|
||||
### 1. Select File to Update
|
||||
|
||||
Select `requirements.txt` to update by clicking on it in GitHub.
|
||||
|
||||
<p align="center"><img width="800" alt="PR_step1" src="https://user-images.githubusercontent.com/26833433/122260847-08be2600-ced4-11eb-828b-8287ace4136c.png"></p>
|
||||
|
||||
### 2. Click 'Edit this file'
|
||||
|
||||
Button is in top-right corner.
|
||||
|
||||
<p align="center"><img width="800" alt="PR_step2" src="https://user-images.githubusercontent.com/26833433/122260844-06f46280-ced4-11eb-9eec-b8a24be519ca.png"></p>
|
||||
|
||||
### 3. Make Changes
|
||||
|
||||
Change `matplotlib` version from `3.2.2` to `3.3`.
|
||||
|
||||
<p align="center"><img width="800" alt="PR_step3" src="https://user-images.githubusercontent.com/26833433/122260853-0a87e980-ced4-11eb-9fd2-3650fb6e0842.png"></p>
|
||||
|
||||
### 4. Preview Changes and Submit PR
|
||||
|
||||
Click on the **Preview changes** tab to verify your updates. At the bottom of the screen select 'Create a **new branch**
|
||||
for this commit', assign your branch a descriptive name such as `fix/matplotlib_version` and click the green **Propose
|
||||
changes** button. All done, your PR is now submitted to YOLOv5 for review and approval 😃!
|
||||
|
||||
<p align="center"><img width="800" alt="PR_step4" src="https://user-images.githubusercontent.com/26833433/122260856-0b208000-ced4-11eb-8e8e-77b6151cbcc3.png"></p>
|
||||
|
||||
### PR recommendations
|
||||
|
||||
To allow your work to be integrated as seamlessly as possible, we advise you to:
|
||||
|
||||
- ✅ Verify your PR is **up-to-date** with `ultralytics/yolov5` `master` branch. If your PR is behind you can update
|
||||
your code by clicking the 'Update branch' button or by running `git pull` and `git merge master` locally.
|
||||
|
||||
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 15" src="https://user-images.githubusercontent.com/26833433/187295893-50ed9f44-b2c9-4138-a614-de69bd1753d7.png"></p>
|
||||
|
||||
- ✅ Verify all YOLOv5 Continuous Integration (CI) **checks are passing**.
|
||||
|
||||
<p align="center"><img width="751" alt="Screenshot 2022-08-29 at 22 47 03" src="https://user-images.githubusercontent.com/26833433/187296922-545c5498-f64a-4d8c-8300-5fa764360da6.png"></p>
|
||||
|
||||
- ✅ Reduce changes to the absolute **minimum** required for your bug fix or feature addition. _"It is not daily increase
|
||||
but daily decrease, hack away the unessential. The closer to the source, the less wastage there is."_ — Bruce Lee
|
||||
|
||||
## Submitting a Bug Report 🐛
|
||||
|
||||
If you spot a problem with YOLOv5 please submit a Bug Report!
|
||||
|
||||
For us to start investigating a possible problem we need to be able to reproduce it ourselves first. We've created a few
|
||||
short guidelines below to help users provide what we need in order to get started.
|
||||
|
||||
When asking a question, people will be better able to provide help if you provide **code** that they can easily
|
||||
understand and use to **reproduce** the problem. This is referred to by community members as creating
|
||||
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example). Your code that reproduces
|
||||
the problem should be:
|
||||
|
||||
- ✅ **Minimal** – Use as little code as possible that still produces the same problem
|
||||
- ✅ **Complete** – Provide **all** parts someone else needs to reproduce your problem in the question itself
|
||||
- ✅ **Reproducible** – Test the code you're about to provide to make sure it reproduces the problem
|
||||
|
||||
In addition to the above requirements, for [Ultralytics](https://ultralytics.com/) to provide assistance your code
|
||||
should be:
|
||||
|
||||
- ✅ **Current** – Verify that your code is up-to-date with current
|
||||
GitHub [master](https://github.com/ultralytics/yolov5/tree/master), and if necessary `git pull` or `git clone` a new
|
||||
copy to ensure your problem has not already been resolved by previous commits.
|
||||
- ✅ **Unmodified** – Your problem must be reproducible without any modifications to the codebase in this
|
||||
repository. [Ultralytics](https://ultralytics.com/) does not provide support for custom code ⚠️.
|
||||
|
||||
If you believe your problem meets all of the above criteria, please close this issue and raise a new one using the 🐛
|
||||
**Bug Report** [template](https://github.com/ultralytics/yolov5/issues/new/choose) and providing
|
||||
a [minimum reproducible example](https://stackoverflow.com/help/minimal-reproducible-example) to help us better
|
||||
understand and diagnose your problem.
|
||||
|
||||
## License
|
||||
|
||||
By contributing, you agree that your contributions will be licensed under
|
||||
the [GPL-3.0 license](https://choosealicense.com/licenses/gpl-3.0/)
|
674
app/yolov5/LICENSE
Normal file
674
app/yolov5/LICENSE
Normal file
@ -0,0 +1,674 @@
|
||||
GNU GENERAL PUBLIC LICENSE
|
||||
Version 3, 29 June 2007
|
||||
|
||||
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
|
||||
Everyone is permitted to copy and distribute verbatim copies
|
||||
of this license document, but changing it is not allowed.
|
||||
|
||||
Preamble
|
||||
|
||||
The GNU General Public License is a free, copyleft license for
|
||||
software and other kinds of works.
|
||||
|
||||
The licenses for most software and other practical works are designed
|
||||
to take away your freedom to share and change the works. By contrast,
|
||||
the GNU General Public License is intended to guarantee your freedom to
|
||||
share and change all versions of a program--to make sure it remains free
|
||||
software for all its users. We, the Free Software Foundation, use the
|
||||
GNU General Public License for most of our software; it applies also to
|
||||
any other work released this way by its authors. You can apply it to
|
||||
your programs, too.
|
||||
|
||||
When we speak of free software, we are referring to freedom, not
|
||||
price. Our General Public Licenses are designed to make sure that you
|
||||
have the freedom to distribute copies of free software (and charge for
|
||||
them if you wish), that you receive source code or can get it if you
|
||||
want it, that you can change the software or use pieces of it in new
|
||||
free programs, and that you know you can do these things.
|
||||
|
||||
To protect your rights, we need to prevent others from denying you
|
||||
these rights or asking you to surrender the rights. Therefore, you have
|
||||
certain responsibilities if you distribute copies of the software, or if
|
||||
you modify it: responsibilities to respect the freedom of others.
|
||||
|
||||
For example, if you distribute copies of such a program, whether
|
||||
gratis or for a fee, you must pass on to the recipients the same
|
||||
freedoms that you received. You must make sure that they, too, receive
|
||||
or can get the source code. And you must show them these terms so they
|
||||
know their rights.
|
||||
|
||||
Developers that use the GNU GPL protect your rights with two steps:
|
||||
(1) assert copyright on the software, and (2) offer you this License
|
||||
giving you legal permission to copy, distribute and/or modify it.
|
||||
|
||||
For the developers' and authors' protection, the GPL clearly explains
|
||||
that there is no warranty for this free software. For both users' and
|
||||
authors' sake, the GPL requires that modified versions be marked as
|
||||
changed, so that their problems will not be attributed erroneously to
|
||||
authors of previous versions.
|
||||
|
||||
Some devices are designed to deny users access to install or run
|
||||
modified versions of the software inside them, although the manufacturer
|
||||
can do so. This is fundamentally incompatible with the aim of
|
||||
protecting users' freedom to change the software. The systematic
|
||||
pattern of such abuse occurs in the area of products for individuals to
|
||||
use, which is precisely where it is most unacceptable. Therefore, we
|
||||
have designed this version of the GPL to prohibit the practice for those
|
||||
products. If such problems arise substantially in other domains, we
|
||||
stand ready to extend this provision to those domains in future versions
|
||||
of the GPL, as needed to protect the freedom of users.
|
||||
|
||||
Finally, every program is threatened constantly by software patents.
|
||||
States should not allow patents to restrict development and use of
|
||||
software on general-purpose computers, but in those that do, we wish to
|
||||
avoid the special danger that patents applied to a free program could
|
||||
make it effectively proprietary. To prevent this, the GPL assures that
|
||||
patents cannot be used to render the program non-free.
|
||||
|
||||
The precise terms and conditions for copying, distribution and
|
||||
modification follow.
|
||||
|
||||
TERMS AND CONDITIONS
|
||||
|
||||
0. Definitions.
|
||||
|
||||
"This License" refers to version 3 of the GNU General Public License.
|
||||
|
||||
"Copyright" also means copyright-like laws that apply to other kinds of
|
||||
works, such as semiconductor masks.
|
||||
|
||||
"The Program" refers to any copyrightable work licensed under this
|
||||
License. Each licensee is addressed as "you". "Licensees" and
|
||||
"recipients" may be individuals or organizations.
|
||||
|
||||
To "modify" a work means to copy from or adapt all or part of the work
|
||||
in a fashion requiring copyright permission, other than the making of an
|
||||
exact copy. The resulting work is called a "modified version" of the
|
||||
earlier work or a work "based on" the earlier work.
|
||||
|
||||
A "covered work" means either the unmodified Program or a work based
|
||||
on the Program.
|
||||
|
||||
To "propagate" a work means to do anything with it that, without
|
||||
permission, would make you directly or secondarily liable for
|
||||
infringement under applicable copyright law, except executing it on a
|
||||
computer or modifying a private copy. Propagation includes copying,
|
||||
distribution (with or without modification), making available to the
|
||||
public, and in some countries other activities as well.
|
||||
|
||||
To "convey" a work means any kind of propagation that enables other
|
||||
parties to make or receive copies. Mere interaction with a user through
|
||||
a computer network, with no transfer of a copy, is not conveying.
|
||||
|
||||
An interactive user interface displays "Appropriate Legal Notices"
|
||||
to the extent that it includes a convenient and prominently visible
|
||||
feature that (1) displays an appropriate copyright notice, and (2)
|
||||
tells the user that there is no warranty for the work (except to the
|
||||
extent that warranties are provided), that licensees may convey the
|
||||
work under this License, and how to view a copy of this License. If
|
||||
the interface presents a list of user commands or options, such as a
|
||||
menu, a prominent item in the list meets this criterion.
|
||||
|
||||
1. Source Code.
|
||||
|
||||
The "source code" for a work means the preferred form of the work
|
||||
for making modifications to it. "Object code" means any non-source
|
||||
form of a work.
|
||||
|
||||
A "Standard Interface" means an interface that either is an official
|
||||
standard defined by a recognized standards body, or, in the case of
|
||||
interfaces specified for a particular programming language, one that
|
||||
is widely used among developers working in that language.
|
||||
|
||||
The "System Libraries" of an executable work include anything, other
|
||||
than the work as a whole, that (a) is included in the normal form of
|
||||
packaging a Major Component, but which is not part of that Major
|
||||
Component, and (b) serves only to enable use of the work with that
|
||||
Major Component, or to implement a Standard Interface for which an
|
||||
implementation is available to the public in source code form. A
|
||||
"Major Component", in this context, means a major essential component
|
||||
(kernel, window system, and so on) of the specific operating system
|
||||
(if any) on which the executable work runs, or a compiler used to
|
||||
produce the work, or an object code interpreter used to run it.
|
||||
|
||||
The "Corresponding Source" for a work in object code form means all
|
||||
the source code needed to generate, install, and (for an executable
|
||||
work) run the object code and to modify the work, including scripts to
|
||||
control those activities. However, it does not include the work's
|
||||
System Libraries, or general-purpose tools or generally available free
|
||||
programs which are used unmodified in performing those activities but
|
||||
which are not part of the work. For example, Corresponding Source
|
||||
includes interface definition files associated with source files for
|
||||
the work, and the source code for shared libraries and dynamically
|
||||
linked subprograms that the work is specifically designed to require,
|
||||
such as by intimate data communication or control flow between those
|
||||
subprograms and other parts of the work.
|
||||
|
||||
The Corresponding Source need not include anything that users
|
||||
can regenerate automatically from other parts of the Corresponding
|
||||
Source.
|
||||
|
||||
The Corresponding Source for a work in source code form is that
|
||||
same work.
|
||||
|
||||
2. Basic Permissions.
|
||||
|
||||
All rights granted under this License are granted for the term of
|
||||
copyright on the Program, and are irrevocable provided the stated
|
||||
conditions are met. This License explicitly affirms your unlimited
|
||||
permission to run the unmodified Program. The output from running a
|
||||
covered work is covered by this License only if the output, given its
|
||||
content, constitutes a covered work. This License acknowledges your
|
||||
rights of fair use or other equivalent, as provided by copyright law.
|
||||
|
||||
You may make, run and propagate covered works that you do not
|
||||
convey, without conditions so long as your license otherwise remains
|
||||
in force. You may convey covered works to others for the sole purpose
|
||||
of having them make modifications exclusively for you, or provide you
|
||||
with facilities for running those works, provided that you comply with
|
||||
the terms of this License in conveying all material for which you do
|
||||
not control copyright. Those thus making or running the covered works
|
||||
for you must do so exclusively on your behalf, under your direction
|
||||
and control, on terms that prohibit them from making any copies of
|
||||
your copyrighted material outside their relationship with you.
|
||||
|
||||
Conveying under any other circumstances is permitted solely under
|
||||
the conditions stated below. Sublicensing is not allowed; section 10
|
||||
makes it unnecessary.
|
||||
|
||||
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
|
||||
|
||||
No covered work shall be deemed part of an effective technological
|
||||
measure under any applicable law fulfilling obligations under article
|
||||
11 of the WIPO copyright treaty adopted on 20 December 1996, or
|
||||
similar laws prohibiting or restricting circumvention of such
|
||||
measures.
|
||||
|
||||
When you convey a covered work, you waive any legal power to forbid
|
||||
circumvention of technological measures to the extent such circumvention
|
||||
is effected by exercising rights under this License with respect to
|
||||
the covered work, and you disclaim any intention to limit operation or
|
||||
modification of the work as a means of enforcing, against the work's
|
||||
users, your or third parties' legal rights to forbid circumvention of
|
||||
technological measures.
|
||||
|
||||
4. Conveying Verbatim Copies.
|
||||
|
||||
You may convey verbatim copies of the Program's source code as you
|
||||
receive it, in any medium, provided that you conspicuously and
|
||||
appropriately publish on each copy an appropriate copyright notice;
|
||||
keep intact all notices stating that this License and any
|
||||
non-permissive terms added in accord with section 7 apply to the code;
|
||||
keep intact all notices of the absence of any warranty; and give all
|
||||
recipients a copy of this License along with the Program.
|
||||
|
||||
You may charge any price or no price for each copy that you convey,
|
||||
and you may offer support or warranty protection for a fee.
|
||||
|
||||
5. Conveying Modified Source Versions.
|
||||
|
||||
You may convey a work based on the Program, or the modifications to
|
||||
produce it from the Program, in the form of source code under the
|
||||
terms of section 4, provided that you also meet all of these conditions:
|
||||
|
||||
a) The work must carry prominent notices stating that you modified
|
||||
it, and giving a relevant date.
|
||||
|
||||
b) The work must carry prominent notices stating that it is
|
||||
released under this License and any conditions added under section
|
||||
7. This requirement modifies the requirement in section 4 to
|
||||
"keep intact all notices".
|
||||
|
||||
c) You must license the entire work, as a whole, under this
|
||||
License to anyone who comes into possession of a copy. This
|
||||
License will therefore apply, along with any applicable section 7
|
||||
additional terms, to the whole of the work, and all its parts,
|
||||
regardless of how they are packaged. This License gives no
|
||||
permission to license the work in any other way, but it does not
|
||||
invalidate such permission if you have separately received it.
|
||||
|
||||
d) If the work has interactive user interfaces, each must display
|
||||
Appropriate Legal Notices; however, if the Program has interactive
|
||||
interfaces that do not display Appropriate Legal Notices, your
|
||||
work need not make them do so.
|
||||
|
||||
A compilation of a covered work with other separate and independent
|
||||
works, which are not by their nature extensions of the covered work,
|
||||
and which are not combined with it such as to form a larger program,
|
||||
in or on a volume of a storage or distribution medium, is called an
|
||||
"aggregate" if the compilation and its resulting copyright are not
|
||||
used to limit the access or legal rights of the compilation's users
|
||||
beyond what the individual works permit. Inclusion of a covered work
|
||||
in an aggregate does not cause this License to apply to the other
|
||||
parts of the aggregate.
|
||||
|
||||
6. Conveying Non-Source Forms.
|
||||
|
||||
You may convey a covered work in object code form under the terms
|
||||
of sections 4 and 5, provided that you also convey the
|
||||
machine-readable Corresponding Source under the terms of this License,
|
||||
in one of these ways:
|
||||
|
||||
a) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by the
|
||||
Corresponding Source fixed on a durable physical medium
|
||||
customarily used for software interchange.
|
||||
|
||||
b) Convey the object code in, or embodied in, a physical product
|
||||
(including a physical distribution medium), accompanied by a
|
||||
written offer, valid for at least three years and valid for as
|
||||
long as you offer spare parts or customer support for that product
|
||||
model, to give anyone who possesses the object code either (1) a
|
||||
copy of the Corresponding Source for all the software in the
|
||||
product that is covered by this License, on a durable physical
|
||||
medium customarily used for software interchange, for a price no
|
||||
more than your reasonable cost of physically performing this
|
||||
conveying of source, or (2) access to copy the
|
||||
Corresponding Source from a network server at no charge.
|
||||
|
||||
c) Convey individual copies of the object code with a copy of the
|
||||
written offer to provide the Corresponding Source. This
|
||||
alternative is allowed only occasionally and noncommercially, and
|
||||
only if you received the object code with such an offer, in accord
|
||||
with subsection 6b.
|
||||
|
||||
d) Convey the object code by offering access from a designated
|
||||
place (gratis or for a charge), and offer equivalent access to the
|
||||
Corresponding Source in the same way through the same place at no
|
||||
further charge. You need not require recipients to copy the
|
||||
Corresponding Source along with the object code. If the place to
|
||||
copy the object code is a network server, the Corresponding Source
|
||||
may be on a different server (operated by you or a third party)
|
||||
that supports equivalent copying facilities, provided you maintain
|
||||
clear directions next to the object code saying where to find the
|
||||
Corresponding Source. Regardless of what server hosts the
|
||||
Corresponding Source, you remain obligated to ensure that it is
|
||||
available for as long as needed to satisfy these requirements.
|
||||
|
||||
e) Convey the object code using peer-to-peer transmission, provided
|
||||
you inform other peers where the object code and Corresponding
|
||||
Source of the work are being offered to the general public at no
|
||||
charge under subsection 6d.
|
||||
|
||||
A separable portion of the object code, whose source code is excluded
|
||||
from the Corresponding Source as a System Library, need not be
|
||||
included in conveying the object code work.
|
||||
|
||||
A "User Product" is either (1) a "consumer product", which means any
|
||||
tangible personal property which is normally used for personal, family,
|
||||
or household purposes, or (2) anything designed or sold for incorporation
|
||||
into a dwelling. In determining whether a product is a consumer product,
|
||||
doubtful cases shall be resolved in favor of coverage. For a particular
|
||||
product received by a particular user, "normally used" refers to a
|
||||
typical or common use of that class of product, regardless of the status
|
||||
of the particular user or of the way in which the particular user
|
||||
actually uses, or expects or is expected to use, the product. A product
|
||||
is a consumer product regardless of whether the product has substantial
|
||||
commercial, industrial or non-consumer uses, unless such uses represent
|
||||
the only significant mode of use of the product.
|
||||
|
||||
"Installation Information" for a User Product means any methods,
|
||||
procedures, authorization keys, or other information required to install
|
||||
and execute modified versions of a covered work in that User Product from
|
||||
a modified version of its Corresponding Source. The information must
|
||||
suffice to ensure that the continued functioning of the modified object
|
||||
code is in no case prevented or interfered with solely because
|
||||
modification has been made.
|
||||
|
||||
If you convey an object code work under this section in, or with, or
|
||||
specifically for use in, a User Product, and the conveying occurs as
|
||||
part of a transaction in which the right of possession and use of the
|
||||
User Product is transferred to the recipient in perpetuity or for a
|
||||
fixed term (regardless of how the transaction is characterized), the
|
||||
Corresponding Source conveyed under this section must be accompanied
|
||||
by the Installation Information. But this requirement does not apply
|
||||
if neither you nor any third party retains the ability to install
|
||||
modified object code on the User Product (for example, the work has
|
||||
been installed in ROM).
|
||||
|
||||
The requirement to provide Installation Information does not include a
|
||||
requirement to continue to provide support service, warranty, or updates
|
||||
for a work that has been modified or installed by the recipient, or for
|
||||
the User Product in which it has been modified or installed. Access to a
|
||||
network may be denied when the modification itself materially and
|
||||
adversely affects the operation of the network or violates the rules and
|
||||
protocols for communication across the network.
|
||||
|
||||
Corresponding Source conveyed, and Installation Information provided,
|
||||
in accord with this section must be in a format that is publicly
|
||||
documented (and with an implementation available to the public in
|
||||
source code form), and must require no special password or key for
|
||||
unpacking, reading or copying.
|
||||
|
||||
7. Additional Terms.
|
||||
|
||||
"Additional permissions" are terms that supplement the terms of this
|
||||
License by making exceptions from one or more of its conditions.
|
||||
Additional permissions that are applicable to the entire Program shall
|
||||
be treated as though they were included in this License, to the extent
|
||||
that they are valid under applicable law. If additional permissions
|
||||
apply only to part of the Program, that part may be used separately
|
||||
under those permissions, but the entire Program remains governed by
|
||||
this License without regard to the additional permissions.
|
||||
|
||||
When you convey a copy of a covered work, you may at your option
|
||||
remove any additional permissions from that copy, or from any part of
|
||||
it. (Additional permissions may be written to require their own
|
||||
removal in certain cases when you modify the work.) You may place
|
||||
additional permissions on material, added by you to a covered work,
|
||||
for which you have or can give appropriate copyright permission.
|
||||
|
||||
Notwithstanding any other provision of this License, for material you
|
||||
add to a covered work, you may (if authorized by the copyright holders of
|
||||
that material) supplement the terms of this License with terms:
|
||||
|
||||
a) Disclaiming warranty or limiting liability differently from the
|
||||
terms of sections 15 and 16 of this License; or
|
||||
|
||||
b) Requiring preservation of specified reasonable legal notices or
|
||||
author attributions in that material or in the Appropriate Legal
|
||||
Notices displayed by works containing it; or
|
||||
|
||||
c) Prohibiting misrepresentation of the origin of that material, or
|
||||
requiring that modified versions of such material be marked in
|
||||
reasonable ways as different from the original version; or
|
||||
|
||||
d) Limiting the use for publicity purposes of names of licensors or
|
||||
authors of the material; or
|
||||
|
||||
e) Declining to grant rights under trademark law for use of some
|
||||
trade names, trademarks, or service marks; or
|
||||
|
||||
f) Requiring indemnification of licensors and authors of that
|
||||
material by anyone who conveys the material (or modified versions of
|
||||
it) with contractual assumptions of liability to the recipient, for
|
||||
any liability that these contractual assumptions directly impose on
|
||||
those licensors and authors.
|
||||
|
||||
All other non-permissive additional terms are considered "further
|
||||
restrictions" within the meaning of section 10. If the Program as you
|
||||
received it, or any part of it, contains a notice stating that it is
|
||||
governed by this License along with a term that is a further
|
||||
restriction, you may remove that term. If a license document contains
|
||||
a further restriction but permits relicensing or conveying under this
|
||||
License, you may add to a covered work material governed by the terms
|
||||
of that license document, provided that the further restriction does
|
||||
not survive such relicensing or conveying.
|
||||
|
||||
If you add terms to a covered work in accord with this section, you
|
||||
must place, in the relevant source files, a statement of the
|
||||
additional terms that apply to those files, or a notice indicating
|
||||
where to find the applicable terms.
|
||||
|
||||
Additional terms, permissive or non-permissive, may be stated in the
|
||||
form of a separately written license, or stated as exceptions;
|
||||
the above requirements apply either way.
|
||||
|
||||
8. Termination.
|
||||
|
||||
You may not propagate or modify a covered work except as expressly
|
||||
provided under this License. Any attempt otherwise to propagate or
|
||||
modify it is void, and will automatically terminate your rights under
|
||||
this License (including any patent licenses granted under the third
|
||||
paragraph of section 11).
|
||||
|
||||
However, if you cease all violation of this License, then your
|
||||
license from a particular copyright holder is reinstated (a)
|
||||
provisionally, unless and until the copyright holder explicitly and
|
||||
finally terminates your license, and (b) permanently, if the copyright
|
||||
holder fails to notify you of the violation by some reasonable means
|
||||
prior to 60 days after the cessation.
|
||||
|
||||
Moreover, your license from a particular copyright holder is
|
||||
reinstated permanently if the copyright holder notifies you of the
|
||||
violation by some reasonable means, this is the first time you have
|
||||
received notice of violation of this License (for any work) from that
|
||||
copyright holder, and you cure the violation prior to 30 days after
|
||||
your receipt of the notice.
|
||||
|
||||
Termination of your rights under this section does not terminate the
|
||||
licenses of parties who have received copies or rights from you under
|
||||
this License. If your rights have been terminated and not permanently
|
||||
reinstated, you do not qualify to receive new licenses for the same
|
||||
material under section 10.
|
||||
|
||||
9. Acceptance Not Required for Having Copies.
|
||||
|
||||
You are not required to accept this License in order to receive or
|
||||
run a copy of the Program. Ancillary propagation of a covered work
|
||||
occurring solely as a consequence of using peer-to-peer transmission
|
||||
to receive a copy likewise does not require acceptance. However,
|
||||
nothing other than this License grants you permission to propagate or
|
||||
modify any covered work. These actions infringe copyright if you do
|
||||
not accept this License. Therefore, by modifying or propagating a
|
||||
covered work, you indicate your acceptance of this License to do so.
|
||||
|
||||
10. Automatic Licensing of Downstream Recipients.
|
||||
|
||||
Each time you convey a covered work, the recipient automatically
|
||||
receives a license from the original licensors, to run, modify and
|
||||
propagate that work, subject to this License. You are not responsible
|
||||
for enforcing compliance by third parties with this License.
|
||||
|
||||
An "entity transaction" is a transaction transferring control of an
|
||||
organization, or substantially all assets of one, or subdividing an
|
||||
organization, or merging organizations. If propagation of a covered
|
||||
work results from an entity transaction, each party to that
|
||||
transaction who receives a copy of the work also receives whatever
|
||||
licenses to the work the party's predecessor in interest had or could
|
||||
give under the previous paragraph, plus a right to possession of the
|
||||
Corresponding Source of the work from the predecessor in interest, if
|
||||
the predecessor has it or can get it with reasonable efforts.
|
||||
|
||||
You may not impose any further restrictions on the exercise of the
|
||||
rights granted or affirmed under this License. For example, you may
|
||||
not impose a license fee, royalty, or other charge for exercise of
|
||||
rights granted under this License, and you may not initiate litigation
|
||||
(including a cross-claim or counterclaim in a lawsuit) alleging that
|
||||
any patent claim is infringed by making, using, selling, offering for
|
||||
sale, or importing the Program or any portion of it.
|
||||
|
||||
11. Patents.
|
||||
|
||||
A "contributor" is a copyright holder who authorizes use under this
|
||||
License of the Program or a work on which the Program is based. The
|
||||
work thus licensed is called the contributor's "contributor version".
|
||||
|
||||
A contributor's "essential patent claims" are all patent claims
|
||||
owned or controlled by the contributor, whether already acquired or
|
||||
hereafter acquired, that would be infringed by some manner, permitted
|
||||
by this License, of making, using, or selling its contributor version,
|
||||
but do not include claims that would be infringed only as a
|
||||
consequence of further modification of the contributor version. For
|
||||
purposes of this definition, "control" includes the right to grant
|
||||
patent sublicenses in a manner consistent with the requirements of
|
||||
this License.
|
||||
|
||||
Each contributor grants you a non-exclusive, worldwide, royalty-free
|
||||
patent license under the contributor's essential patent claims, to
|
||||
make, use, sell, offer for sale, import and otherwise run, modify and
|
||||
propagate the contents of its contributor version.
|
||||
|
||||
In the following three paragraphs, a "patent license" is any express
|
||||
agreement or commitment, however denominated, not to enforce a patent
|
||||
(such as an express permission to practice a patent or covenant not to
|
||||
sue for patent infringement). To "grant" such a patent license to a
|
||||
party means to make such an agreement or commitment not to enforce a
|
||||
patent against the party.
|
||||
|
||||
If you convey a covered work, knowingly relying on a patent license,
|
||||
and the Corresponding Source of the work is not available for anyone
|
||||
to copy, free of charge and under the terms of this License, through a
|
||||
publicly available network server or other readily accessible means,
|
||||
then you must either (1) cause the Corresponding Source to be so
|
||||
available, or (2) arrange to deprive yourself of the benefit of the
|
||||
patent license for this particular work, or (3) arrange, in a manner
|
||||
consistent with the requirements of this License, to extend the patent
|
||||
license to downstream recipients. "Knowingly relying" means you have
|
||||
actual knowledge that, but for the patent license, your conveying the
|
||||
covered work in a country, or your recipient's use of the covered work
|
||||
in a country, would infringe one or more identifiable patents in that
|
||||
country that you have reason to believe are valid.
|
||||
|
||||
If, pursuant to or in connection with a single transaction or
|
||||
arrangement, you convey, or propagate by procuring conveyance of, a
|
||||
covered work, and grant a patent license to some of the parties
|
||||
receiving the covered work authorizing them to use, propagate, modify
|
||||
or convey a specific copy of the covered work, then the patent license
|
||||
you grant is automatically extended to all recipients of the covered
|
||||
work and works based on it.
|
||||
|
||||
A patent license is "discriminatory" if it does not include within
|
||||
the scope of its coverage, prohibits the exercise of, or is
|
||||
conditioned on the non-exercise of one or more of the rights that are
|
||||
specifically granted under this License. You may not convey a covered
|
||||
work if you are a party to an arrangement with a third party that is
|
||||
in the business of distributing software, under which you make payment
|
||||
to the third party based on the extent of your activity of conveying
|
||||
the work, and under which the third party grants, to any of the
|
||||
parties who would receive the covered work from you, a discriminatory
|
||||
patent license (a) in connection with copies of the covered work
|
||||
conveyed by you (or copies made from those copies), or (b) primarily
|
||||
for and in connection with specific products or compilations that
|
||||
contain the covered work, unless you entered into that arrangement,
|
||||
or that patent license was granted, prior to 28 March 2007.
|
||||
|
||||
Nothing in this License shall be construed as excluding or limiting
|
||||
any implied license or other defenses to infringement that may
|
||||
otherwise be available to you under applicable patent law.
|
||||
|
||||
12. No Surrender of Others' Freedom.
|
||||
|
||||
If conditions are imposed on you (whether by court order, agreement or
|
||||
otherwise) that contradict the conditions of this License, they do not
|
||||
excuse you from the conditions of this License. If you cannot convey a
|
||||
covered work so as to satisfy simultaneously your obligations under this
|
||||
License and any other pertinent obligations, then as a consequence you may
|
||||
not convey it at all. For example, if you agree to terms that obligate you
|
||||
to collect a royalty for further conveying from those to whom you convey
|
||||
the Program, the only way you could satisfy both those terms and this
|
||||
License would be to refrain entirely from conveying the Program.
|
||||
|
||||
13. Use with the GNU Affero General Public License.
|
||||
|
||||
Notwithstanding any other provision of this License, you have
|
||||
permission to link or combine any covered work with a work licensed
|
||||
under version 3 of the GNU Affero General Public License into a single
|
||||
combined work, and to convey the resulting work. The terms of this
|
||||
License will continue to apply to the part which is the covered work,
|
||||
but the special requirements of the GNU Affero General Public License,
|
||||
section 13, concerning interaction through a network will apply to the
|
||||
combination as such.
|
||||
|
||||
14. Revised Versions of this License.
|
||||
|
||||
The Free Software Foundation may publish revised and/or new versions of
|
||||
the GNU General Public License from time to time. Such new versions will
|
||||
be similar in spirit to the present version, but may differ in detail to
|
||||
address new problems or concerns.
|
||||
|
||||
Each version is given a distinguishing version number. If the
|
||||
Program specifies that a certain numbered version of the GNU General
|
||||
Public License "or any later version" applies to it, you have the
|
||||
option of following the terms and conditions either of that numbered
|
||||
version or of any later version published by the Free Software
|
||||
Foundation. If the Program does not specify a version number of the
|
||||
GNU General Public License, you may choose any version ever published
|
||||
by the Free Software Foundation.
|
||||
|
||||
If the Program specifies that a proxy can decide which future
|
||||
versions of the GNU General Public License can be used, that proxy's
|
||||
public statement of acceptance of a version permanently authorizes you
|
||||
to choose that version for the Program.
|
||||
|
||||
Later license versions may give you additional or different
|
||||
permissions. However, no additional obligations are imposed on any
|
||||
author or copyright holder as a result of your choosing to follow a
|
||||
later version.
|
||||
|
||||
15. Disclaimer of Warranty.
|
||||
|
||||
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
|
||||
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
|
||||
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
|
||||
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
|
||||
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
|
||||
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
|
||||
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
|
||||
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
|
||||
|
||||
16. Limitation of Liability.
|
||||
|
||||
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
|
||||
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
|
||||
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
|
||||
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
|
||||
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
|
||||
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
|
||||
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
|
||||
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
|
||||
SUCH DAMAGES.
|
||||
|
||||
17. Interpretation of Sections 15 and 16.
|
||||
|
||||
If the disclaimer of warranty and limitation of liability provided
|
||||
above cannot be given local legal effect according to their terms,
|
||||
reviewing courts shall apply local law that most closely approximates
|
||||
an absolute waiver of all civil liability in connection with the
|
||||
Program, unless a warranty or assumption of liability accompanies a
|
||||
copy of the Program in return for a fee.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
How to Apply These Terms to Your New Programs
|
||||
|
||||
If you develop a new program, and you want it to be of the greatest
|
||||
possible use to the public, the best way to achieve this is to make it
|
||||
free software which everyone can redistribute and change under these terms.
|
||||
|
||||
To do so, attach the following notices to the program. It is safest
|
||||
to attach them to the start of each source file to most effectively
|
||||
state the exclusion of warranty; and each file should have at least
|
||||
the "copyright" line and a pointer to where the full notice is found.
|
||||
|
||||
<one line to give the program's name and a brief idea of what it does.>
|
||||
Copyright (C) <year> <name of author>
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
it under the terms of the GNU General Public License as published by
|
||||
the Free Software Foundation, either version 3 of the License, or
|
||||
(at your option) any later version.
|
||||
|
||||
This program is distributed in the hope that it will be useful,
|
||||
but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
GNU General Public License for more details.
|
||||
|
||||
You should have received a copy of the GNU General Public License
|
||||
along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
Also add information on how to contact you by electronic and paper mail.
|
||||
|
||||
If the program does terminal interaction, make it output a short
|
||||
notice like this when it starts in an interactive mode:
|
||||
|
||||
<program> Copyright (C) <year> <name of author>
|
||||
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
|
||||
This is free software, and you are welcome to redistribute it
|
||||
under certain conditions; type `show c' for details.
|
||||
|
||||
The hypothetical commands `show w' and `show c' should show the appropriate
|
||||
parts of the General Public License. Of course, your program's commands
|
||||
might be different; for a GUI interface, you would use an "about box".
|
||||
|
||||
You should also get your employer (if you work as a programmer) or school,
|
||||
if any, to sign a "copyright disclaimer" for the program, if necessary.
|
||||
For more information on this, and how to apply and follow the GNU GPL, see
|
||||
<http://www.gnu.org/licenses/>.
|
||||
|
||||
The GNU General Public License does not permit incorporating your program
|
||||
into proprietary programs. If your program is a subroutine library, you
|
||||
may consider it more useful to permit linking proprietary applications with
|
||||
the library. If this is what you want to do, use the GNU Lesser General
|
||||
Public License instead of this License. But first, please read
|
||||
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
|
363
app/yolov5/README.md
Normal file
363
app/yolov5/README.md
Normal file
@ -0,0 +1,363 @@
|
||||
<div align="center">
|
||||
<p>
|
||||
<a align="center" href="https://ultralytics.com/yolov5" target="_blank">
|
||||
<img width="850" src="https://github.com/ultralytics/assets/raw/master/yolov5/v62/splash_readme.png"></a>
|
||||
<br><br>
|
||||
<a href="https://play.google.com/store/apps/details?id=com.ultralytics.ultralytics_app" style="text-decoration:none;">
|
||||
<img src="https://raw.githubusercontent.com/ultralytics/assets/master/app/google-play.svg" width="15%" alt="" /></a>
|
||||
<a href="https://apps.apple.com/xk/app/ultralytics/id1583935240" style="text-decoration:none;">
|
||||
<img src="https://raw.githubusercontent.com/ultralytics/assets/master/app/app-store.svg" width="15%" alt="" /></a>
|
||||
</p>
|
||||
|
||||
English | [简体中文](.github/README_cn.md)
|
||||
<br>
|
||||
<div>
|
||||
<a href="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml"><img src="https://github.com/ultralytics/yolov5/actions/workflows/ci-testing.yml/badge.svg" alt="CI CPU testing"></a>
|
||||
<a href="https://zenodo.org/badge/latestdoi/264818686"><img src="https://zenodo.org/badge/264818686.svg" alt="YOLOv5 Citation"></a>
|
||||
<a href="https://hub.docker.com/r/ultralytics/yolov5"><img src="https://img.shields.io/docker/pulls/ultralytics/yolov5?logo=docker" alt="Docker Pulls"></a>
|
||||
<br>
|
||||
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb"><img src="https://colab.research.google.com/assets/colab-badge.svg" alt="Open In Colab"></a>
|
||||
<a href="https://www.kaggle.com/ultralytics/yolov5"><img src="https://kaggle.com/static/images/open-in-kaggle.svg" alt="Open In Kaggle"></a>
|
||||
<a href="https://join.slack.com/t/ultralytics/shared_invite/zt-w29ei8bp-jczz7QYUmDtgo6r6KcMIAg"><img src="https://img.shields.io/badge/Slack-Join_Forum-blue.svg?logo=slack" alt="Join Forum"></a>
|
||||
</div>
|
||||
|
||||
<br>
|
||||
<p>
|
||||
YOLOv5 🚀 is a family of object detection architectures and models pretrained on the COCO dataset, and represents <a href="https://ultralytics.com">Ultralytics</a>
|
||||
open-source research into future vision AI methods, incorporating lessons learned and best practices evolved over thousands of hours of research and development.
|
||||
</p>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://github.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="2%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="2%" alt="" />
|
||||
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="2%" alt="" /></a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
## <div align="center">Documentation</div>
|
||||
|
||||
See the [YOLOv5 Docs](https://docs.ultralytics.com) for full documentation on training, testing and deployment.
|
||||
|
||||
## <div align="center">Quick Start Examples</div>
|
||||
|
||||
<details open>
|
||||
<summary>Install</summary>
|
||||
|
||||
Clone repo and install [requirements.txt](https://github.com/ultralytics/yolov5/blob/master/requirements.txt) in a
|
||||
[**Python>=3.7.0**](https://www.python.org/) environment, including
|
||||
[**PyTorch>=1.7**](https://pytorch.org/get-started/locally/).
|
||||
|
||||
```bash
|
||||
git clone https://github.com/ultralytics/yolov5 # clone
|
||||
cd yolov5
|
||||
pip install -r requirements.txt # install
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details open>
|
||||
<summary>Inference</summary>
|
||||
|
||||
YOLOv5 [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) inference. [Models](https://github.com/ultralytics/yolov5/tree/master/models) download automatically from the latest
|
||||
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases).
|
||||
|
||||
```python
|
||||
import torch
|
||||
|
||||
# Model
|
||||
model = torch.hub.load('ultralytics/yolov5', 'yolov5s') # or yolov5n - yolov5x6, custom
|
||||
|
||||
# Images
|
||||
img = 'https://ultralytics.com/images/zidane.jpg' # or file, Path, PIL, OpenCV, numpy, list
|
||||
|
||||
# Inference
|
||||
results = model(img)
|
||||
|
||||
# Results
|
||||
results.print() # or .show(), .save(), .crop(), .pandas(), etc.
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Inference with detect.py</summary>
|
||||
|
||||
`detect.py` runs inference on a variety of sources, downloading [models](https://github.com/ultralytics/yolov5/tree/master/models) automatically from
|
||||
the latest YOLOv5 [release](https://github.com/ultralytics/yolov5/releases) and saving results to `runs/detect`.
|
||||
|
||||
```bash
|
||||
python detect.py --source 0 # webcam
|
||||
img.jpg # image
|
||||
vid.mp4 # video
|
||||
path/ # directory
|
||||
'path/*.jpg' # glob
|
||||
'https://youtu.be/Zgi9g1ksQHc' # YouTube
|
||||
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
||||
```
|
||||
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Training</summary>
|
||||
|
||||
The commands below reproduce YOLOv5 [COCO](https://github.com/ultralytics/yolov5/blob/master/data/scripts/get_coco.sh)
|
||||
results. [Models](https://github.com/ultralytics/yolov5/tree/master/models)
|
||||
and [datasets](https://github.com/ultralytics/yolov5/tree/master/data) download automatically from the latest
|
||||
YOLOv5 [release](https://github.com/ultralytics/yolov5/releases). Training times for YOLOv5n/s/m/l/x are
|
||||
1/2/4/6/8 days on a V100 GPU ([Multi-GPU](https://github.com/ultralytics/yolov5/issues/475) times faster). Use the
|
||||
largest `--batch-size` possible, or pass `--batch-size -1` for
|
||||
YOLOv5 [AutoBatch](https://github.com/ultralytics/yolov5/pull/5092). Batch sizes shown for V100-16GB.
|
||||
|
||||
```bash
|
||||
python train.py --data coco.yaml --cfg yolov5n.yaml --weights '' --batch-size 128
|
||||
yolov5s 64
|
||||
yolov5m 40
|
||||
yolov5l 24
|
||||
yolov5x 16
|
||||
```
|
||||
|
||||
<img width="800" src="https://user-images.githubusercontent.com/26833433/90222759-949d8800-ddc1-11ea-9fa1-1c97eed2b963.png">
|
||||
|
||||
</details>
|
||||
|
||||
<details open>
|
||||
<summary>Tutorials</summary>
|
||||
|
||||
- [Train Custom Data](https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data) 🚀 RECOMMENDED
|
||||
- [Tips for Best Training Results](https://github.com/ultralytics/yolov5/wiki/Tips-for-Best-Training-Results) ☘️
|
||||
RECOMMENDED
|
||||
- [Multi-GPU Training](https://github.com/ultralytics/yolov5/issues/475)
|
||||
- [PyTorch Hub](https://github.com/ultralytics/yolov5/issues/36) 🌟 NEW
|
||||
- [TFLite, ONNX, CoreML, TensorRT Export](https://github.com/ultralytics/yolov5/issues/251) 🚀
|
||||
- [Test-Time Augmentation (TTA)](https://github.com/ultralytics/yolov5/issues/303)
|
||||
- [Model Ensembling](https://github.com/ultralytics/yolov5/issues/318)
|
||||
- [Model Pruning/Sparsity](https://github.com/ultralytics/yolov5/issues/304)
|
||||
- [Hyperparameter Evolution](https://github.com/ultralytics/yolov5/issues/607)
|
||||
- [Transfer Learning with Frozen Layers](https://github.com/ultralytics/yolov5/issues/1314)
|
||||
- [Architecture Summary](https://github.com/ultralytics/yolov5/issues/6998) 🌟 NEW
|
||||
- [Weights & Biases Logging](https://github.com/ultralytics/yolov5/issues/1289)
|
||||
- [Roboflow for Datasets, Labeling, and Active Learning](https://github.com/ultralytics/yolov5/issues/4975) 🌟 NEW
|
||||
- [ClearML Logging](https://github.com/ultralytics/yolov5/tree/master/utils/loggers/clearml) 🌟 NEW
|
||||
- [Deci Platform](https://github.com/ultralytics/yolov5/wiki/Deci-Platform) 🌟 NEW
|
||||
|
||||
</details>
|
||||
|
||||
## <div align="center">Environments</div>
|
||||
|
||||
Get started in seconds with our verified environments. Click each icon below for details.
|
||||
|
||||
<div align="center">
|
||||
<a href="https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-colab-small.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
|
||||
<a href="https://www.kaggle.com/ultralytics/yolov5">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-kaggle-small.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
|
||||
<a href="https://hub.docker.com/r/ultralytics/yolov5">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-docker-small.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
|
||||
<a href="https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-aws-small.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="5%" alt="" />
|
||||
<a href="https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-gcp-small.png" width="10%" /></a>
|
||||
</div>
|
||||
|
||||
## <div align="center">Integrations</div>
|
||||
|
||||
<div align="center">
|
||||
<a href="https://bit.ly/yolov5-deci-platform">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-deci.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://cutt.ly/yolov5-readme-clearml">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-clearml.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://roboflow.com/?ref=ultralytics">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-roboflow.png" width="10%" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="14%" height="0" alt="" />
|
||||
<a href="https://wandb.ai/site?utm_campaign=repo_yolo_readme">
|
||||
<img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/logo-wb.png" width="10%" /></a>
|
||||
</div>
|
||||
|
||||
|Deci ⭐ NEW|ClearML ⭐ NEW|Roboflow|Weights & Biases
|
||||
|:-:|:-:|:-:|:-:|
|
||||
|Automatically compile and quantize YOLOv5 for better inference performance in one click at [Deci](https://bit.ly/yolov5-deci-platform)|Automatically track, visualize and even remotely train YOLOv5 using [ClearML](https://cutt.ly/yolov5-readme-clearml) (open-source!)|Label and export your custom datasets directly to YOLOv5 for training with [Roboflow](https://roboflow.com/?ref=ultralytics) |Automatically track and visualize all your YOLOv5 training runs in the cloud with [Weights & Biases](https://wandb.ai/site?utm_campaign=repo_yolo_readme)
|
||||
|
||||
|
||||
## <div align="center">Why YOLOv5</div>
|
||||
|
||||
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040763-93c22a27-347c-4e3c-847a-8094621d3f4e.png"></p>
|
||||
<details>
|
||||
<summary>YOLOv5-P5 640 Figure (click to expand)</summary>
|
||||
|
||||
<p align="left"><img width="800" src="https://user-images.githubusercontent.com/26833433/155040757-ce0934a3-06a6-43dc-a979-2edbbd69ea0e.png"></p>
|
||||
</details>
|
||||
<details>
|
||||
<summary>Figure Notes (click to expand)</summary>
|
||||
|
||||
- **COCO AP val** denotes mAP@0.5:0.95 metric measured on the 5000-image [COCO val2017](http://cocodataset.org) dataset over various inference sizes from 256 to 1536.
|
||||
- **GPU Speed** measures average inference time per image on [COCO val2017](http://cocodataset.org) dataset using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) V100 instance at batch-size 32.
|
||||
- **EfficientDet** data from [google/automl](https://github.com/google/automl) at batch size 8.
|
||||
- **Reproduce** by `python val.py --task study --data coco.yaml --iou 0.7 --weights yolov5n6.pt yolov5s6.pt yolov5m6.pt yolov5l6.pt yolov5x6.pt`
|
||||
|
||||
</details>
|
||||
|
||||
### Pretrained Checkpoints
|
||||
|
||||
| Model | size<br><sup>(pixels) | mAP<sup>val<br>0.5:0.95 | mAP<sup>val<br>0.5 | Speed<br><sup>CPU b1<br>(ms) | Speed<br><sup>V100 b1<br>(ms) | Speed<br><sup>V100 b32<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@640 (B) |
|
||||
|------------------------------------------------------------------------------------------------------|-----------------------|-------------------------|--------------------|------------------------------|-------------------------------|--------------------------------|--------------------|------------------------|
|
||||
| [YOLOv5n](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n.pt) | 640 | 28.0 | 45.7 | **45** | **6.3** | **0.6** | **1.9** | **4.5** |
|
||||
| [YOLOv5s](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s.pt) | 640 | 37.4 | 56.8 | 98 | 6.4 | 0.9 | 7.2 | 16.5 |
|
||||
| [YOLOv5m](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m.pt) | 640 | 45.4 | 64.1 | 224 | 8.2 | 1.7 | 21.2 | 49.0 |
|
||||
| [YOLOv5l](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l.pt) | 640 | 49.0 | 67.3 | 430 | 10.1 | 2.7 | 46.5 | 109.1 |
|
||||
| [YOLOv5x](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x.pt) | 640 | 50.7 | 68.9 | 766 | 12.1 | 4.8 | 86.7 | 205.7 |
|
||||
| | | | | | | | | |
|
||||
| [YOLOv5n6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n6.pt) | 1280 | 36.0 | 54.4 | 153 | 8.1 | 2.1 | 3.2 | 4.6 |
|
||||
| [YOLOv5s6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s6.pt) | 1280 | 44.8 | 63.7 | 385 | 8.2 | 3.6 | 12.6 | 16.8 |
|
||||
| [YOLOv5m6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m6.pt) | 1280 | 51.3 | 69.3 | 887 | 11.1 | 6.8 | 35.7 | 50.0 |
|
||||
| [YOLOv5l6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l6.pt) | 1280 | 53.7 | 71.3 | 1784 | 15.8 | 10.5 | 76.8 | 111.4 |
|
||||
| [YOLOv5x6](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x6.pt)<br>+ [TTA][TTA] | 1280<br>1536 | 55.0<br>**55.8** | 72.7<br>**72.7** | 3136<br>- | 26.2<br>- | 19.4<br>- | 140.7<br>- | 209.8<br>- |
|
||||
|
||||
<details>
|
||||
<summary>Table Notes (click to expand)</summary>
|
||||
|
||||
- All checkpoints are trained to 300 epochs with default settings. Nano and Small models use [hyp.scratch-low.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-low.yaml) hyps, all others use [hyp.scratch-high.yaml](https://github.com/ultralytics/yolov5/blob/master/data/hyps/hyp.scratch-high.yaml).
|
||||
- **mAP<sup>val</sup>** values are for single-model single-scale on [COCO val2017](http://cocodataset.org) dataset.<br>Reproduce by `python val.py --data coco.yaml --img 640 --conf 0.001 --iou 0.65`
|
||||
- **Speed** averaged over COCO val images using a [AWS p3.2xlarge](https://aws.amazon.com/ec2/instance-types/p3/) instance. NMS times (~1 ms/img) not included.<br>Reproduce by `python val.py --data coco.yaml --img 640 --task speed --batch 1`
|
||||
- **TTA** [Test Time Augmentation](https://github.com/ultralytics/yolov5/issues/303) includes reflection and scale augmentations.<br>Reproduce by `python val.py --data coco.yaml --img 1536 --iou 0.7 --augment`
|
||||
|
||||
</details>
|
||||
|
||||
## <div align="center">Classification ⭐ NEW</div>
|
||||
|
||||
YOLOv5 [release v6.2](https://github.com/ultralytics/yolov5/releases) brings support for classification model training, validation, prediction and export! We've made training classifier models super simple. Click below to get started.
|
||||
|
||||
<details>
|
||||
<summary>Classification Checkpoints (click to expand)</summary>
|
||||
|
||||
<br>
|
||||
|
||||
We trained YOLOv5-cls classification models on ImageNet for 90 epochs using a 4xA100 instance, and we trained ResNet and EfficientNet models alongside with the same default training settings to compare. We exported all models to ONNX FP32 for CPU speed tests and to TensorRT FP16 for GPU speed tests. We ran all speed tests on Google [Colab Pro](https://colab.research.google.com/signup) for easy reproducibility.
|
||||
|
||||
| Model | size<br><sup>(pixels) | acc<br><sup>top1 | acc<br><sup>top5 | Training<br><sup>90 epochs<br>4xA100 (hours) | Speed<br><sup>ONNX CPU<br>(ms) | Speed<br><sup>TensorRT V100<br>(ms) | params<br><sup>(M) | FLOPs<br><sup>@224 (B) |
|
||||
|----------------------------------------------------------------------------------------------------|-----------------------|------------------|------------------|----------------------------------------------|--------------------------------|-------------------------------------|--------------------|------------------------|
|
||||
| [YOLOv5n-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5n-cls.pt) | 224 | 64.6 | 85.4 | 7:59 | **3.3** | **0.5** | **2.5** | **0.5** |
|
||||
| [YOLOv5s-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5s-cls.pt) | 224 | 71.5 | 90.2 | 8:09 | 6.6 | 0.6 | 5.4 | 1.4 |
|
||||
| [YOLOv5m-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5m-cls.pt) | 224 | 75.9 | 92.9 | 10:06 | 15.5 | 0.9 | 12.9 | 3.9 |
|
||||
| [YOLOv5l-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5l-cls.pt) | 224 | 78.0 | 94.0 | 11:56 | 26.9 | 1.4 | 26.5 | 8.5 |
|
||||
| [YOLOv5x-cls](https://github.com/ultralytics/yolov5/releases/download/v6.2/yolov5x-cls.pt) | 224 | **79.0** | **94.4** | 15:04 | 54.3 | 1.8 | 48.1 | 15.9 |
|
||||
| |
|
||||
| [ResNet18](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet18.pt) | 224 | 70.3 | 89.5 | **6:47** | 11.2 | 0.5 | 11.7 | 3.7 |
|
||||
| [ResNet34](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet34.pt) | 224 | 73.9 | 91.8 | 8:33 | 20.6 | 0.9 | 21.8 | 7.4 |
|
||||
| [ResNet50](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet50.pt) | 224 | 76.8 | 93.4 | 11:10 | 23.4 | 1.0 | 25.6 | 8.5 |
|
||||
| [ResNet101](https://github.com/ultralytics/yolov5/releases/download/v6.2/resnet101.pt) | 224 | 78.5 | 94.3 | 17:10 | 42.1 | 1.9 | 44.5 | 15.9 |
|
||||
| |
|
||||
| [EfficientNet_b0](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b0.pt) | 224 | 75.1 | 92.4 | 13:03 | 12.5 | 1.3 | 5.3 | 1.0 |
|
||||
| [EfficientNet_b1](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b1.pt) | 224 | 76.4 | 93.2 | 17:04 | 14.9 | 1.6 | 7.8 | 1.5 |
|
||||
| [EfficientNet_b2](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b2.pt) | 224 | 76.6 | 93.4 | 17:10 | 15.9 | 1.6 | 9.1 | 1.7 |
|
||||
| [EfficientNet_b3](https://github.com/ultralytics/yolov5/releases/download/v6.2/efficientnet_b3.pt) | 224 | 77.7 | 94.0 | 19:19 | 18.9 | 1.9 | 12.2 | 2.4 |
|
||||
|
||||
<details>
|
||||
<summary>Table Notes (click to expand)</summary>
|
||||
|
||||
- All checkpoints are trained to 90 epochs with SGD optimizer with `lr0=0.001` and `weight_decay=5e-5` at image size 224 and all default settings.<br>Runs logged to https://wandb.ai/glenn-jocher/YOLOv5-Classifier-v6-2
|
||||
- **Accuracy** values are for single-model single-scale on [ImageNet-1k](https://www.image-net.org/index.php) dataset.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224`
|
||||
- **Speed** averaged over 100 inference images using a Google [Colab Pro](https://colab.research.google.com/signup) V100 High-RAM instance.<br>Reproduce by `python classify/val.py --data ../datasets/imagenet --img 224 --batch 1`
|
||||
- **Export** to ONNX at FP32 and TensorRT at FP16 done with `export.py`. <br>Reproduce by `python export.py --weights yolov5s-cls.pt --include engine onnx --imgsz 224`
|
||||
</details>
|
||||
</details>
|
||||
|
||||
<details>
|
||||
<summary>Classification Usage Examples (click to expand)</summary>
|
||||
|
||||
### Train
|
||||
YOLOv5 classification training supports auto-download of MNIST, Fashion-MNIST, CIFAR10, CIFAR100, Imagenette, Imagewoof, and ImageNet datasets with the `--data` argument. To start training on MNIST for example use `--data mnist`.
|
||||
|
||||
```bash
|
||||
# Single-GPU
|
||||
python classify/train.py --model yolov5s-cls.pt --data cifar100 --epochs 5 --img 224 --batch 128
|
||||
|
||||
# Multi-GPU DDP
|
||||
python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
|
||||
```
|
||||
|
||||
### Val
|
||||
Validate YOLOv5m-cls accuracy on ImageNet-1k dataset:
|
||||
```bash
|
||||
bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
||||
python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate
|
||||
```
|
||||
|
||||
### Predict
|
||||
Use pretrained YOLOv5s-cls.pt to predict bus.jpg:
|
||||
```bash
|
||||
python classify/predict.py --weights yolov5s-cls.pt --data data/images/bus.jpg
|
||||
```
|
||||
```python
|
||||
model = torch.hub.load('ultralytics/yolov5', 'custom', 'yolov5s-cls.pt') # load from PyTorch Hub
|
||||
```
|
||||
|
||||
### Export
|
||||
Export a group of trained YOLOv5s-cls, ResNet and EfficientNet models to ONNX and TensorRT:
|
||||
```bash
|
||||
python export.py --weights yolov5s-cls.pt resnet50.pt efficientnet_b0.pt --include onnx engine --img 224
|
||||
```
|
||||
</details>
|
||||
|
||||
|
||||
## <div align="center">Contribute</div>
|
||||
|
||||
We love your input! We want to make contributing to YOLOv5 as easy and transparent as possible. Please see our [Contributing Guide](CONTRIBUTING.md) to get started, and fill out the [YOLOv5 Survey](https://ultralytics.com/survey?utm_source=github&utm_medium=social&utm_campaign=Survey) to send us feedback on your experiences. Thank you to all our contributors!
|
||||
|
||||
<!-- SVG image from https://opencollective.com/ultralytics/contributors.svg?width=990 -->
|
||||
<a href="https://github.com/ultralytics/yolov5/graphs/contributors"><img src="https://github.com/ultralytics/yolov5/releases/download/v1.0/image-contributors-1280.png" /></a>
|
||||
|
||||
## <div align="center">Contact</div>
|
||||
|
||||
For YOLOv5 bugs and feature requests please visit [GitHub Issues](https://github.com/ultralytics/yolov5/issues). For business inquiries or
|
||||
professional support requests please visit [https://ultralytics.com/contact](https://ultralytics.com/contact).
|
||||
|
||||
<br>
|
||||
<div align="center">
|
||||
<a href="https://github.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-github.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.linkedin.com/company/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-linkedin.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://twitter.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-twitter.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.producthunt.com/@glenn_jocher" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-producthunt.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://youtube.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-youtube.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.facebook.com/ultralytics" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-facebook.png" width="3%" alt="" /></a>
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-transparent.png" width="3%" alt="" />
|
||||
<a href="https://www.instagram.com/ultralytics/" style="text-decoration:none;">
|
||||
<img src="https://github.com/ultralytics/assets/raw/master/social/logo-social-instagram.png" width="3%" alt="" /></a>
|
||||
</div>
|
||||
|
||||
[assets]: https://github.com/ultralytics/yolov5/releases
|
||||
[tta]: https://github.com/ultralytics/yolov5/issues/303
|
214
app/yolov5/classify/predict.py
Normal file
214
app/yolov5/classify/predict.py
Normal file
@ -0,0 +1,214 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
"""
|
||||
Run YOLOv5 classification inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
|
||||
|
||||
Usage - sources:
|
||||
$ python classify/predict.py --weights yolov5s-cls.pt --source 0 # webcam
|
||||
img.jpg # image
|
||||
vid.mp4 # video
|
||||
path/ # directory
|
||||
'path/*.jpg' # glob
|
||||
'https://youtu.be/Zgi9g1ksQHc' # YouTube
|
||||
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
||||
|
||||
Usage - formats:
|
||||
$ python classify/predict.py --weights yolov5s-cls.pt # PyTorch
|
||||
yolov5s-cls.torchscript # TorchScript
|
||||
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
||||
yolov5s-cls.xml # OpenVINO
|
||||
yolov5s-cls.engine # TensorRT
|
||||
yolov5s-cls.mlmodel # CoreML (macOS-only)
|
||||
yolov5s-cls_saved_model # TensorFlow SavedModel
|
||||
yolov5s-cls.pb # TensorFlow GraphDef
|
||||
yolov5s-cls.tflite # TensorFlow Lite
|
||||
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import platform
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.nn.functional as F
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[1] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
from models.common import DetectMultiBackend
|
||||
from utils.augmentations import classify_transforms
|
||||
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadStreams
|
||||
from utils.general import (LOGGER, Profile, check_file, check_img_size, check_imshow, check_requirements, colorstr, cv2,
|
||||
increment_path, print_args, strip_optimizer)
|
||||
from utils.plots import Annotator
|
||||
from utils.torch_utils import select_device, smart_inference_mode
|
||||
|
||||
|
||||
@smart_inference_mode()
|
||||
def run(
|
||||
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
|
||||
source=ROOT / 'data/images', # file/dir/URL/glob, 0 for webcam
|
||||
data=ROOT / 'data/coco128.yaml', # dataset.yaml path
|
||||
imgsz=(224, 224), # inference size (height, width)
|
||||
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
||||
view_img=False, # show results
|
||||
save_txt=False, # save results to *.txt
|
||||
nosave=False, # do not save images/videos
|
||||
augment=False, # augmented inference
|
||||
visualize=False, # visualize features
|
||||
update=False, # update all models
|
||||
project=ROOT / 'runs/predict-cls', # save results to project/name
|
||||
name='exp', # save results to project/name
|
||||
exist_ok=False, # existing project/name ok, do not increment
|
||||
half=False, # use FP16 half-precision inference
|
||||
dnn=False, # use OpenCV DNN for ONNX inference
|
||||
vid_stride=1, # video frame-rate stride
|
||||
):
|
||||
source = str(source)
|
||||
save_img = not nosave and not source.endswith('.txt') # save inference images
|
||||
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
||||
is_url = source.lower().startswith(('rtsp://', 'rtmp://', 'http://', 'https://'))
|
||||
webcam = source.isnumeric() or source.endswith('.txt') or (is_url and not is_file)
|
||||
if is_url and is_file:
|
||||
source = check_file(source) # download
|
||||
|
||||
# Directories
|
||||
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
||||
(save_dir / 'labels' if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
||||
|
||||
# Load model
|
||||
device = select_device(device)
|
||||
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
||||
stride, names, pt = model.stride, model.names, model.pt
|
||||
imgsz = check_img_size(imgsz, s=stride) # check image size
|
||||
|
||||
# Dataloader
|
||||
if webcam:
|
||||
view_img = check_imshow()
|
||||
dataset = LoadStreams(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
||||
bs = len(dataset) # batch_size
|
||||
else:
|
||||
dataset = LoadImages(source, img_size=imgsz, transforms=classify_transforms(imgsz[0]), vid_stride=vid_stride)
|
||||
bs = 1 # batch_size
|
||||
vid_path, vid_writer = [None] * bs, [None] * bs
|
||||
|
||||
# Run inference
|
||||
model.warmup(imgsz=(1 if pt else bs, 3, *imgsz)) # warmup
|
||||
seen, windows, dt = 0, [], (Profile(), Profile(), Profile())
|
||||
for path, im, im0s, vid_cap, s in dataset:
|
||||
with dt[0]:
|
||||
im = torch.Tensor(im).to(device)
|
||||
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
||||
if len(im.shape) == 3:
|
||||
im = im[None] # expand for batch dim
|
||||
|
||||
# Inference
|
||||
with dt[1]:
|
||||
results = model(im)
|
||||
|
||||
# Post-process
|
||||
with dt[2]:
|
||||
pred = F.softmax(results, dim=1) # probabilities
|
||||
|
||||
# Process predictions
|
||||
for i, prob in enumerate(pred): # per image
|
||||
seen += 1
|
||||
if webcam: # batch_size >= 1
|
||||
p, im0 = path[i], im0s[i].copy()
|
||||
s += f'{i}: '
|
||||
else:
|
||||
p, im0 = path, im0s.copy()
|
||||
|
||||
p = Path(p) # to Path
|
||||
save_path = str(save_dir / p.name) # im.jpg
|
||||
s += '%gx%g ' % im.shape[2:] # print string
|
||||
annotator = Annotator(im0, example=str(names), pil=True)
|
||||
|
||||
# Print results
|
||||
top5i = prob.argsort(0, descending=True)[:5].tolist() # top 5 indices
|
||||
s += f"{', '.join(f'{names[j]} {prob[j]:.2f}' for j in top5i)}, "
|
||||
|
||||
# Write results
|
||||
if save_img or view_img: # Add bbox to image
|
||||
text = '\n'.join(f'{prob[j]:.2f} {names[j]}' for j in top5i)
|
||||
annotator.text((32, 32), text, txt_color=(255, 255, 255))
|
||||
|
||||
# Stream results
|
||||
im0 = annotator.result()
|
||||
if view_img:
|
||||
if platform.system() == 'Linux' and p not in windows:
|
||||
windows.append(p)
|
||||
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
||||
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
||||
cv2.imshow(str(p), im0)
|
||||
cv2.waitKey(1) # 1 millisecond
|
||||
|
||||
# Save results (image with detections)
|
||||
if save_img:
|
||||
if dataset.mode == 'image':
|
||||
cv2.imwrite(save_path, im0)
|
||||
else: # 'video' or 'stream'
|
||||
if vid_path[i] != save_path: # new video
|
||||
vid_path[i] = save_path
|
||||
if isinstance(vid_writer[i], cv2.VideoWriter):
|
||||
vid_writer[i].release() # release previous video writer
|
||||
if vid_cap: # video
|
||||
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
||||
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
||||
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
||||
else: # stream
|
||||
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
||||
save_path = str(Path(save_path).with_suffix('.mp4')) # force *.mp4 suffix on results videos
|
||||
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
|
||||
vid_writer[i].write(im0)
|
||||
|
||||
# Print time (inference-only)
|
||||
LOGGER.info(f"{s}{dt[1].dt * 1E3:.1f}ms")
|
||||
|
||||
# Print results
|
||||
t = tuple(x.t / seen * 1E3 for x in dt) # speeds per image
|
||||
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}' % t)
|
||||
if save_txt or save_img:
|
||||
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ''
|
||||
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
||||
if update:
|
||||
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
||||
|
||||
|
||||
def parse_opt():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model path(s)')
|
||||
parser.add_argument('--source', type=str, default=ROOT / 'data/images', help='file/dir/URL/glob, 0 for webcam')
|
||||
parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='(optional) dataset.yaml path')
|
||||
parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[224], help='inference size h,w')
|
||||
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
||||
parser.add_argument('--view-img', action='store_true', help='show results')
|
||||
parser.add_argument('--save-txt', action='store_true', help='save results to *.txt')
|
||||
parser.add_argument('--nosave', action='store_true', help='do not save images/videos')
|
||||
parser.add_argument('--augment', action='store_true', help='augmented inference')
|
||||
parser.add_argument('--visualize', action='store_true', help='visualize features')
|
||||
parser.add_argument('--update', action='store_true', help='update all models')
|
||||
parser.add_argument('--project', default=ROOT / 'runs/predict-cls', help='save results to project/name')
|
||||
parser.add_argument('--name', default='exp', help='save results to project/name')
|
||||
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
||||
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
||||
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
||||
parser.add_argument('--vid-stride', type=int, default=1, help='video frame-rate stride')
|
||||
opt = parser.parse_args()
|
||||
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
||||
print_args(vars(opt))
|
||||
return opt
|
||||
|
||||
|
||||
def main(opt):
|
||||
check_requirements(exclude=('tensorboard', 'thop'))
|
||||
run(**vars(opt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
331
app/yolov5/classify/train.py
Normal file
331
app/yolov5/classify/train.py
Normal file
@ -0,0 +1,331 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
"""
|
||||
Train a YOLOv5 classifier model on a classification dataset
|
||||
|
||||
Usage - Single-GPU training:
|
||||
$ python classify/train.py --model yolov5s-cls.pt --data imagenette160 --epochs 5 --img 128
|
||||
|
||||
Usage - Multi-GPU DDP training:
|
||||
$ python -m torch.distributed.run --nproc_per_node 4 --master_port 1 classify/train.py --model yolov5s-cls.pt --data imagenet --epochs 5 --img 224 --device 0,1,2,3
|
||||
|
||||
Datasets: --data mnist, fashion-mnist, cifar10, cifar100, imagenette, imagewoof, imagenet, or 'path/to/data'
|
||||
YOLOv5-cls models: --model yolov5n-cls.pt, yolov5s-cls.pt, yolov5m-cls.pt, yolov5l-cls.pt, yolov5x-cls.pt
|
||||
Torchvision models: --model resnet50, efficientnet_b0, etc. See https://pytorch.org/vision/stable/models.html
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from copy import deepcopy
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
import torch.distributed as dist
|
||||
import torch.hub as hub
|
||||
import torch.optim.lr_scheduler as lr_scheduler
|
||||
import torchvision
|
||||
from torch.cuda import amp
|
||||
from tqdm import tqdm
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[1] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
from classify import val as validate
|
||||
from models.experimental import attempt_load
|
||||
from models.yolo import ClassificationModel, DetectionModel
|
||||
from utils.dataloaders import create_classification_dataloader
|
||||
from utils.general import (DATASETS_DIR, LOGGER, WorkingDirectory, check_git_status, check_requirements, colorstr,
|
||||
download, increment_path, init_seeds, print_args, yaml_save)
|
||||
from utils.loggers import GenericLogger
|
||||
from utils.plots import imshow_cls
|
||||
from utils.torch_utils import (ModelEMA, model_info, reshape_classifier_output, select_device, smart_DDP,
|
||||
smart_optimizer, smartCrossEntropyLoss, torch_distributed_zero_first)
|
||||
|
||||
LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
|
||||
RANK = int(os.getenv('RANK', -1))
|
||||
WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
|
||||
|
||||
|
||||
def train(opt, device):
|
||||
init_seeds(opt.seed + 1 + RANK, deterministic=True)
|
||||
save_dir, data, bs, epochs, nw, imgsz, pretrained = \
|
||||
opt.save_dir, Path(opt.data), opt.batch_size, opt.epochs, min(os.cpu_count() - 1, opt.workers), \
|
||||
opt.imgsz, str(opt.pretrained).lower() == 'true'
|
||||
cuda = device.type != 'cpu'
|
||||
|
||||
# Directories
|
||||
wdir = save_dir / 'weights'
|
||||
wdir.mkdir(parents=True, exist_ok=True) # make dir
|
||||
last, best = wdir / 'last.pt', wdir / 'best.pt'
|
||||
|
||||
# Save run settings
|
||||
yaml_save(save_dir / 'opt.yaml', vars(opt))
|
||||
|
||||
# Logger
|
||||
logger = GenericLogger(opt=opt, console_logger=LOGGER) if RANK in {-1, 0} else None
|
||||
|
||||
# Download Dataset
|
||||
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
||||
data_dir = data if data.is_dir() else (DATASETS_DIR / data)
|
||||
if not data_dir.is_dir():
|
||||
LOGGER.info(f'\nDataset not found ⚠️, missing path {data_dir}, attempting download...')
|
||||
t = time.time()
|
||||
if str(data) == 'imagenet':
|
||||
subprocess.run(f"bash {ROOT / 'data/scripts/get_imagenet.sh'}", shell=True, check=True)
|
||||
else:
|
||||
url = f'https://github.com/ultralytics/yolov5/releases/download/v1.0/{data}.zip'
|
||||
download(url, dir=data_dir.parent)
|
||||
s = f"Dataset download success ✅ ({time.time() - t:.1f}s), saved to {colorstr('bold', data_dir)}\n"
|
||||
LOGGER.info(s)
|
||||
|
||||
# Dataloaders
|
||||
nc = len([x for x in (data_dir / 'train').glob('*') if x.is_dir()]) # number of classes
|
||||
trainloader = create_classification_dataloader(path=data_dir / 'train',
|
||||
imgsz=imgsz,
|
||||
batch_size=bs // WORLD_SIZE,
|
||||
augment=True,
|
||||
cache=opt.cache,
|
||||
rank=LOCAL_RANK,
|
||||
workers=nw)
|
||||
|
||||
test_dir = data_dir / 'test' if (data_dir / 'test').exists() else data_dir / 'val' # data/test or data/val
|
||||
if RANK in {-1, 0}:
|
||||
testloader = create_classification_dataloader(path=test_dir,
|
||||
imgsz=imgsz,
|
||||
batch_size=bs // WORLD_SIZE * 2,
|
||||
augment=False,
|
||||
cache=opt.cache,
|
||||
rank=-1,
|
||||
workers=nw)
|
||||
|
||||
# Model
|
||||
with torch_distributed_zero_first(LOCAL_RANK), WorkingDirectory(ROOT):
|
||||
if Path(opt.model).is_file() or opt.model.endswith('.pt'):
|
||||
model = attempt_load(opt.model, device='cpu', fuse=False)
|
||||
elif opt.model in torchvision.models.__dict__: # TorchVision models i.e. resnet50, efficientnet_b0
|
||||
model = torchvision.models.__dict__[opt.model](weights='IMAGENET1K_V1' if pretrained else None)
|
||||
else:
|
||||
m = hub.list('ultralytics/yolov5') # + hub.list('pytorch/vision') # models
|
||||
raise ModuleNotFoundError(f'--model {opt.model} not found. Available models are: \n' + '\n'.join(m))
|
||||
if isinstance(model, DetectionModel):
|
||||
LOGGER.warning("WARNING: pass YOLOv5 classifier model with '-cls' suffix, i.e. '--model yolov5s-cls.pt'")
|
||||
model = ClassificationModel(model=model, nc=nc, cutoff=opt.cutoff or 10) # convert to classification model
|
||||
reshape_classifier_output(model, nc) # update class count
|
||||
for m in model.modules():
|
||||
if not pretrained and hasattr(m, 'reset_parameters'):
|
||||
m.reset_parameters()
|
||||
if isinstance(m, torch.nn.Dropout) and opt.dropout is not None:
|
||||
m.p = opt.dropout # set dropout
|
||||
for p in model.parameters():
|
||||
p.requires_grad = True # for training
|
||||
model = model.to(device)
|
||||
|
||||
# Info
|
||||
if RANK in {-1, 0}:
|
||||
model.names = trainloader.dataset.classes # attach class names
|
||||
model.transforms = testloader.dataset.torch_transforms # attach inference transforms
|
||||
model_info(model)
|
||||
if opt.verbose:
|
||||
LOGGER.info(model)
|
||||
images, labels = next(iter(trainloader))
|
||||
file = imshow_cls(images[:25], labels[:25], names=model.names, f=save_dir / 'train_images.jpg')
|
||||
logger.log_images(file, name='Train Examples')
|
||||
logger.log_graph(model, imgsz) # log model
|
||||
|
||||
# Optimizer
|
||||
optimizer = smart_optimizer(model, opt.optimizer, opt.lr0, momentum=0.9, decay=opt.decay)
|
||||
|
||||
# Scheduler
|
||||
lrf = 0.01 # final lr (fraction of lr0)
|
||||
# lf = lambda x: ((1 + math.cos(x * math.pi / epochs)) / 2) * (1 - lrf) + lrf # cosine
|
||||
lf = lambda x: (1 - x / epochs) * (1 - lrf) + lrf # linear
|
||||
scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf)
|
||||
# scheduler = lr_scheduler.OneCycleLR(optimizer, max_lr=lr0, total_steps=epochs, pct_start=0.1,
|
||||
# final_div_factor=1 / 25 / lrf)
|
||||
|
||||
# EMA
|
||||
ema = ModelEMA(model) if RANK in {-1, 0} else None
|
||||
|
||||
# DDP mode
|
||||
if cuda and RANK != -1:
|
||||
model = smart_DDP(model)
|
||||
|
||||
# Train
|
||||
t0 = time.time()
|
||||
criterion = smartCrossEntropyLoss(label_smoothing=opt.label_smoothing) # loss function
|
||||
best_fitness = 0.0
|
||||
scaler = amp.GradScaler(enabled=cuda)
|
||||
val = test_dir.stem # 'val' or 'test'
|
||||
LOGGER.info(f'Image sizes {imgsz} train, {imgsz} test\n'
|
||||
f'Using {nw * WORLD_SIZE} dataloader workers\n'
|
||||
f"Logging results to {colorstr('bold', save_dir)}\n"
|
||||
f'Starting {opt.model} training on {data} dataset with {nc} classes for {epochs} epochs...\n\n'
|
||||
f"{'Epoch':>10}{'GPU_mem':>10}{'train_loss':>12}{f'{val}_loss':>12}{'top1_acc':>12}{'top5_acc':>12}")
|
||||
for epoch in range(epochs): # loop over the dataset multiple times
|
||||
tloss, vloss, fitness = 0.0, 0.0, 0.0 # train loss, val loss, fitness
|
||||
model.train()
|
||||
if RANK != -1:
|
||||
trainloader.sampler.set_epoch(epoch)
|
||||
pbar = enumerate(trainloader)
|
||||
if RANK in {-1, 0}:
|
||||
pbar = tqdm(enumerate(trainloader), total=len(trainloader), bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}')
|
||||
for i, (images, labels) in pbar: # progress bar
|
||||
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
||||
|
||||
# Forward
|
||||
with amp.autocast(enabled=cuda): # stability issues when enabled
|
||||
loss = criterion(model(images), labels)
|
||||
|
||||
# Backward
|
||||
scaler.scale(loss).backward()
|
||||
|
||||
# Optimize
|
||||
scaler.unscale_(optimizer) # unscale gradients
|
||||
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=10.0) # clip gradients
|
||||
scaler.step(optimizer)
|
||||
scaler.update()
|
||||
optimizer.zero_grad()
|
||||
if ema:
|
||||
ema.update(model)
|
||||
|
||||
if RANK in {-1, 0}:
|
||||
# Print
|
||||
tloss = (tloss * i + loss.item()) / (i + 1) # update mean losses
|
||||
mem = '%.3gG' % (torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0) # (GB)
|
||||
pbar.desc = f"{f'{epoch + 1}/{epochs}':>10}{mem:>10}{tloss:>12.3g}" + ' ' * 36
|
||||
|
||||
# Test
|
||||
if i == len(pbar) - 1: # last batch
|
||||
top1, top5, vloss = validate.run(model=ema.ema,
|
||||
dataloader=testloader,
|
||||
criterion=criterion,
|
||||
pbar=pbar) # test accuracy, loss
|
||||
fitness = top1 # define fitness as top1 accuracy
|
||||
|
||||
# Scheduler
|
||||
scheduler.step()
|
||||
|
||||
# Log metrics
|
||||
if RANK in {-1, 0}:
|
||||
# Best fitness
|
||||
if fitness > best_fitness:
|
||||
best_fitness = fitness
|
||||
|
||||
# Log
|
||||
metrics = {
|
||||
"train/loss": tloss,
|
||||
f"{val}/loss": vloss,
|
||||
"metrics/accuracy_top1": top1,
|
||||
"metrics/accuracy_top5": top5,
|
||||
"lr/0": optimizer.param_groups[0]['lr']} # learning rate
|
||||
logger.log_metrics(metrics, epoch)
|
||||
|
||||
# Save model
|
||||
final_epoch = epoch + 1 == epochs
|
||||
if (not opt.nosave) or final_epoch:
|
||||
ckpt = {
|
||||
'epoch': epoch,
|
||||
'best_fitness': best_fitness,
|
||||
'model': deepcopy(ema.ema).half(), # deepcopy(de_parallel(model)).half(),
|
||||
'ema': None, # deepcopy(ema.ema).half(),
|
||||
'updates': ema.updates,
|
||||
'optimizer': None, # optimizer.state_dict(),
|
||||
'opt': vars(opt),
|
||||
'date': datetime.now().isoformat()}
|
||||
|
||||
# Save last, best and delete
|
||||
torch.save(ckpt, last)
|
||||
if best_fitness == fitness:
|
||||
torch.save(ckpt, best)
|
||||
del ckpt
|
||||
|
||||
# Train complete
|
||||
if RANK in {-1, 0} and final_epoch:
|
||||
LOGGER.info(f'\nTraining complete ({(time.time() - t0) / 3600:.3f} hours)'
|
||||
f"\nResults saved to {colorstr('bold', save_dir)}"
|
||||
f"\nPredict: python classify/predict.py --weights {best} --source im.jpg"
|
||||
f"\nValidate: python classify/val.py --weights {best} --data {data_dir}"
|
||||
f"\nExport: python export.py --weights {best} --include onnx"
|
||||
f"\nPyTorch Hub: model = torch.hub.load('ultralytics/yolov5', 'custom', '{best}')"
|
||||
f"\nVisualize: https://netron.app\n")
|
||||
|
||||
# Plot examples
|
||||
images, labels = (x[:25] for x in next(iter(testloader))) # first 25 images and labels
|
||||
pred = torch.max(ema.ema(images.to(device)), 1)[1]
|
||||
file = imshow_cls(images, labels, pred, model.names, verbose=False, f=save_dir / 'test_images.jpg')
|
||||
|
||||
# Log results
|
||||
meta = {"epochs": epochs, "top1_acc": best_fitness, "date": datetime.now().isoformat()}
|
||||
logger.log_images(file, name='Test Examples (true-predicted)', epoch=epoch)
|
||||
logger.log_model(best, epochs, metadata=meta)
|
||||
|
||||
|
||||
def parse_opt(known=False):
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--model', type=str, default='yolov5s-cls.pt', help='initial weights path')
|
||||
parser.add_argument('--data', type=str, default='imagenette160', help='cifar10, cifar100, mnist, imagenet, ...')
|
||||
parser.add_argument('--epochs', type=int, default=10, help='total training epochs')
|
||||
parser.add_argument('--batch-size', type=int, default=64, help='total batch size for all GPUs')
|
||||
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=128, help='train, val image size (pixels)')
|
||||
parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
|
||||
parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
|
||||
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
||||
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
||||
parser.add_argument('--project', default=ROOT / 'runs/train-cls', help='save to project/name')
|
||||
parser.add_argument('--name', default='exp', help='save to project/name')
|
||||
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
||||
parser.add_argument('--pretrained', nargs='?', const=True, default=True, help='start from i.e. --pretrained False')
|
||||
parser.add_argument('--optimizer', choices=['SGD', 'Adam', 'AdamW', 'RMSProp'], default='Adam', help='optimizer')
|
||||
parser.add_argument('--lr0', type=float, default=0.001, help='initial learning rate')
|
||||
parser.add_argument('--decay', type=float, default=5e-5, help='weight decay')
|
||||
parser.add_argument('--label-smoothing', type=float, default=0.1, help='Label smoothing epsilon')
|
||||
parser.add_argument('--cutoff', type=int, default=None, help='Model layer cutoff index for Classify() head')
|
||||
parser.add_argument('--dropout', type=float, default=None, help='Dropout (fraction)')
|
||||
parser.add_argument('--verbose', action='store_true', help='Verbose mode')
|
||||
parser.add_argument('--seed', type=int, default=0, help='Global training seed')
|
||||
parser.add_argument('--local_rank', type=int, default=-1, help='Automatic DDP Multi-GPU argument, do not modify')
|
||||
return parser.parse_known_args()[0] if known else parser.parse_args()
|
||||
|
||||
|
||||
def main(opt):
|
||||
# Checks
|
||||
if RANK in {-1, 0}:
|
||||
print_args(vars(opt))
|
||||
check_git_status()
|
||||
check_requirements()
|
||||
|
||||
# DDP mode
|
||||
device = select_device(opt.device, batch_size=opt.batch_size)
|
||||
if LOCAL_RANK != -1:
|
||||
assert opt.batch_size != -1, 'AutoBatch is coming soon for classification, please pass a valid --batch-size'
|
||||
assert opt.batch_size % WORLD_SIZE == 0, f'--batch-size {opt.batch_size} must be multiple of WORLD_SIZE'
|
||||
assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
|
||||
torch.cuda.set_device(LOCAL_RANK)
|
||||
device = torch.device('cuda', LOCAL_RANK)
|
||||
dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
|
||||
|
||||
# Parameters
|
||||
opt.save_dir = increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok) # increment run
|
||||
|
||||
# Train
|
||||
train(opt, device)
|
||||
|
||||
|
||||
def run(**kwargs):
|
||||
# Usage: from yolov5 import classify; classify.train.run(data=mnist, imgsz=320, model='yolov5m')
|
||||
opt = parse_opt(True)
|
||||
for k, v in kwargs.items():
|
||||
setattr(opt, k, v)
|
||||
main(opt)
|
||||
return opt
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
168
app/yolov5/classify/val.py
Normal file
168
app/yolov5/classify/val.py
Normal file
@ -0,0 +1,168 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
"""
|
||||
Validate a trained YOLOv5 classification model on a classification dataset
|
||||
|
||||
Usage:
|
||||
$ bash data/scripts/get_imagenet.sh --val # download ImageNet val split (6.3G, 50000 images)
|
||||
$ python classify/val.py --weights yolov5m-cls.pt --data ../datasets/imagenet --img 224 # validate ImageNet
|
||||
|
||||
Usage - formats:
|
||||
$ python classify/val.py --weights yolov5s-cls.pt # PyTorch
|
||||
yolov5s-cls.torchscript # TorchScript
|
||||
yolov5s-cls.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
||||
yolov5s-cls.xml # OpenVINO
|
||||
yolov5s-cls.engine # TensorRT
|
||||
yolov5s-cls.mlmodel # CoreML (macOS-only)
|
||||
yolov5s-cls_saved_model # TensorFlow SavedModel
|
||||
yolov5s-cls.pb # TensorFlow GraphDef
|
||||
yolov5s-cls.tflite # TensorFlow Lite
|
||||
yolov5s-cls_edgetpu.tflite # TensorFlow Edge TPU
|
||||
"""
|
||||
|
||||
import argparse
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
import torch
|
||||
from tqdm import tqdm
|
||||
|
||||
FILE = Path(__file__).resolve()
|
||||
ROOT = FILE.parents[1] # YOLOv5 root directory
|
||||
if str(ROOT) not in sys.path:
|
||||
sys.path.append(str(ROOT)) # add ROOT to PATH
|
||||
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
||||
|
||||
from models.common import DetectMultiBackend
|
||||
from utils.dataloaders import create_classification_dataloader
|
||||
from utils.general import LOGGER, Profile, check_img_size, check_requirements, colorstr, increment_path, print_args
|
||||
from utils.torch_utils import select_device, smart_inference_mode
|
||||
|
||||
|
||||
@smart_inference_mode()
|
||||
def run(
|
||||
data=ROOT / '../datasets/mnist', # dataset dir
|
||||
weights=ROOT / 'yolov5s-cls.pt', # model.pt path(s)
|
||||
batch_size=128, # batch size
|
||||
imgsz=224, # inference size (pixels)
|
||||
device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
||||
workers=8, # max dataloader workers (per RANK in DDP mode)
|
||||
verbose=False, # verbose output
|
||||
project=ROOT / 'runs/val-cls', # save to project/name
|
||||
name='exp', # save to project/name
|
||||
exist_ok=False, # existing project/name ok, do not increment
|
||||
half=False, # use FP16 half-precision inference
|
||||
dnn=False, # use OpenCV DNN for ONNX inference
|
||||
model=None,
|
||||
dataloader=None,
|
||||
criterion=None,
|
||||
pbar=None,
|
||||
):
|
||||
# Initialize/load model and set device
|
||||
training = model is not None
|
||||
if training: # called by train.py
|
||||
device, pt, jit, engine = next(model.parameters()).device, True, False, False # get model device, PyTorch model
|
||||
half &= device.type != 'cpu' # half precision only supported on CUDA
|
||||
model.half() if half else model.float()
|
||||
else: # called directly
|
||||
device = select_device(device, batch_size=batch_size)
|
||||
|
||||
# Directories
|
||||
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
||||
save_dir.mkdir(parents=True, exist_ok=True) # make dir
|
||||
|
||||
# Load model
|
||||
model = DetectMultiBackend(weights, device=device, dnn=dnn, fp16=half)
|
||||
stride, pt, jit, engine = model.stride, model.pt, model.jit, model.engine
|
||||
imgsz = check_img_size(imgsz, s=stride) # check image size
|
||||
half = model.fp16 # FP16 supported on limited backends with CUDA
|
||||
if engine:
|
||||
batch_size = model.batch_size
|
||||
else:
|
||||
device = model.device
|
||||
if not (pt or jit):
|
||||
batch_size = 1 # export.py models default to batch-size 1
|
||||
LOGGER.info(f'Forcing --batch-size 1 square inference (1,3,{imgsz},{imgsz}) for non-PyTorch models')
|
||||
|
||||
# Dataloader
|
||||
data = Path(data)
|
||||
test_dir = data / 'test' if (data / 'test').exists() else data / 'val' # data/test or data/val
|
||||
dataloader = create_classification_dataloader(path=test_dir,
|
||||
imgsz=imgsz,
|
||||
batch_size=batch_size,
|
||||
augment=False,
|
||||
rank=-1,
|
||||
workers=workers)
|
||||
|
||||
model.eval()
|
||||
pred, targets, loss, dt = [], [], 0, (Profile(), Profile(), Profile())
|
||||
n = len(dataloader) # number of batches
|
||||
action = 'validating' if dataloader.dataset.root.stem == 'val' else 'testing'
|
||||
desc = f"{pbar.desc[:-36]}{action:>36}" if pbar else f"{action}"
|
||||
bar = tqdm(dataloader, desc, n, not training, bar_format='{l_bar}{bar:10}{r_bar}{bar:-10b}', position=0)
|
||||
with torch.cuda.amp.autocast(enabled=device.type != 'cpu'):
|
||||
for images, labels in bar:
|
||||
with dt[0]:
|
||||
images, labels = images.to(device, non_blocking=True), labels.to(device)
|
||||
|
||||
with dt[1]:
|
||||
y = model(images)
|
||||
|
||||
with dt[2]:
|
||||
pred.append(y.argsort(1, descending=True)[:, :5])
|
||||
targets.append(labels)
|
||||
if criterion:
|
||||
loss += criterion(y, labels)
|
||||
|
||||
loss /= n
|
||||
pred, targets = torch.cat(pred), torch.cat(targets)
|
||||
correct = (targets[:, None] == pred).float()
|
||||
acc = torch.stack((correct[:, 0], correct.max(1).values), dim=1) # (top1, top5) accuracy
|
||||
top1, top5 = acc.mean(0).tolist()
|
||||
|
||||
if pbar:
|
||||
pbar.desc = f"{pbar.desc[:-36]}{loss:>12.3g}{top1:>12.3g}{top5:>12.3g}"
|
||||
if verbose: # all classes
|
||||
LOGGER.info(f"{'Class':>24}{'Images':>12}{'top1_acc':>12}{'top5_acc':>12}")
|
||||
LOGGER.info(f"{'all':>24}{targets.shape[0]:>12}{top1:>12.3g}{top5:>12.3g}")
|
||||
for i, c in model.names.items():
|
||||
aci = acc[targets == i]
|
||||
top1i, top5i = aci.mean(0).tolist()
|
||||
LOGGER.info(f"{c:>24}{aci.shape[0]:>12}{top1i:>12.3g}{top5i:>12.3g}")
|
||||
|
||||
# Print results
|
||||
t = tuple(x.t / len(dataloader.dataset.samples) * 1E3 for x in dt) # speeds per image
|
||||
shape = (1, 3, imgsz, imgsz)
|
||||
LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms post-process per image at shape {shape}' % t)
|
||||
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
|
||||
|
||||
return top1, top5, loss
|
||||
|
||||
|
||||
def parse_opt():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument('--data', type=str, default=ROOT / '../datasets/mnist', help='dataset path')
|
||||
parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s-cls.pt', help='model.pt path(s)')
|
||||
parser.add_argument('--batch-size', type=int, default=128, help='batch size')
|
||||
parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=224, help='inference size (pixels)')
|
||||
parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
|
||||
parser.add_argument('--workers', type=int, default=8, help='max dataloader workers (per RANK in DDP mode)')
|
||||
parser.add_argument('--verbose', nargs='?', const=True, default=True, help='verbose output')
|
||||
parser.add_argument('--project', default=ROOT / 'runs/val-cls', help='save to project/name')
|
||||
parser.add_argument('--name', default='exp', help='save to project/name')
|
||||
parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
|
||||
parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
|
||||
parser.add_argument('--dnn', action='store_true', help='use OpenCV DNN for ONNX inference')
|
||||
opt = parser.parse_args()
|
||||
print_args(vars(opt))
|
||||
return opt
|
||||
|
||||
|
||||
def main(opt):
|
||||
check_requirements(exclude=('tensorboard', 'thop'))
|
||||
run(**vars(opt))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
opt = parse_opt()
|
||||
main(opt)
|
74
app/yolov5/data/Argoverse.yaml
Normal file
74
app/yolov5/data/Argoverse.yaml
Normal file
@ -0,0 +1,74 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Argoverse-HD dataset (ring-front-center camera) http://www.cs.cmu.edu/~mengtial/proj/streaming/ by Argo AI
|
||||
# Example usage: python train.py --data Argoverse.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── Argoverse ← downloads here (31.3 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/Argoverse # dataset root dir
|
||||
train: Argoverse-1.1/images/train/ # train images (relative to 'path') 39384 images
|
||||
val: Argoverse-1.1/images/val/ # val images (relative to 'path') 15062 images
|
||||
test: Argoverse-1.1/images/test/ # test images (optional) https://eval.ai/web/challenges/challenge-page/800/overview
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: person
|
||||
1: bicycle
|
||||
2: car
|
||||
3: motorcycle
|
||||
4: bus
|
||||
5: truck
|
||||
6: traffic_light
|
||||
7: stop_sign
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
import json
|
||||
|
||||
from tqdm import tqdm
|
||||
from utils.general import download, Path
|
||||
|
||||
|
||||
def argoverse2yolo(set):
|
||||
labels = {}
|
||||
a = json.load(open(set, "rb"))
|
||||
for annot in tqdm(a['annotations'], desc=f"Converting {set} to YOLOv5 format..."):
|
||||
img_id = annot['image_id']
|
||||
img_name = a['images'][img_id]['name']
|
||||
img_label_name = f'{img_name[:-3]}txt'
|
||||
|
||||
cls = annot['category_id'] # instance class id
|
||||
x_center, y_center, width, height = annot['bbox']
|
||||
x_center = (x_center + width / 2) / 1920.0 # offset and scale
|
||||
y_center = (y_center + height / 2) / 1200.0 # offset and scale
|
||||
width /= 1920.0 # scale
|
||||
height /= 1200.0 # scale
|
||||
|
||||
img_dir = set.parents[2] / 'Argoverse-1.1' / 'labels' / a['seq_dirs'][a['images'][annot['image_id']]['sid']]
|
||||
if not img_dir.exists():
|
||||
img_dir.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
k = str(img_dir / img_label_name)
|
||||
if k not in labels:
|
||||
labels[k] = []
|
||||
labels[k].append(f"{cls} {x_center} {y_center} {width} {height}\n")
|
||||
|
||||
for k in labels:
|
||||
with open(k, "w") as f:
|
||||
f.writelines(labels[k])
|
||||
|
||||
|
||||
# Download
|
||||
dir = Path('../datasets/Argoverse') # dataset root dir
|
||||
urls = ['https://argoverse-hd.s3.us-east-2.amazonaws.com/Argoverse-HD-Full.zip']
|
||||
download(urls, dir=dir, delete=False)
|
||||
|
||||
# Convert
|
||||
annotations_dir = 'Argoverse-HD/annotations/'
|
||||
(dir / 'Argoverse-1.1' / 'tracking').rename(dir / 'Argoverse-1.1' / 'images') # rename 'tracking' to 'images'
|
||||
for d in "train.json", "val.json":
|
||||
argoverse2yolo(dir / annotations_dir / d) # convert VisDrone annotations to YOLO labels
|
54
app/yolov5/data/GlobalWheat2020.yaml
Normal file
54
app/yolov5/data/GlobalWheat2020.yaml
Normal file
@ -0,0 +1,54 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Global Wheat 2020 dataset http://www.global-wheat.com/ by University of Saskatchewan
|
||||
# Example usage: python train.py --data GlobalWheat2020.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── GlobalWheat2020 ← downloads here (7.0 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/GlobalWheat2020 # dataset root dir
|
||||
train: # train images (relative to 'path') 3422 images
|
||||
- images/arvalis_1
|
||||
- images/arvalis_2
|
||||
- images/arvalis_3
|
||||
- images/ethz_1
|
||||
- images/rres_1
|
||||
- images/inrae_1
|
||||
- images/usask_1
|
||||
val: # val images (relative to 'path') 748 images (WARNING: train set contains ethz_1)
|
||||
- images/ethz_1
|
||||
test: # test images (optional) 1276 images
|
||||
- images/utokyo_1
|
||||
- images/utokyo_2
|
||||
- images/nau_1
|
||||
- images/uq_1
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: wheat_head
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
from utils.general import download, Path
|
||||
|
||||
|
||||
# Download
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
urls = ['https://zenodo.org/record/4298502/files/global-wheat-codalab-official.zip',
|
||||
'https://github.com/ultralytics/yolov5/releases/download/v1.0/GlobalWheat2020_labels.zip']
|
||||
download(urls, dir=dir)
|
||||
|
||||
# Make Directories
|
||||
for p in 'annotations', 'images', 'labels':
|
||||
(dir / p).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Move
|
||||
for p in 'arvalis_1', 'arvalis_2', 'arvalis_3', 'ethz_1', 'rres_1', 'inrae_1', 'usask_1', \
|
||||
'utokyo_1', 'utokyo_2', 'nau_1', 'uq_1':
|
||||
(dir / p).rename(dir / 'images' / p) # move to /images
|
||||
f = (dir / p).with_suffix('.json') # json file
|
||||
if f.exists():
|
||||
f.rename((dir / 'annotations' / p).with_suffix('.json')) # move to /annotations
|
1022
app/yolov5/data/ImageNet.yaml
Normal file
1022
app/yolov5/data/ImageNet.yaml
Normal file
File diff suppressed because it is too large
Load Diff
438
app/yolov5/data/Objects365.yaml
Normal file
438
app/yolov5/data/Objects365.yaml
Normal file
@ -0,0 +1,438 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Objects365 dataset https://www.objects365.org/ by Megvii
|
||||
# Example usage: python train.py --data Objects365.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── Objects365 ← downloads here (712 GB = 367G data + 345G zips)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/Objects365 # dataset root dir
|
||||
train: images/train # train images (relative to 'path') 1742289 images
|
||||
val: images/val # val images (relative to 'path') 80000 images
|
||||
test: # test images (optional)
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: Person
|
||||
1: Sneakers
|
||||
2: Chair
|
||||
3: Other Shoes
|
||||
4: Hat
|
||||
5: Car
|
||||
6: Lamp
|
||||
7: Glasses
|
||||
8: Bottle
|
||||
9: Desk
|
||||
10: Cup
|
||||
11: Street Lights
|
||||
12: Cabinet/shelf
|
||||
13: Handbag/Satchel
|
||||
14: Bracelet
|
||||
15: Plate
|
||||
16: Picture/Frame
|
||||
17: Helmet
|
||||
18: Book
|
||||
19: Gloves
|
||||
20: Storage box
|
||||
21: Boat
|
||||
22: Leather Shoes
|
||||
23: Flower
|
||||
24: Bench
|
||||
25: Potted Plant
|
||||
26: Bowl/Basin
|
||||
27: Flag
|
||||
28: Pillow
|
||||
29: Boots
|
||||
30: Vase
|
||||
31: Microphone
|
||||
32: Necklace
|
||||
33: Ring
|
||||
34: SUV
|
||||
35: Wine Glass
|
||||
36: Belt
|
||||
37: Monitor/TV
|
||||
38: Backpack
|
||||
39: Umbrella
|
||||
40: Traffic Light
|
||||
41: Speaker
|
||||
42: Watch
|
||||
43: Tie
|
||||
44: Trash bin Can
|
||||
45: Slippers
|
||||
46: Bicycle
|
||||
47: Stool
|
||||
48: Barrel/bucket
|
||||
49: Van
|
||||
50: Couch
|
||||
51: Sandals
|
||||
52: Basket
|
||||
53: Drum
|
||||
54: Pen/Pencil
|
||||
55: Bus
|
||||
56: Wild Bird
|
||||
57: High Heels
|
||||
58: Motorcycle
|
||||
59: Guitar
|
||||
60: Carpet
|
||||
61: Cell Phone
|
||||
62: Bread
|
||||
63: Camera
|
||||
64: Canned
|
||||
65: Truck
|
||||
66: Traffic cone
|
||||
67: Cymbal
|
||||
68: Lifesaver
|
||||
69: Towel
|
||||
70: Stuffed Toy
|
||||
71: Candle
|
||||
72: Sailboat
|
||||
73: Laptop
|
||||
74: Awning
|
||||
75: Bed
|
||||
76: Faucet
|
||||
77: Tent
|
||||
78: Horse
|
||||
79: Mirror
|
||||
80: Power outlet
|
||||
81: Sink
|
||||
82: Apple
|
||||
83: Air Conditioner
|
||||
84: Knife
|
||||
85: Hockey Stick
|
||||
86: Paddle
|
||||
87: Pickup Truck
|
||||
88: Fork
|
||||
89: Traffic Sign
|
||||
90: Balloon
|
||||
91: Tripod
|
||||
92: Dog
|
||||
93: Spoon
|
||||
94: Clock
|
||||
95: Pot
|
||||
96: Cow
|
||||
97: Cake
|
||||
98: Dinning Table
|
||||
99: Sheep
|
||||
100: Hanger
|
||||
101: Blackboard/Whiteboard
|
||||
102: Napkin
|
||||
103: Other Fish
|
||||
104: Orange/Tangerine
|
||||
105: Toiletry
|
||||
106: Keyboard
|
||||
107: Tomato
|
||||
108: Lantern
|
||||
109: Machinery Vehicle
|
||||
110: Fan
|
||||
111: Green Vegetables
|
||||
112: Banana
|
||||
113: Baseball Glove
|
||||
114: Airplane
|
||||
115: Mouse
|
||||
116: Train
|
||||
117: Pumpkin
|
||||
118: Soccer
|
||||
119: Skiboard
|
||||
120: Luggage
|
||||
121: Nightstand
|
||||
122: Tea pot
|
||||
123: Telephone
|
||||
124: Trolley
|
||||
125: Head Phone
|
||||
126: Sports Car
|
||||
127: Stop Sign
|
||||
128: Dessert
|
||||
129: Scooter
|
||||
130: Stroller
|
||||
131: Crane
|
||||
132: Remote
|
||||
133: Refrigerator
|
||||
134: Oven
|
||||
135: Lemon
|
||||
136: Duck
|
||||
137: Baseball Bat
|
||||
138: Surveillance Camera
|
||||
139: Cat
|
||||
140: Jug
|
||||
141: Broccoli
|
||||
142: Piano
|
||||
143: Pizza
|
||||
144: Elephant
|
||||
145: Skateboard
|
||||
146: Surfboard
|
||||
147: Gun
|
||||
148: Skating and Skiing shoes
|
||||
149: Gas stove
|
||||
150: Donut
|
||||
151: Bow Tie
|
||||
152: Carrot
|
||||
153: Toilet
|
||||
154: Kite
|
||||
155: Strawberry
|
||||
156: Other Balls
|
||||
157: Shovel
|
||||
158: Pepper
|
||||
159: Computer Box
|
||||
160: Toilet Paper
|
||||
161: Cleaning Products
|
||||
162: Chopsticks
|
||||
163: Microwave
|
||||
164: Pigeon
|
||||
165: Baseball
|
||||
166: Cutting/chopping Board
|
||||
167: Coffee Table
|
||||
168: Side Table
|
||||
169: Scissors
|
||||
170: Marker
|
||||
171: Pie
|
||||
172: Ladder
|
||||
173: Snowboard
|
||||
174: Cookies
|
||||
175: Radiator
|
||||
176: Fire Hydrant
|
||||
177: Basketball
|
||||
178: Zebra
|
||||
179: Grape
|
||||
180: Giraffe
|
||||
181: Potato
|
||||
182: Sausage
|
||||
183: Tricycle
|
||||
184: Violin
|
||||
185: Egg
|
||||
186: Fire Extinguisher
|
||||
187: Candy
|
||||
188: Fire Truck
|
||||
189: Billiards
|
||||
190: Converter
|
||||
191: Bathtub
|
||||
192: Wheelchair
|
||||
193: Golf Club
|
||||
194: Briefcase
|
||||
195: Cucumber
|
||||
196: Cigar/Cigarette
|
||||
197: Paint Brush
|
||||
198: Pear
|
||||
199: Heavy Truck
|
||||
200: Hamburger
|
||||
201: Extractor
|
||||
202: Extension Cord
|
||||
203: Tong
|
||||
204: Tennis Racket
|
||||
205: Folder
|
||||
206: American Football
|
||||
207: earphone
|
||||
208: Mask
|
||||
209: Kettle
|
||||
210: Tennis
|
||||
211: Ship
|
||||
212: Swing
|
||||
213: Coffee Machine
|
||||
214: Slide
|
||||
215: Carriage
|
||||
216: Onion
|
||||
217: Green beans
|
||||
218: Projector
|
||||
219: Frisbee
|
||||
220: Washing Machine/Drying Machine
|
||||
221: Chicken
|
||||
222: Printer
|
||||
223: Watermelon
|
||||
224: Saxophone
|
||||
225: Tissue
|
||||
226: Toothbrush
|
||||
227: Ice cream
|
||||
228: Hot-air balloon
|
||||
229: Cello
|
||||
230: French Fries
|
||||
231: Scale
|
||||
232: Trophy
|
||||
233: Cabbage
|
||||
234: Hot dog
|
||||
235: Blender
|
||||
236: Peach
|
||||
237: Rice
|
||||
238: Wallet/Purse
|
||||
239: Volleyball
|
||||
240: Deer
|
||||
241: Goose
|
||||
242: Tape
|
||||
243: Tablet
|
||||
244: Cosmetics
|
||||
245: Trumpet
|
||||
246: Pineapple
|
||||
247: Golf Ball
|
||||
248: Ambulance
|
||||
249: Parking meter
|
||||
250: Mango
|
||||
251: Key
|
||||
252: Hurdle
|
||||
253: Fishing Rod
|
||||
254: Medal
|
||||
255: Flute
|
||||
256: Brush
|
||||
257: Penguin
|
||||
258: Megaphone
|
||||
259: Corn
|
||||
260: Lettuce
|
||||
261: Garlic
|
||||
262: Swan
|
||||
263: Helicopter
|
||||
264: Green Onion
|
||||
265: Sandwich
|
||||
266: Nuts
|
||||
267: Speed Limit Sign
|
||||
268: Induction Cooker
|
||||
269: Broom
|
||||
270: Trombone
|
||||
271: Plum
|
||||
272: Rickshaw
|
||||
273: Goldfish
|
||||
274: Kiwi fruit
|
||||
275: Router/modem
|
||||
276: Poker Card
|
||||
277: Toaster
|
||||
278: Shrimp
|
||||
279: Sushi
|
||||
280: Cheese
|
||||
281: Notepaper
|
||||
282: Cherry
|
||||
283: Pliers
|
||||
284: CD
|
||||
285: Pasta
|
||||
286: Hammer
|
||||
287: Cue
|
||||
288: Avocado
|
||||
289: Hamimelon
|
||||
290: Flask
|
||||
291: Mushroom
|
||||
292: Screwdriver
|
||||
293: Soap
|
||||
294: Recorder
|
||||
295: Bear
|
||||
296: Eggplant
|
||||
297: Board Eraser
|
||||
298: Coconut
|
||||
299: Tape Measure/Ruler
|
||||
300: Pig
|
||||
301: Showerhead
|
||||
302: Globe
|
||||
303: Chips
|
||||
304: Steak
|
||||
305: Crosswalk Sign
|
||||
306: Stapler
|
||||
307: Camel
|
||||
308: Formula 1
|
||||
309: Pomegranate
|
||||
310: Dishwasher
|
||||
311: Crab
|
||||
312: Hoverboard
|
||||
313: Meat ball
|
||||
314: Rice Cooker
|
||||
315: Tuba
|
||||
316: Calculator
|
||||
317: Papaya
|
||||
318: Antelope
|
||||
319: Parrot
|
||||
320: Seal
|
||||
321: Butterfly
|
||||
322: Dumbbell
|
||||
323: Donkey
|
||||
324: Lion
|
||||
325: Urinal
|
||||
326: Dolphin
|
||||
327: Electric Drill
|
||||
328: Hair Dryer
|
||||
329: Egg tart
|
||||
330: Jellyfish
|
||||
331: Treadmill
|
||||
332: Lighter
|
||||
333: Grapefruit
|
||||
334: Game board
|
||||
335: Mop
|
||||
336: Radish
|
||||
337: Baozi
|
||||
338: Target
|
||||
339: French
|
||||
340: Spring Rolls
|
||||
341: Monkey
|
||||
342: Rabbit
|
||||
343: Pencil Case
|
||||
344: Yak
|
||||
345: Red Cabbage
|
||||
346: Binoculars
|
||||
347: Asparagus
|
||||
348: Barbell
|
||||
349: Scallop
|
||||
350: Noddles
|
||||
351: Comb
|
||||
352: Dumpling
|
||||
353: Oyster
|
||||
354: Table Tennis paddle
|
||||
355: Cosmetics Brush/Eyeliner Pencil
|
||||
356: Chainsaw
|
||||
357: Eraser
|
||||
358: Lobster
|
||||
359: Durian
|
||||
360: Okra
|
||||
361: Lipstick
|
||||
362: Cosmetics Mirror
|
||||
363: Curling
|
||||
364: Table Tennis
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
from tqdm import tqdm
|
||||
|
||||
from utils.general import Path, check_requirements, download, np, xyxy2xywhn
|
||||
|
||||
check_requirements(('pycocotools>=2.0',))
|
||||
from pycocotools.coco import COCO
|
||||
|
||||
# Make Directories
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
for p in 'images', 'labels':
|
||||
(dir / p).mkdir(parents=True, exist_ok=True)
|
||||
for q in 'train', 'val':
|
||||
(dir / p / q).mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Train, Val Splits
|
||||
for split, patches in [('train', 50 + 1), ('val', 43 + 1)]:
|
||||
print(f"Processing {split} in {patches} patches ...")
|
||||
images, labels = dir / 'images' / split, dir / 'labels' / split
|
||||
|
||||
# Download
|
||||
url = f"https://dorc.ks3-cn-beijing.ksyun.com/data-set/2020Objects365%E6%95%B0%E6%8D%AE%E9%9B%86/{split}/"
|
||||
if split == 'train':
|
||||
download([f'{url}zhiyuan_objv2_{split}.tar.gz'], dir=dir, delete=False) # annotations json
|
||||
download([f'{url}patch{i}.tar.gz' for i in range(patches)], dir=images, curl=True, delete=False, threads=8)
|
||||
elif split == 'val':
|
||||
download([f'{url}zhiyuan_objv2_{split}.json'], dir=dir, delete=False) # annotations json
|
||||
download([f'{url}images/v1/patch{i}.tar.gz' for i in range(15 + 1)], dir=images, curl=True, delete=False, threads=8)
|
||||
download([f'{url}images/v2/patch{i}.tar.gz' for i in range(16, patches)], dir=images, curl=True, delete=False, threads=8)
|
||||
|
||||
# Move
|
||||
for f in tqdm(images.rglob('*.jpg'), desc=f'Moving {split} images'):
|
||||
f.rename(images / f.name) # move to /images/{split}
|
||||
|
||||
# Labels
|
||||
coco = COCO(dir / f'zhiyuan_objv2_{split}.json')
|
||||
names = [x["name"] for x in coco.loadCats(coco.getCatIds())]
|
||||
for cid, cat in enumerate(names):
|
||||
catIds = coco.getCatIds(catNms=[cat])
|
||||
imgIds = coco.getImgIds(catIds=catIds)
|
||||
for im in tqdm(coco.loadImgs(imgIds), desc=f'Class {cid + 1}/{len(names)} {cat}'):
|
||||
width, height = im["width"], im["height"]
|
||||
path = Path(im["file_name"]) # image filename
|
||||
try:
|
||||
with open(labels / path.with_suffix('.txt').name, 'a') as file:
|
||||
annIds = coco.getAnnIds(imgIds=im["id"], catIds=catIds, iscrowd=None)
|
||||
for a in coco.loadAnns(annIds):
|
||||
x, y, w, h = a['bbox'] # bounding box in xywh (xy top-left corner)
|
||||
xyxy = np.array([x, y, x + w, y + h])[None] # pixels(1,4)
|
||||
x, y, w, h = xyxy2xywhn(xyxy, w=width, h=height, clip=True)[0] # normalized and clipped
|
||||
file.write(f"{cid} {x:.5f} {y:.5f} {w:.5f} {h:.5f}\n")
|
||||
except Exception as e:
|
||||
print(e)
|
53
app/yolov5/data/SKU-110K.yaml
Normal file
53
app/yolov5/data/SKU-110K.yaml
Normal file
@ -0,0 +1,53 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# SKU-110K retail items dataset https://github.com/eg4000/SKU110K_CVPR19 by Trax Retail
|
||||
# Example usage: python train.py --data SKU-110K.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── SKU-110K ← downloads here (13.6 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/SKU-110K # dataset root dir
|
||||
train: train.txt # train images (relative to 'path') 8219 images
|
||||
val: val.txt # val images (relative to 'path') 588 images
|
||||
test: test.txt # test images (optional) 2936 images
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: object
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
import shutil
|
||||
from tqdm import tqdm
|
||||
from utils.general import np, pd, Path, download, xyxy2xywh
|
||||
|
||||
|
||||
# Download
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
parent = Path(dir.parent) # download dir
|
||||
urls = ['http://trax-geometry.s3.amazonaws.com/cvpr_challenge/SKU110K_fixed.tar.gz']
|
||||
download(urls, dir=parent, delete=False)
|
||||
|
||||
# Rename directories
|
||||
if dir.exists():
|
||||
shutil.rmtree(dir)
|
||||
(parent / 'SKU110K_fixed').rename(dir) # rename dir
|
||||
(dir / 'labels').mkdir(parents=True, exist_ok=True) # create labels dir
|
||||
|
||||
# Convert labels
|
||||
names = 'image', 'x1', 'y1', 'x2', 'y2', 'class', 'image_width', 'image_height' # column names
|
||||
for d in 'annotations_train.csv', 'annotations_val.csv', 'annotations_test.csv':
|
||||
x = pd.read_csv(dir / 'annotations' / d, names=names).values # annotations
|
||||
images, unique_images = x[:, 0], np.unique(x[:, 0])
|
||||
with open((dir / d).with_suffix('.txt').__str__().replace('annotations_', ''), 'w') as f:
|
||||
f.writelines(f'./images/{s}\n' for s in unique_images)
|
||||
for im in tqdm(unique_images, desc=f'Converting {dir / d}'):
|
||||
cls = 0 # single-class dataset
|
||||
with open((dir / 'labels' / im).with_suffix('.txt'), 'a') as f:
|
||||
for r in x[images == im]:
|
||||
w, h = r[6], r[7] # image width, height
|
||||
xywh = xyxy2xywh(np.array([[r[1] / w, r[2] / h, r[3] / w, r[4] / h]]))[0] # instance
|
||||
f.write(f"{cls} {xywh[0]:.5f} {xywh[1]:.5f} {xywh[2]:.5f} {xywh[3]:.5f}\n") # write label
|
100
app/yolov5/data/VOC.yaml
Normal file
100
app/yolov5/data/VOC.yaml
Normal file
@ -0,0 +1,100 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# PASCAL VOC dataset http://host.robots.ox.ac.uk/pascal/VOC by University of Oxford
|
||||
# Example usage: python train.py --data VOC.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── VOC ← downloads here (2.8 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/VOC
|
||||
train: # train images (relative to 'path') 16551 images
|
||||
- images/train2012
|
||||
- images/train2007
|
||||
- images/val2012
|
||||
- images/val2007
|
||||
val: # val images (relative to 'path') 4952 images
|
||||
- images/test2007
|
||||
test: # test images (optional)
|
||||
- images/test2007
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: aeroplane
|
||||
1: bicycle
|
||||
2: bird
|
||||
3: boat
|
||||
4: bottle
|
||||
5: bus
|
||||
6: car
|
||||
7: cat
|
||||
8: chair
|
||||
9: cow
|
||||
10: diningtable
|
||||
11: dog
|
||||
12: horse
|
||||
13: motorbike
|
||||
14: person
|
||||
15: pottedplant
|
||||
16: sheep
|
||||
17: sofa
|
||||
18: train
|
||||
19: tvmonitor
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from tqdm import tqdm
|
||||
from utils.general import download, Path
|
||||
|
||||
|
||||
def convert_label(path, lb_path, year, image_id):
|
||||
def convert_box(size, box):
|
||||
dw, dh = 1. / size[0], 1. / size[1]
|
||||
x, y, w, h = (box[0] + box[1]) / 2.0 - 1, (box[2] + box[3]) / 2.0 - 1, box[1] - box[0], box[3] - box[2]
|
||||
return x * dw, y * dh, w * dw, h * dh
|
||||
|
||||
in_file = open(path / f'VOC{year}/Annotations/{image_id}.xml')
|
||||
out_file = open(lb_path, 'w')
|
||||
tree = ET.parse(in_file)
|
||||
root = tree.getroot()
|
||||
size = root.find('size')
|
||||
w = int(size.find('width').text)
|
||||
h = int(size.find('height').text)
|
||||
|
||||
names = list(yaml['names'].values()) # names list
|
||||
for obj in root.iter('object'):
|
||||
cls = obj.find('name').text
|
||||
if cls in names and int(obj.find('difficult').text) != 1:
|
||||
xmlbox = obj.find('bndbox')
|
||||
bb = convert_box((w, h), [float(xmlbox.find(x).text) for x in ('xmin', 'xmax', 'ymin', 'ymax')])
|
||||
cls_id = names.index(cls) # class id
|
||||
out_file.write(" ".join([str(a) for a in (cls_id, *bb)]) + '\n')
|
||||
|
||||
|
||||
# Download
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
||||
urls = [f'{url}VOCtrainval_06-Nov-2007.zip', # 446MB, 5012 images
|
||||
f'{url}VOCtest_06-Nov-2007.zip', # 438MB, 4953 images
|
||||
f'{url}VOCtrainval_11-May-2012.zip'] # 1.95GB, 17126 images
|
||||
download(urls, dir=dir / 'images', delete=False, curl=True, threads=3)
|
||||
|
||||
# Convert
|
||||
path = dir / 'images/VOCdevkit'
|
||||
for year, image_set in ('2012', 'train'), ('2012', 'val'), ('2007', 'train'), ('2007', 'val'), ('2007', 'test'):
|
||||
imgs_path = dir / 'images' / f'{image_set}{year}'
|
||||
lbs_path = dir / 'labels' / f'{image_set}{year}'
|
||||
imgs_path.mkdir(exist_ok=True, parents=True)
|
||||
lbs_path.mkdir(exist_ok=True, parents=True)
|
||||
|
||||
with open(path / f'VOC{year}/ImageSets/Main/{image_set}.txt') as f:
|
||||
image_ids = f.read().strip().split()
|
||||
for id in tqdm(image_ids, desc=f'{image_set}{year}'):
|
||||
f = path / f'VOC{year}/JPEGImages/{id}.jpg' # old img path
|
||||
lb_path = (lbs_path / f.name).with_suffix('.txt') # new label path
|
||||
f.rename(imgs_path / f.name) # move image
|
||||
convert_label(path, lb_path, year, id) # convert labels to YOLO format
|
70
app/yolov5/data/VisDrone.yaml
Normal file
70
app/yolov5/data/VisDrone.yaml
Normal file
@ -0,0 +1,70 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# VisDrone2019-DET dataset https://github.com/VisDrone/VisDrone-Dataset by Tianjin University
|
||||
# Example usage: python train.py --data VisDrone.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── VisDrone ← downloads here (2.3 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/VisDrone # dataset root dir
|
||||
train: VisDrone2019-DET-train/images # train images (relative to 'path') 6471 images
|
||||
val: VisDrone2019-DET-val/images # val images (relative to 'path') 548 images
|
||||
test: VisDrone2019-DET-test-dev/images # test images (optional) 1610 images
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: pedestrian
|
||||
1: people
|
||||
2: bicycle
|
||||
3: car
|
||||
4: van
|
||||
5: truck
|
||||
6: tricycle
|
||||
7: awning-tricycle
|
||||
8: bus
|
||||
9: motor
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
from utils.general import download, os, Path
|
||||
|
||||
def visdrone2yolo(dir):
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
|
||||
def convert_box(size, box):
|
||||
# Convert VisDrone box to YOLO xywh box
|
||||
dw = 1. / size[0]
|
||||
dh = 1. / size[1]
|
||||
return (box[0] + box[2] / 2) * dw, (box[1] + box[3] / 2) * dh, box[2] * dw, box[3] * dh
|
||||
|
||||
(dir / 'labels').mkdir(parents=True, exist_ok=True) # make labels directory
|
||||
pbar = tqdm((dir / 'annotations').glob('*.txt'), desc=f'Converting {dir}')
|
||||
for f in pbar:
|
||||
img_size = Image.open((dir / 'images' / f.name).with_suffix('.jpg')).size
|
||||
lines = []
|
||||
with open(f, 'r') as file: # read annotation.txt
|
||||
for row in [x.split(',') for x in file.read().strip().splitlines()]:
|
||||
if row[4] == '0': # VisDrone 'ignored regions' class 0
|
||||
continue
|
||||
cls = int(row[5]) - 1
|
||||
box = convert_box(img_size, tuple(map(int, row[:4])))
|
||||
lines.append(f"{cls} {' '.join(f'{x:.6f}' for x in box)}\n")
|
||||
with open(str(f).replace(os.sep + 'annotations' + os.sep, os.sep + 'labels' + os.sep), 'w') as fl:
|
||||
fl.writelines(lines) # write label.txt
|
||||
|
||||
|
||||
# Download
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
urls = ['https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-train.zip',
|
||||
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-val.zip',
|
||||
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-dev.zip',
|
||||
'https://github.com/ultralytics/yolov5/releases/download/v1.0/VisDrone2019-DET-test-challenge.zip']
|
||||
download(urls, dir=dir, curl=True, threads=4)
|
||||
|
||||
# Convert
|
||||
for d in 'VisDrone2019-DET-train', 'VisDrone2019-DET-val', 'VisDrone2019-DET-test-dev':
|
||||
visdrone2yolo(dir / d) # convert VisDrone annotations to YOLO labels
|
116
app/yolov5/data/coco.yaml
Normal file
116
app/yolov5/data/coco.yaml
Normal file
@ -0,0 +1,116 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# COCO 2017 dataset http://cocodataset.org by Microsoft
|
||||
# Example usage: python train.py --data coco.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── coco ← downloads here (20.1 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/coco # dataset root dir
|
||||
train: train2017.txt # train images (relative to 'path') 118287 images
|
||||
val: val2017.txt # val images (relative to 'path') 5000 images
|
||||
test: test-dev2017.txt # 20288 of 40670 images, submit to https://competitions.codalab.org/competitions/20794
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: person
|
||||
1: bicycle
|
||||
2: car
|
||||
3: motorcycle
|
||||
4: airplane
|
||||
5: bus
|
||||
6: train
|
||||
7: truck
|
||||
8: boat
|
||||
9: traffic light
|
||||
10: fire hydrant
|
||||
11: stop sign
|
||||
12: parking meter
|
||||
13: bench
|
||||
14: bird
|
||||
15: cat
|
||||
16: dog
|
||||
17: horse
|
||||
18: sheep
|
||||
19: cow
|
||||
20: elephant
|
||||
21: bear
|
||||
22: zebra
|
||||
23: giraffe
|
||||
24: backpack
|
||||
25: umbrella
|
||||
26: handbag
|
||||
27: tie
|
||||
28: suitcase
|
||||
29: frisbee
|
||||
30: skis
|
||||
31: snowboard
|
||||
32: sports ball
|
||||
33: kite
|
||||
34: baseball bat
|
||||
35: baseball glove
|
||||
36: skateboard
|
||||
37: surfboard
|
||||
38: tennis racket
|
||||
39: bottle
|
||||
40: wine glass
|
||||
41: cup
|
||||
42: fork
|
||||
43: knife
|
||||
44: spoon
|
||||
45: bowl
|
||||
46: banana
|
||||
47: apple
|
||||
48: sandwich
|
||||
49: orange
|
||||
50: broccoli
|
||||
51: carrot
|
||||
52: hot dog
|
||||
53: pizza
|
||||
54: donut
|
||||
55: cake
|
||||
56: chair
|
||||
57: couch
|
||||
58: potted plant
|
||||
59: bed
|
||||
60: dining table
|
||||
61: toilet
|
||||
62: tv
|
||||
63: laptop
|
||||
64: mouse
|
||||
65: remote
|
||||
66: keyboard
|
||||
67: cell phone
|
||||
68: microwave
|
||||
69: oven
|
||||
70: toaster
|
||||
71: sink
|
||||
72: refrigerator
|
||||
73: book
|
||||
74: clock
|
||||
75: vase
|
||||
76: scissors
|
||||
77: teddy bear
|
||||
78: hair drier
|
||||
79: toothbrush
|
||||
|
||||
|
||||
# Download script/URL (optional)
|
||||
download: |
|
||||
from utils.general import download, Path
|
||||
|
||||
|
||||
# Download labels
|
||||
segments = False # segment or box labels
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
url = 'https://github.com/ultralytics/yolov5/releases/download/v1.0/'
|
||||
urls = [url + ('coco2017labels-segments.zip' if segments else 'coco2017labels.zip')] # labels
|
||||
download(urls, dir=dir.parent)
|
||||
|
||||
# Download data
|
||||
urls = ['http://images.cocodataset.org/zips/train2017.zip', # 19G, 118k images
|
||||
'http://images.cocodataset.org/zips/val2017.zip', # 1G, 5k images
|
||||
'http://images.cocodataset.org/zips/test2017.zip'] # 7G, 41k images (optional)
|
||||
download(urls, dir=dir / 'images', threads=3)
|
101
app/yolov5/data/coco128 - 副本.yaml
Normal file
101
app/yolov5/data/coco128 - 副本.yaml
Normal file
@ -0,0 +1,101 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017) by Ultralytics
|
||||
# Example usage: python train.py --data coco128.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── coco128 ← downloads here (7 MB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/coco128 # dataset root dir
|
||||
train: images/train2017 # train images (relative to 'path') 128 images
|
||||
val: images/train2017 # val images (relative to 'path') 128 images
|
||||
test: # test images (optional)
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: person
|
||||
1: bicycle
|
||||
2: car
|
||||
3: motorcycle
|
||||
4: airplane
|
||||
5: bus
|
||||
6: train
|
||||
7: truck
|
||||
8: boat
|
||||
9: traffic light
|
||||
10: fire hydrant
|
||||
11: stop sign
|
||||
12: parking meter
|
||||
13: bench
|
||||
14: bird
|
||||
15: cat
|
||||
16: dog
|
||||
17: horse
|
||||
18: sheep
|
||||
19: cow
|
||||
20: elephant
|
||||
21: bear
|
||||
22: zebra
|
||||
23: giraffe
|
||||
24: backpack
|
||||
25: umbrella
|
||||
26: handbag
|
||||
27: tie
|
||||
28: suitcase
|
||||
29: frisbee
|
||||
30: skis
|
||||
31: snowboard
|
||||
32: sports ball
|
||||
33: kite
|
||||
34: baseball bat
|
||||
35: baseball glove
|
||||
36: skateboard
|
||||
37: surfboard
|
||||
38: tennis racket
|
||||
39: bottle
|
||||
40: wine glass
|
||||
41: cup
|
||||
42: fork
|
||||
43: knife
|
||||
44: spoon
|
||||
45: bowl
|
||||
46: banana
|
||||
47: apple
|
||||
48: sandwich
|
||||
49: orange
|
||||
50: broccoli
|
||||
51: carrot
|
||||
52: hot dog
|
||||
53: pizza
|
||||
54: donut
|
||||
55: cake
|
||||
56: chair
|
||||
57: couch
|
||||
58: potted plant
|
||||
59: bed
|
||||
60: dining table
|
||||
61: toilet
|
||||
62: tv
|
||||
63: laptop
|
||||
64: mouse
|
||||
65: remote
|
||||
66: keyboard
|
||||
67: cell phone
|
||||
68: microwave
|
||||
69: oven
|
||||
70: toaster
|
||||
71: sink
|
||||
72: refrigerator
|
||||
73: book
|
||||
74: clock
|
||||
75: vase
|
||||
76: scissors
|
||||
77: teddy bear
|
||||
78: hair drier
|
||||
79: toothbrush
|
||||
|
||||
|
||||
# Download script/URL (optional)
|
||||
download: https://ultralytics.com/assets/coco128.zip
|
7
app/yolov5/data/coco128.yaml
Normal file
7
app/yolov5/data/coco128.yaml
Normal file
@ -0,0 +1,7 @@
|
||||
path: null
|
||||
train: E:/aicheck/data_set/11442136178662604800/trained/images/train/
|
||||
val: E:/aicheck/data_set/11442136178662604800/trained/images/val/
|
||||
test: null
|
||||
names:
|
||||
0: logo
|
||||
1: 3C
|
34
app/yolov5/data/hyps/hyp.Objects365.yaml
Normal file
34
app/yolov5/data/hyps/hyp.Objects365.yaml
Normal file
@ -0,0 +1,34 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Hyperparameters for Objects365 training
|
||||
# python train.py --weights yolov5m.pt --data Objects365.yaml --evolve
|
||||
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.00258
|
||||
lrf: 0.17
|
||||
momentum: 0.779
|
||||
weight_decay: 0.00058
|
||||
warmup_epochs: 1.33
|
||||
warmup_momentum: 0.86
|
||||
warmup_bias_lr: 0.0711
|
||||
box: 0.0539
|
||||
cls: 0.299
|
||||
cls_pw: 0.825
|
||||
obj: 0.632
|
||||
obj_pw: 1.0
|
||||
iou_t: 0.2
|
||||
anchor_t: 3.44
|
||||
anchors: 3.2
|
||||
fl_gamma: 0.0
|
||||
hsv_h: 0.0188
|
||||
hsv_s: 0.704
|
||||
hsv_v: 0.36
|
||||
degrees: 0.0
|
||||
translate: 0.0902
|
||||
scale: 0.491
|
||||
shear: 0.0
|
||||
perspective: 0.0
|
||||
flipud: 0.0
|
||||
fliplr: 0.5
|
||||
mosaic: 1.0
|
||||
mixup: 0.0
|
||||
copy_paste: 0.0
|
40
app/yolov5/data/hyps/hyp.VOC.yaml
Normal file
40
app/yolov5/data/hyps/hyp.VOC.yaml
Normal file
@ -0,0 +1,40 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Hyperparameters for VOC training
|
||||
# python train.py --batch 128 --weights yolov5m6.pt --data VOC.yaml --epochs 50 --img 512 --hyp hyp.scratch-med.yaml --evolve
|
||||
# See Hyperparameter Evolution tutorial for details https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
# YOLOv5 Hyperparameter Evolution Results
|
||||
# Best generation: 467
|
||||
# Last generation: 996
|
||||
# metrics/precision, metrics/recall, metrics/mAP_0.5, metrics/mAP_0.5:0.95, val/box_loss, val/obj_loss, val/cls_loss
|
||||
# 0.87729, 0.85125, 0.91286, 0.72664, 0.0076739, 0.0042529, 0.0013865
|
||||
|
||||
lr0: 0.00334
|
||||
lrf: 0.15135
|
||||
momentum: 0.74832
|
||||
weight_decay: 0.00025
|
||||
warmup_epochs: 3.3835
|
||||
warmup_momentum: 0.59462
|
||||
warmup_bias_lr: 0.18657
|
||||
box: 0.02
|
||||
cls: 0.21638
|
||||
cls_pw: 0.5
|
||||
obj: 0.51728
|
||||
obj_pw: 0.67198
|
||||
iou_t: 0.2
|
||||
anchor_t: 3.3744
|
||||
fl_gamma: 0.0
|
||||
hsv_h: 0.01041
|
||||
hsv_s: 0.54703
|
||||
hsv_v: 0.27739
|
||||
degrees: 0.0
|
||||
translate: 0.04591
|
||||
scale: 0.75544
|
||||
shear: 0.0
|
||||
perspective: 0.0
|
||||
flipud: 0.0
|
||||
fliplr: 0.5
|
||||
mosaic: 0.85834
|
||||
mixup: 0.04266
|
||||
copy_paste: 0.0
|
||||
anchors: 3.412
|
34
app/yolov5/data/hyps/hyp.scratch-high.yaml
Normal file
34
app/yolov5/data/hyps/hyp.scratch-high.yaml
Normal file
@ -0,0 +1,34 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Hyperparameters for high-augmentation COCO training from scratch
|
||||
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.3 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 0.7 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.9 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.1 # image mixup (probability)
|
||||
copy_paste: 0.1 # segment copy-paste (probability)
|
34
app/yolov5/data/hyps/hyp.scratch-low.yaml
Normal file
34
app/yolov5/data/hyps/hyp.scratch-low.yaml
Normal file
@ -0,0 +1,34 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Hyperparameters for low-augmentation COCO training from scratch
|
||||
# python train.py --batch 64 --cfg yolov5n6.yaml --weights '' --data coco.yaml --img 640 --epochs 300 --linear
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.01 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.5 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 1.0 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.5 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.0 # image mixup (probability)
|
||||
copy_paste: 0.0 # segment copy-paste (probability)
|
34
app/yolov5/data/hyps/hyp.scratch-med.yaml
Normal file
34
app/yolov5/data/hyps/hyp.scratch-med.yaml
Normal file
@ -0,0 +1,34 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Hyperparameters for medium-augmentation COCO training from scratch
|
||||
# python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
|
||||
# See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
|
||||
|
||||
lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
|
||||
lrf: 0.1 # final OneCycleLR learning rate (lr0 * lrf)
|
||||
momentum: 0.937 # SGD momentum/Adam beta1
|
||||
weight_decay: 0.0005 # optimizer weight decay 5e-4
|
||||
warmup_epochs: 3.0 # warmup epochs (fractions ok)
|
||||
warmup_momentum: 0.8 # warmup initial momentum
|
||||
warmup_bias_lr: 0.1 # warmup initial bias lr
|
||||
box: 0.05 # box loss gain
|
||||
cls: 0.3 # cls loss gain
|
||||
cls_pw: 1.0 # cls BCELoss positive_weight
|
||||
obj: 0.7 # obj loss gain (scale with pixels)
|
||||
obj_pw: 1.0 # obj BCELoss positive_weight
|
||||
iou_t: 0.20 # IoU training threshold
|
||||
anchor_t: 4.0 # anchor-multiple threshold
|
||||
# anchors: 3 # anchors per output layer (0 to ignore)
|
||||
fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
|
||||
hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
|
||||
hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
|
||||
hsv_v: 0.4 # image HSV-Value augmentation (fraction)
|
||||
degrees: 0.0 # image rotation (+/- deg)
|
||||
translate: 0.1 # image translation (+/- fraction)
|
||||
scale: 0.9 # image scale (+/- gain)
|
||||
shear: 0.0 # image shear (+/- deg)
|
||||
perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
|
||||
flipud: 0.0 # image flip up-down (probability)
|
||||
fliplr: 0.5 # image flip left-right (probability)
|
||||
mosaic: 1.0 # image mosaic (probability)
|
||||
mixup: 0.1 # image mixup (probability)
|
||||
copy_paste: 0.0 # segment copy-paste (probability)
|
21
app/yolov5/data/scripts/download_weights.sh
Normal file
21
app/yolov5/data/scripts/download_weights.sh
Normal file
@ -0,0 +1,21 @@
|
||||
#!/bin/bash
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Download latest models from https://github.com/ultralytics/yolov5/releases
|
||||
# Example usage: bash data/scripts/download_weights.sh
|
||||
# parent
|
||||
# └── yolov5
|
||||
# ├── yolov5s.pt ← downloads here
|
||||
# ├── yolov5m.pt
|
||||
# └── ...
|
||||
|
||||
python - <<EOF
|
||||
from utils.downloads import attempt_download
|
||||
|
||||
p5 = ['n', 's', 'm', 'l', 'x'] # P5 models
|
||||
p6 = [f'{x}6' for x in p5] # P6 models
|
||||
cls = [f'{x}-cls' for x in p5] # classification models
|
||||
|
||||
for x in p5 + p6 + cls:
|
||||
attempt_download(f'weights/yolov5{x}.pt')
|
||||
|
||||
EOF
|
56
app/yolov5/data/scripts/get_coco.sh
Normal file
56
app/yolov5/data/scripts/get_coco.sh
Normal file
@ -0,0 +1,56 @@
|
||||
#!/bin/bash
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Download COCO 2017 dataset http://cocodataset.org
|
||||
# Example usage: bash data/scripts/get_coco.sh
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── coco ← downloads here
|
||||
|
||||
# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments
|
||||
if [ "$#" -gt 0 ]; then
|
||||
for opt in "$@"; do
|
||||
case "${opt}" in
|
||||
--train) train=true ;;
|
||||
--val) val=true ;;
|
||||
--test) test=true ;;
|
||||
--segments) segments=true ;;
|
||||
esac
|
||||
done
|
||||
else
|
||||
train=true
|
||||
val=true
|
||||
test=false
|
||||
segments=false
|
||||
fi
|
||||
|
||||
# Download/unzip labels
|
||||
d='../datasets' # unzip directory
|
||||
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
||||
if [ "$segments" == "true" ]; then
|
||||
f='coco2017labels-segments.zip' # 168 MB
|
||||
else
|
||||
f='coco2017labels.zip' # 168 MB
|
||||
fi
|
||||
echo 'Downloading' $url$f ' ...'
|
||||
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
||||
|
||||
# Download/unzip images
|
||||
d='../datasets/coco/images' # unzip directory
|
||||
url=http://images.cocodataset.org/zips/
|
||||
if [ "$train" == "true" ]; then
|
||||
f='train2017.zip' # 19G, 118k images
|
||||
echo 'Downloading' $url$f '...'
|
||||
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
||||
fi
|
||||
if [ "$val" == "true" ]; then
|
||||
f='val2017.zip' # 1G, 5k images
|
||||
echo 'Downloading' $url$f '...'
|
||||
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
||||
fi
|
||||
if [ "$test" == "true" ]; then
|
||||
f='test2017.zip' # 7G, 41k images (optional)
|
||||
echo 'Downloading' $url$f '...'
|
||||
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
||||
fi
|
||||
wait # finish background tasks
|
17
app/yolov5/data/scripts/get_coco128.sh
Normal file
17
app/yolov5/data/scripts/get_coco128.sh
Normal file
@ -0,0 +1,17 @@
|
||||
#!/bin/bash
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
|
||||
# Example usage: bash data/scripts/get_coco128.sh
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── coco128 ← downloads here
|
||||
|
||||
# Download/unzip images and labels
|
||||
d='../datasets' # unzip directory
|
||||
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
||||
f='coco128.zip' # or 'coco128-segments.zip', 68 MB
|
||||
echo 'Downloading' $url$f ' ...'
|
||||
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
||||
|
||||
wait # finish background tasks
|
51
app/yolov5/data/scripts/get_imagenet.sh
Normal file
51
app/yolov5/data/scripts/get_imagenet.sh
Normal file
@ -0,0 +1,51 @@
|
||||
#!/bin/bash
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# Download ILSVRC2012 ImageNet dataset https://image-net.org
|
||||
# Example usage: bash data/scripts/get_imagenet.sh
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── imagenet ← downloads here
|
||||
|
||||
# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val
|
||||
if [ "$#" -gt 0 ]; then
|
||||
for opt in "$@"; do
|
||||
case "${opt}" in
|
||||
--train) train=true ;;
|
||||
--val) val=true ;;
|
||||
esac
|
||||
done
|
||||
else
|
||||
train=true
|
||||
val=true
|
||||
fi
|
||||
|
||||
# Make dir
|
||||
d='../datasets/imagenet' # unzip directory
|
||||
mkdir -p $d && cd $d
|
||||
|
||||
# Download/unzip train
|
||||
if [ "$train" == "true" ]; then
|
||||
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images
|
||||
mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train
|
||||
tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar
|
||||
find . -name "*.tar" | while read NAME; do
|
||||
mkdir -p "${NAME%.tar}"
|
||||
tar -xf "${NAME}" -C "${NAME%.tar}"
|
||||
rm -f "${NAME}"
|
||||
done
|
||||
cd ..
|
||||
fi
|
||||
|
||||
# Download/unzip val
|
||||
if [ "$val" == "true" ]; then
|
||||
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images
|
||||
mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar
|
||||
wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs
|
||||
fi
|
||||
|
||||
# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail)
|
||||
# rm train/n04266014/n04266014_10835.JPEG
|
||||
|
||||
# TFRecords (optional)
|
||||
# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt
|
153
app/yolov5/data/xView.yaml
Normal file
153
app/yolov5/data/xView.yaml
Normal file
@ -0,0 +1,153 @@
|
||||
# YOLOv5 🚀 by Ultralytics, GPL-3.0 license
|
||||
# DIUx xView 2018 Challenge https://challenge.xviewdataset.org by U.S. National Geospatial-Intelligence Agency (NGA)
|
||||
# -------- DOWNLOAD DATA MANUALLY and jar xf val_images.zip to 'datasets/xView' before running train command! --------
|
||||
# Example usage: python train.py --data xView.yaml
|
||||
# parent
|
||||
# ├── yolov5
|
||||
# └── datasets
|
||||
# └── xView ← downloads here (20.7 GB)
|
||||
|
||||
|
||||
# Train/val/test sets as 1) dir: path/to/imgs, 2) file: path/to/imgs.txt, or 3) list: [path/to/imgs1, path/to/imgs2, ..]
|
||||
path: ../datasets/xView # dataset root dir
|
||||
train: images/autosplit_train.txt # train images (relative to 'path') 90% of 847 train images
|
||||
val: images/autosplit_val.txt # train images (relative to 'path') 10% of 847 train images
|
||||
|
||||
# Classes
|
||||
names:
|
||||
0: Fixed-wing Aircraft
|
||||
1: Small Aircraft
|
||||
2: Cargo Plane
|
||||
3: Helicopter
|
||||
4: Passenger Vehicle
|
||||
5: Small Car
|
||||
6: Bus
|
||||
7: Pickup Truck
|
||||
8: Utility Truck
|
||||
9: Truck
|
||||
10: Cargo Truck
|
||||
11: Truck w/Box
|
||||
12: Truck Tractor
|
||||
13: Trailer
|
||||
14: Truck w/Flatbed
|
||||
15: Truck w/Liquid
|
||||
16: Crane Truck
|
||||
17: Railway Vehicle
|
||||
18: Passenger Car
|
||||
19: Cargo Car
|
||||
20: Flat Car
|
||||
21: Tank car
|
||||
22: Locomotive
|
||||
23: Maritime Vessel
|
||||
24: Motorboat
|
||||
25: Sailboat
|
||||
26: Tugboat
|
||||
27: Barge
|
||||
28: Fishing Vessel
|
||||
29: Ferry
|
||||
30: Yacht
|
||||
31: Container Ship
|
||||
32: Oil Tanker
|
||||
33: Engineering Vehicle
|
||||
34: Tower crane
|
||||
35: Container Crane
|
||||
36: Reach Stacker
|
||||
37: Straddle Carrier
|
||||
38: Mobile Crane
|
||||
39: Dump Truck
|
||||
40: Haul Truck
|
||||
41: Scraper/Tractor
|
||||
42: Front loader/Bulldozer
|
||||
43: Excavator
|
||||
44: Cement Mixer
|
||||
45: Ground Grader
|
||||
46: Hut/Tent
|
||||
47: Shed
|
||||
48: Building
|
||||
49: Aircraft Hangar
|
||||
50: Damaged Building
|
||||
51: Facility
|
||||
52: Construction Site
|
||||
53: Vehicle Lot
|
||||
54: Helipad
|
||||
55: Storage Tank
|
||||
56: Shipping container lot
|
||||
57: Shipping Container
|
||||
58: Pylon
|
||||
59: Tower
|
||||
|
||||
|
||||
# Download script/URL (optional) ---------------------------------------------------------------------------------------
|
||||
download: |
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
from tqdm import tqdm
|
||||
|
||||
from utils.datasets import autosplit
|
||||
from utils.general import download, xyxy2xywhn
|
||||
|
||||
|
||||
def convert_labels(fname=Path('xView/xView_train.geojson')):
|
||||
# Convert xView geoJSON labels to YOLO format
|
||||
path = fname.parent
|
||||
with open(fname) as f:
|
||||
print(f'Loading {fname}...')
|
||||
data = json.load(f)
|
||||
|
||||
# Make dirs
|
||||
labels = Path(path / 'labels' / 'train')
|
||||
os.system(f'rm -rf {labels}')
|
||||
labels.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# xView classes 11-94 to 0-59
|
||||
xview_class2index = [-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 0, 1, 2, -1, 3, -1, 4, 5, 6, 7, 8, -1, 9, 10, 11,
|
||||
12, 13, 14, 15, -1, -1, 16, 17, 18, 19, 20, 21, 22, -1, 23, 24, 25, -1, 26, 27, -1, 28, -1,
|
||||
29, 30, 31, 32, 33, 34, 35, 36, 37, -1, 38, 39, 40, 41, 42, 43, 44, 45, -1, -1, -1, -1, 46,
|
||||
47, 48, 49, -1, 50, 51, -1, 52, -1, -1, -1, 53, 54, -1, 55, -1, -1, 56, -1, 57, -1, 58, 59]
|
||||
|
||||
shapes = {}
|
||||
for feature in tqdm(data['features'], desc=f'Converting {fname}'):
|
||||
p = feature['properties']
|
||||
if p['bounds_imcoords']:
|
||||
id = p['image_id']
|
||||
file = path / 'train_images' / id
|
||||
if file.exists(): # 1395.tif missing
|
||||
try:
|
||||
box = np.array([int(num) for num in p['bounds_imcoords'].split(",")])
|
||||
assert box.shape[0] == 4, f'incorrect box shape {box.shape[0]}'
|
||||
cls = p['type_id']
|
||||
cls = xview_class2index[int(cls)] # xView class to 0-60
|
||||
assert 59 >= cls >= 0, f'incorrect class index {cls}'
|
||||
|
||||
# Write YOLO label
|
||||
if id not in shapes:
|
||||
shapes[id] = Image.open(file).size
|
||||
box = xyxy2xywhn(box[None].astype(np.float), w=shapes[id][0], h=shapes[id][1], clip=True)
|
||||
with open((labels / id).with_suffix('.txt'), 'a') as f:
|
||||
f.write(f"{cls} {' '.join(f'{x:.6f}' for x in box[0])}\n") # write label.txt
|
||||
except Exception as e:
|
||||
print(f'WARNING: skipping one label for {file}: {e}')
|
||||
|
||||
|
||||
# Download manually from https://challenge.xviewdataset.org
|
||||
dir = Path(yaml['path']) # dataset root dir
|
||||
# urls = ['https://d307kc0mrhucc3.cloudfront.net/train_labels.zip', # train labels
|
||||
# 'https://d307kc0mrhucc3.cloudfront.net/train_images.zip', # 15G, 847 train images
|
||||
# 'https://d307kc0mrhucc3.cloudfront.net/val_images.zip'] # 5G, 282 val images (no labels)
|
||||
# download(urls, dir=dir, delete=False)
|
||||
|
||||
# Convert labels
|
||||
convert_labels(dir / 'xView_train.geojson')
|
||||
|
||||
# Move images
|
||||
images = Path(dir / 'images')
|
||||
images.mkdir(parents=True, exist_ok=True)
|
||||
Path(dir / 'train_images').rename(dir / 'images' / 'train')
|
||||
Path(dir / 'val_images').rename(dir / 'images' / 'val')
|
||||
|
||||
# Split
|
||||
autosplit(dir / 'images' / 'train')
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user