2021SC@SDUSC山东大学软件学院软件工程应用与实践--YOLOV5代码分析(二)general.py-1

2021SC@SDUSC

目录

引用库

设置

Profile类

Timeout类

try_except函数

methods函数

set_logging函数

init_seeds函数

get_latest_run函数

user_config_dir函数


​​​​​​​

从这篇文章开始正式对代码进行解读,我会按照函数调用的关系自底向上进行解读,这一篇开始介绍general.py的部分,由于这部分代码量较大,我会分几次来进行解读。

引用库

import contextlib
import glob
import logging
import math
import os
import platform
import random
import re
import signal
import time
import urllib
from itertools import repeat
from multiprocessing.pool import ThreadPool
from pathlib import Path
from subprocess import check_output

import cv2
import numpy as np
import pandas as pd
import pkg_resources as pkg
import torch
import torchvision
import yaml

from utils.downloads import gsutil_getsize
from utils.metrics import box_iou, fitness

contextlib:是用于创建和使用上下文管理器的实用程序,该模块包含用于处理上下文管理器和with语句的实时程序。

glob:该模块用来查找文件目录和文件,并将搜索到的结果返回到一个列表中,常见的两个方法有glob.glob()和glob.iglob(),可以和常用的find功能进行类比。

logging:该模块可以根据自定义日志信息,在程序运行的时候将日志打印在终端及记录日志到文件中。

math:数学库

os:提供与操作系统进行交互的接口。

platform:该模块用来访问平台相关属性。

random:产生随机数

re:提供正则表达式功能

signal:负责在python程序内部处理信号,主要针对UNIX平台。

time:提供对日期和时间处理的功能。

urllib:提供爬取网页的功能。

itertools:提供了可在迭代器上工作以产生复杂迭代器的各种功能。repeat()函数属于无限迭代器类别,给出数据和数字,数据将被重复多少次,如果不指定数字,将重复无数次。

multiprocessing:提供了对多进程、线程的处理。

pathlib:该模块的操作对象是各种操作系统中使用的路径。

subprocess:允许生成新的进程,连接到它们的input/output/error管道,并获取它们的返回。check_output()函数执行指定的命令,如果执行状态码为0则返回执行结果,否则抛出异常。

cv2:openCV,提供对图像处理的方法。

numpy:对多维数据处理的常用库。

pandas:数据分析支持库。

pkg_resource:提供了运行时工具,用于查找、自省、激活和使用已安装的python发行版。

torch:pytorch库,深度学习框架。

torchvision:pytorch里对视觉处理

yaml:是一个专门用来写配置文件的语言。

设置

# Settings
torch.set_printoptions(linewidth=320, precision=5, profile='long')
np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format})  # format short g, %precision=5
pd.options.display.max_columns = 10
cv2.setNumThreads(0)  # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8))  # NumExpr max threads

 torch.set_printoptions设置了输出时的一些格式,linewidth-每行输出的长度,precision-浮点精度保留5位,profile-修正默认设置。

np.set_printoptions同上

pd.options.display.max_columns将输出的最大列数设为10

cv2.setNumThreads关闭opencv的多线程

接下来一句设置了该程序的线程数量。

Profile类

class Profile(contextlib.ContextDecorator):
    # Usage: @Profile() decorator or 'with Profile():' context manager
    def __enter__(self):
        self.start = time.time()

    def __exit__(self, type, value, traceback):
        print(f'Profile results: {time.time() - self.start:.5f}s')

继承自ContextDecorator类,该类是使上下文管理器也可以用作装饰器的基类,需要重写__enter__和__exit__函数.Profile用于计时,在进入时记录当前时间,退出时输出当前时间与start的差。

Timeout类

class Timeout(contextlib.ContextDecorator):
    # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
    def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
        self.seconds = int(seconds)
        self.timeout_message = timeout_msg
        self.suppress = bool(suppress_timeout_errors)

    def _timeout_handler(self, signum, frame):
        raise TimeoutError(self.timeout_message)

    def __enter__(self):
        signal.signal(signal.SIGALRM, self._timeout_handler)  # Set handler for SIGALRM
        signal.alarm(self.seconds)  # start countdown for SIGALRM to be raised

    def __exit__(self, exc_type, exc_val, exc_tb):
        signal.alarm(0)  # Cancel SIGALRM if it's scheduled
        if self.suppress and exc_type is TimeoutError:  # Suppress TimeoutError
            return True

该类同样继承自ContextDecorator,是用来检查是否超时。seconds是规定的时间,超出这个时间会抛出异常,timeout_msg是异常输出信息,suppress为是否严格检查,严格检查会抛出异常,而不严格则输出异常信息,程序继续执行。

__enter__方法,定义了一个闹钟信号,由signal.alarm发起,参数为seconds,即我们所要保证的时间,当时间超过了我们定义的时间,则会调用_timeout_handler,该方法抛出异常,执行,_-exit__方法。__exit__首先将闹钟关闭,防止程序正常退出时也报错,接下来看是否严格检查,是的话则抛出异常,否则直接返回,输出异常信息。

try_except函数

def try_except(func):
    # try-except function. Usage: @try_except decorator
    def handler(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as e:
            print(e)

    return handler

该函数将try 和 except模块融合了起来,当需要使用该模块时直接调用该函数即可,不用再调用try和ecept模块,func为要执行的内容。

methods函数

def methods(instance):
    # Get class/instance methods
    return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]

该函数将一个类或实例的全部公有方法返回成一个列表,方便后面调用。

set_logging函数

def set_logging(rank=-1, verbose=True):
    logging.basicConfig(
        format="%(message)s",
        level=logging.INFO if (verbose and rank in [-1, 0]) else logging.WARN)

使用默认格式化程序创建StreamHandler并将其添加到根日志记录器中,从而完成日志系统的基本配置。如果没有为根日志程序定义处理程序,debug(),info(),warning(),error()和critical()函数,将自动调用basicConfig()。

format为处理程序使用指定的格式字符串,level将根记录器级别设置为指定的级别。默认生成的root logger的level是logging.Warning,低于该级别的就不输出。

def print_args(name, opt):
    # Print argparser arguments
    print(colorstr(f'{name}: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))

输出argparser的参数

init_seeds函数

def init_seeds(seed=0):
    # Initialize random number generator (RNG) seeds https://pytorch.org/docs/stable/notes/randomness.html
    # cudnn seed 0 settings are slower and more reproducible, else faster and less reproducible
    import torch.backends.cudnn as cudnn
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    cudnn.benchmark, cudnn.deterministic = (False, True) if seed == 0 else (True, False)

初始化随机生成器的种子,当seed为0时将cudnn设为为更慢当可重用性更高,否则设置为更快但低可重用性。

get_latest_run函数

def get_latest_run(search_dir='.'):
    # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
    last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
    return max(last_list, key=os.path.getctime) if last_list else ''

last_list是glob返回的一个列表,glob.glob可以返回所有匹配的文件路径列表,参数定义了文件路径匹配规则,即找到所有last**.pt的文件路径,**代表的是其他所有字符串。最后根据创建的时间,返回离当前时间最近的路径

user_config_dir函数

def user_config_dir(dir='Ultralytics', env_var='YOLOV5_CONFIG_DIR'):
    # Return path of user configuration directory. Prefer environment variable if exists. Make dir if required.
    env = os.getenv(env_var)
    if env:
        path = Path(env)  # use environment variable
    else:
        cfg = {'Windows': 'AppData/Roaming', 'Linux': '.config', 'Darwin': 'Library/Application Support'}  # 3 OS dirs
        path = Path.home() / cfg.get(platform.system(), '')  # OS-specific config dir
        path = (path if is_writeable(path) else Path('/tmp')) / dir  # GCP and AWS lambda fix, only /tmp is writeable
    path.mkdir(exist_ok=True)  # make if required
    return path

返回用户配置环境目录的路径,当不存在时则创建一个。

  • 6
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值