补全yolov5的代码

This commit is contained in:
2025-03-13 17:48:59 +08:00
parent 6daea23f0a
commit 9d369b9898
42 changed files with 8571 additions and 171 deletions

View File

@ -10,8 +10,8 @@ import torch
import torchvision.transforms as T
import torchvision.transforms.functional as TF
from utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from utils.metrics import bbox_ioa
from yolov5.utils.general import LOGGER, check_version, colorstr, resample_segments, segment2box, xywhn2xyxy
from yolov5.utils.metrics import bbox_ioa
IMAGENET_MEAN = 0.485, 0.456, 0.406 # RGB mean
IMAGENET_STD = 0.229, 0.224, 0.225 # RGB standard deviation

View File

@ -26,7 +26,7 @@ from PIL import ExifTags, Image, ImageOps
from torch.utils.data import DataLoader, Dataset, dataloader, distributed
from tqdm import tqdm
from utils.augmentations import (
from yolov5.utils.augmentations import (
Albumentations,
augment_hsv,
classify_albumentations,
@ -36,7 +36,7 @@ from utils.augmentations import (
mixup,
random_perspective,
)
from utils.general import (
from yolov5.utils.general import (
DATASETS_DIR,
LOGGER,
NUM_THREADS,
@ -55,7 +55,7 @@ from utils.general import (
xywhn2xyxy,
xyxy2xywhn,
)
from utils.torch_utils import torch_distributed_zero_first
from yolov5.utils.torch_utils import torch_distributed_zero_first
# Parameters
HELP_URL = "See https://docs.ultralytics.com/yolov5/tutorials/train_custom_data"

View File

@ -45,9 +45,9 @@ except (ImportError, AssertionError):
from ultralytics.utils.checks import check_requirements
from utils import TryExcept, emojis
from utils.downloads import curl_download, gsutil_getsize
from utils.metrics import box_iou, fitness
from yolov5.utils import TryExcept, emojis
from yolov5.utils.downloads import curl_download, gsutil_getsize
from yolov5.utils.metrics import box_iou, fitness
FILE = Path(__file__).resolve()
ROOT = FILE.parents[1] # YOLOv5 root directory
@ -585,7 +585,7 @@ def check_dataset(data, autodownload=True):
def check_amp(model):
"""Checks PyTorch AMP functionality for a model, returns True if AMP operates correctly, otherwise False."""
from models.common import AutoShape, DetectMultiBackend
from yolov5.models.common import AutoShape, DetectMultiBackend
def amp_allclose(model, im):
"""Compares FP32 and AMP model inference outputs, ensuring they are close within a 10% absolute tolerance."""
@ -611,6 +611,27 @@ def check_amp(model):
return False
def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
# Rescale coords (xyxy) from img1_shape to img0_shape
if ratio_pad is None: # calculate from img0_shape
gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
else:
gain = ratio_pad[0][0]
pad = ratio_pad[1]
coords[:, [0, 2]] -= pad[0] # x padding
coords[:, [1, 3]] -= pad[1] # y padding
coords[:, :4] /= gain
# Clip bounding xyxy bounding boxes to image shape (height, width)
coords[:, 0].clamp_(0, img0_shape[1]) # x1
coords[:, 1].clamp_(0, img0_shape[0]) # y1
coords[:, 2].clamp_(0, img0_shape[1]) # x2
coords[:, 3].clamp_(0, img0_shape[0]) # y2
return coords
def yaml_load(file="data.yaml"):
"""Safely loads and returns the contents of a YAML file specified by `file` argument."""
with open(file, errors="ignore") as f:

View File

@ -1,135 +0,0 @@
{
"algorithm": "random",
"parameters": {
"anchor_t": {
"type": "discrete",
"values": [2, 8]
},
"batch_size": {
"type": "discrete",
"values": [16, 32, 64]
},
"box": {
"type": "discrete",
"values": [0.02, 0.2]
},
"cls": {
"type": "discrete",
"values": [0.2]
},
"cls_pw": {
"type": "discrete",
"values": [0.5]
},
"copy_paste": {
"type": "discrete",
"values": [1]
},
"degrees": {
"type": "discrete",
"values": [0, 45]
},
"epochs": {
"type": "discrete",
"values": [5]
},
"fl_gamma": {
"type": "discrete",
"values": [0]
},
"fliplr": {
"type": "discrete",
"values": [0]
},
"flipud": {
"type": "discrete",
"values": [0]
},
"hsv_h": {
"type": "discrete",
"values": [0]
},
"hsv_s": {
"type": "discrete",
"values": [0]
},
"hsv_v": {
"type": "discrete",
"values": [0]
},
"iou_t": {
"type": "discrete",
"values": [0.7]
},
"lr0": {
"type": "discrete",
"values": [1e-5, 0.1]
},
"lrf": {
"type": "discrete",
"values": [0.01, 1]
},
"mixup": {
"type": "discrete",
"values": [1]
},
"momentum": {
"type": "discrete",
"values": [0.6]
},
"mosaic": {
"type": "discrete",
"values": [0]
},
"obj": {
"type": "discrete",
"values": [0.2]
},
"obj_pw": {
"type": "discrete",
"values": [0.5]
},
"optimizer": {
"type": "categorical",
"values": ["SGD", "Adam", "AdamW"]
},
"perspective": {
"type": "discrete",
"values": [0]
},
"scale": {
"type": "discrete",
"values": [0]
},
"shear": {
"type": "discrete",
"values": [0]
},
"translate": {
"type": "discrete",
"values": [0]
},
"warmup_bias_lr": {
"type": "discrete",
"values": [0, 0.2]
},
"warmup_epochs": {
"type": "discrete",
"values": [5]
},
"warmup_momentum": {
"type": "discrete",
"values": [0, 0.95]
},
"weight_decay": {
"type": "discrete",
"values": [0, 0.001]
}
},
"spec": {
"maxCombo": 0,
"metric": "metrics/mAP_0.5",
"objective": "maximize"
},
"trials": 1
}

View File

@ -9,7 +9,7 @@ import matplotlib.pyplot as plt
import numpy as np
import torch
from utils import TryExcept, threaded
from yolov5.utils import TryExcept, threaded
def fitness(x):

View File

@ -18,9 +18,9 @@ from PIL import Image, ImageDraw
from scipy.ndimage.filters import gaussian_filter1d
from ultralytics.utils.plotting import Annotator
from utils import TryExcept, threaded
from utils.general import LOGGER, clip_boxes, increment_path, xywh2xyxy, xyxy2xywh
from utils.metrics import fitness
from yolov5.utils import TryExcept, threaded
from yolov5.utils.general import LOGGER, clip_boxes, increment_path, xywh2xyxy, xyxy2xywh
from yolov5.utils.metrics import fitness
# Settings
RANK = int(os.getenv("RANK", -1))
@ -372,7 +372,7 @@ def plot_labels(labels, names=(), save_dir=Path("")):
def imshow_cls(im, labels=None, pred=None, names=None, nmax=25, verbose=False, f=Path("images.jpg")):
"""Displays a grid of images with optional labels and predictions, saving to a file."""
from utils.augmentations import denormalize
from yolov5.utils.augmentations import denormalize
names = names or [f"class{i}" for i in range(1000)]
blocks = torch.chunk(

View File

@ -17,7 +17,7 @@ import torch.nn as nn
import torch.nn.functional as F
from torch.nn.parallel import DistributedDataParallel as DDP
from utils.general import LOGGER, check_version, colorstr, file_date, git_describe
from yolov5.utils.general import LOGGER, check_version, colorstr, file_date, git_describe
LOCAL_RANK = int(os.getenv("LOCAL_RANK", -1)) # https://pytorch.org/docs/stable/elastic/run.html
RANK = int(os.getenv("RANK", -1))
@ -68,7 +68,7 @@ def smart_DDP(model):
def reshape_classifier_output(model, n=1000):
"""Reshapes last layer of model to match class count 'n', supporting Classify, Linear, Sequential types."""
from models.common import Classify
from yolov5.models.common import Classify
name, m = list((model.model if hasattr(model, "model") else model).named_children())[-1] # last module
if isinstance(m, Classify): # YOLOv5 Classify() head