AK391 commited on
Commit
e6e7cb5
·
1 Parent(s): 528cf18
data/coco-kp.yaml ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
3
+ path: data/datasets/coco
4
+ labels: kp_labels
5
+ train: kp_labels/img_txt/train2017.txt
6
+ val: kp_labels/img_txt/val2017.txt
7
+ test: kp_labels/img_txt/test2017.txt
8
+
9
+ train_annotations: annotations/person_keypoints_train2017.json
10
+ val_annotations: annotations/person_keypoints_val2017.json
11
+ test_annotations: annotations/image_info_test-dev2017.json
12
+
13
+ pose_obj: True # write pose object labels
14
+
15
+ nc: 18 # number of classes (person class + 17 keypoint classes)
16
+ num_coords: 34 # number of keypoint coordinates (x, y)
17
+
18
+ # class names
19
+ names: [ 'person', 'nose',
20
+ 'left_eye', 'right_eye',
21
+ 'left_ear', 'right_ear',
22
+ 'left_shoulder', 'right_shoulder',
23
+ 'left_elbow', 'right_elbow',
24
+ 'left_wrist', 'right_wrist',
25
+ 'left_hip', 'right_hip',
26
+ 'left_knee', 'right_knee',
27
+ 'left_ankle', 'right_ankle' ]
28
+
29
+ kp_bbox: 0.05 # keypoint object size (normalized by longest img dim)
30
+ kp_flip: [0, 2, 1, 4, 3, 6, 5, 8, 7, 10, 9, 12, 11, 14, 13, 16, 15] # for left-right keypoint flipping
31
+ kp_left: [1, 3, 5, 7, 9, 11, 13, 15] # left keypoints
32
+
33
+ kp_names_short:
34
+ 0: 'n'
35
+ 1: 'ley'
36
+ 2: 'rey'
37
+ 3: 'lea'
38
+ 4: 'rea'
39
+ 5: 'ls'
40
+ 6: 'rs'
41
+ 7: 'lel'
42
+ 8: 'rel'
43
+ 9: 'lw'
44
+ 10: 'rw'
45
+ 11: 'lh'
46
+ 12: 'rh'
47
+ 13: 'lk'
48
+ 14: 'rk'
49
+ 15: 'la'
50
+ 16: 'ra'
51
+
52
+ # segments for plotting
53
+ segments:
54
+ 1: [5, 6]
55
+ 2: [5, 11]
56
+ 3: [11, 12]
57
+ 4: [12, 6]
58
+ 5: [5, 7]
59
+ 6: [7, 9]
60
+ 7: [6, 8]
61
+ 8: [8, 10]
62
+ 9: [11, 13]
63
+ 10: [13, 15]
64
+ 11: [12, 14]
65
+ 12: [14, 16]
data/crowdpose.yaml ADDED
@@ -0,0 +1,62 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+
2
+ # train and val data as 1) directory: path/images/, 2) file: path/images.txt, or 3) list: [path1/images/, path2/images/]
3
+ path: data/datasets/crowdpose
4
+ labels: kp_labels
5
+ train: kp_labels/img_txt/trainval.txt
6
+ val: kp_labels/img_txt/test.txt
7
+
8
+ train_annotations: crowdpose_trainval.json
9
+ val_annotations: crowdpose_test.json
10
+
11
+ pose_obj: True # write pose object labels
12
+
13
+ nc: 15 # number of classes (person class + 14 keypoint classes)
14
+ num_coords: 28 # number of keypoint coordinates (x, y)
15
+
16
+ # class names
17
+ names: [ 'person',
18
+ 'left_shoulder', 'right_shoulder',
19
+ 'left_elbow', 'right_elbow',
20
+ 'left_wrist', 'right_wrist',
21
+ 'left_hip', 'right_hip',
22
+ 'left_knee', 'right_knee',
23
+ 'left_ankle', 'right_ankle',
24
+ 'head', 'neck']
25
+
26
+ kp_bbox: 0.05 # keypoint object size (normalized by longest img dim)
27
+ kp_flip: [1, 0, 3, 2, 5, 4, 7, 6, 9, 8, 11, 10, 12, 13] # for left-right keypoint flipping
28
+ kp_left: [0, 2, 4, 6, 8, 10] # left keypoints
29
+
30
+ kp_names_short:
31
+ 0: 'ls'
32
+ 1: 'rs'
33
+ 2: 'lel'
34
+ 3: 'rel'
35
+ 4: 'lw'
36
+ 5: 'rw'
37
+ 6: 'lh'
38
+ 7: 'rh'
39
+ 8: 'lk'
40
+ 9: 'rk'
41
+ 10: 'la'
42
+ 11: 'ra'
43
+ 12: 'h'
44
+ 13: 'n'
45
+
46
+ # segments for plotting
47
+ segments:
48
+ 1: [0, 13]
49
+ 2: [1, 13]
50
+ 3: [0, 2]
51
+ 4: [2, 4]
52
+ 5: [1, 3]
53
+ 6: [3, 5]
54
+ 7: [0, 6]
55
+ 8: [6, 7]
56
+ 9: [7, 1]
57
+ 10: [6, 8]
58
+ 11: [8, 10]
59
+ 12: [7, 9]
60
+ 13: [9, 11]
61
+ 14: [12, 13]
62
+
data/hyps/hyp.kp-p6.yaml ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for COCO training from scratch
3
+ # python train.py --batch 32 --cfg yolov5m6.yaml --weights '' --data coco.yaml --img 1280 --epochs 300
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8
+ momentum: 0.937 # SGD momentum/Adam beta1
9
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
10
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
11
+ warmup_momentum: 0.8 # warmup initial momentum
12
+ warmup_bias_lr: 0.1 # warmup initial bias lr
13
+ box: 0.05 # box loss gain
14
+ cls: 0.3 # cls loss gain
15
+ cls_pw: 1.0 # cls BCELoss positive_weight
16
+ obj: 0.7 # obj loss gain (scale with pixels)
17
+ obj_pw: 1.0 # obj BCELoss positive_weight
18
+ kp: 0.025 # kp loss gain
19
+ iou_t: 0.20 # IoU training threshold
20
+ anchor_t: 4.0 # anchor-multiple threshold
21
+ # anchors: 3 # anchors per output layer (0 to ignore)
22
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
23
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
24
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
25
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
26
+ degrees: 0.0 # image rotation (+/- deg)
27
+ translate: 0.1 # image translation (+/- fraction)
28
+ scale: 0.9 # image scale (+/- gain)
29
+ shear: 0.0 # image shear (+/- deg)
30
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
31
+ flipud: 0.0 # image flip up-down (probability)
32
+ fliplr: 0.5 # image flip left-right (probability)
33
+ mosaic: 1.0 # image mosaic (probability)
34
+ mixup: 0.0 # image mixup (probability)
35
+ copy_paste: 0.0 # segment copy-paste (probability)
36
+ kp_bbox: 0.05
data/hyps/hyp.kp.yaml ADDED
@@ -0,0 +1,54 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ # Hyperparameters for COCO training from scratch
3
+ # python train.py --batch 40 --cfg yolov5m.yaml --weights '' --data coco.yaml --img 640 --epochs 300
4
+ # See tutorials for hyperparameter evolution https://github.com/ultralytics/yolov5#tutorials
5
+
6
+ lr0: 0.01 # initial learning rate (SGD=1E-2, Adam=1E-3)
7
+ lrf: 0.2 # final OneCycleLR learning rate (lr0 * lrf)
8
+ momentum: 0.937 # SGD momentum/Adam beta1
9
+ weight_decay: 0.0005 # optimizer weight decay 5e-4
10
+ warmup_epochs: 3.0 # warmup epochs (fractions ok)
11
+ warmup_momentum: 0.8 # warmup initial momentum
12
+ warmup_bias_lr: 0.1 # warmup initial bias lr
13
+ box: 0.05 # box loss gain
14
+ cls: 0.5 # cls loss gain
15
+ cls_pw: 1.0 # cls BCELoss positive_weight
16
+ obj: 1.0 # obj loss gain (scale with pixels)
17
+ obj_pw: 1.0 # obj BCELoss positive_weight
18
+ kp: 0.05 # kp loss gain
19
+ iou_t: 0.20 # IoU training threshold
20
+ anchor_t: 4.0 # anchor-multiple threshold
21
+ # anchors: 3 # anchors per output layer (0 to ignore)
22
+ fl_gamma: 0.0 # focal loss gamma (efficientDet default gamma=1.5)
23
+ hsv_h: 0.015 # image HSV-Hue augmentation (fraction)
24
+ hsv_s: 0.7 # image HSV-Saturation augmentation (fraction)
25
+ hsv_v: 0.4 # image HSV-Value augmentation (fraction)
26
+ degrees: 0.0 # image rotation (+/- deg)
27
+ translate: 0.2 # image translation (+/- fraction)
28
+ scale: 0.8 # image scale (+/- gain)
29
+ shear: 0.0 # image shear (+/- deg)
30
+ perspective: 0.0 # image perspective (+/- fraction), range 0-0.001
31
+ flipud: 0.0 # image flip up-down (probability)
32
+ fliplr: 0.5 # image flip left-right (probability)
33
+ mosaic: 1.0 # image mosaic (probability)
34
+ mixup: 0.0 # image mixup (probability)
35
+ copy_paste: 0.0 # segment copy-paste (probability)
36
+ kp_bbox: 0.05
37
+ #kp_bbox:
38
+ #- 0.026 # nose
39
+ #- 0.025 # left eye
40
+ #- 0.025 # right eye
41
+ #- 0.035 # left ear
42
+ #- 0.035 # right ear
43
+ #- 0.079 # left shoulder
44
+ #- 0.079 # right shoulder
45
+ #- 0.072 # left elbow
46
+ #- 0.072 # right elbow
47
+ #- 0.062 # left wrist
48
+ #- 0.062 # right wrist
49
+ #- 0.107 # left hip
50
+ #- 0.107 # right hip
51
+ #- 0.087 # left knee
52
+ #- 0.087 # right knee
53
+ #- 0.089 # left ankle
54
+ #- 0.089 # right ankle
data/scripts/download_models.sh ADDED
@@ -0,0 +1,10 @@
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Example usage: bash data/scripts/download_models.sh
3
+
4
+ gdown https://drive.google.com/uc?id=1hv0xwdbdf-Ym06Hpjy6wKyIklNmKmB99 # kapao_s_coco.pt
5
+ gdown https://drive.google.com/uc?id=1B-QGa99n7ZrxkgKCQ1XHnm6j0Y-lvOQz # kapao_m_coco.pt
6
+ gdown https://drive.google.com/uc?id=1jYDfvRjhMoDf5xpMq1AuzdkFzUeLwt85 # kapao_l_coco.pt
7
+
8
+ gdown https://drive.google.com/uc?id=1SmWwmqPwb_G6d9UPAFSUnWZ-4eaL9TTv # kapao_s_crowdpose.pt
9
+ gdown https://drive.google.com/uc?id=1IqrAk-gBdcfONrlIT6d4ndaDqnlFmT0r # kapao_m_crowdpose.pt
10
+ gdown https://drive.google.com/uc?id=146DW9ELzIBY2oDofPru446yLErxHrjJU # kapao_l_crowdpose.pt
data/scripts/get_coco_kp.sh ADDED
@@ -0,0 +1,27 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Example usage: bash data/scripts/get_coco_kp.sh
3
+
4
+ # Make dataset directories
5
+ mkdir -p data/datasets/coco/images
6
+
7
+ # Download/unzip annotations
8
+ d='data/datasets/coco' # unzip directory
9
+ f1='annotations_trainval2017.zip'
10
+ f2='image_info_test2017.zip'
11
+ url=http://images.cocodataset.org/annotations/
12
+ for f in $f1 $f2; do
13
+ echo 'Downloading' $url$f '...'
14
+ curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &
15
+ done
16
+
17
+ # Download/unzip images
18
+ d='data/datasets/coco/images' # unzip directory
19
+ url=http://images.cocodataset.org/zips/
20
+ f1='train2017.zip' # 19G, 118k images
21
+ f2='val2017.zip' # 1G, 5k images
22
+ f3='test2017.zip' # 7G, 41k images (optional)
23
+ for f in $f1 $f2 $f3; do
24
+ echo 'Downloading' $url$f '...'
25
+ curl -L $url$f -o $f && unzip -q $f -d $d && rm $f &
26
+ done
27
+ wait # finish background tasks
data/scripts/get_crowdpose.sh ADDED
@@ -0,0 +1,11 @@
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Example usage: bash data/scripts/get_crowdpose.sh
3
+
4
+ # Make dataset directories
5
+ mkdir -p data/datasets/crowdpose
6
+
7
+ gdown -O data/datasets/crowdpose/images.zip https://drive.google.com/uc?id=1VprytECcLtU4tKP32SYi_7oDRbw7yUTL
8
+ gdown -O data/datasets/crowdpose/crowdpose_trainval.json https://drive.google.com/uc?id=13xScmTWqO6Y6m_CjiQ-23ptgX9sC-J9I
9
+ gdown -O data/datasets/crowdpose/crowdpose_test.json https://drive.google.com/uc?id=1FUzRj-dPbL1OyBwcIX2BgFPEaY5Yrz7S
10
+ unzip -q -d data/datasets/crowdpose data/datasets/crowdpose/images.zip
11
+ rm data/datasets/crowdpose/images.zip
demos/flash_mob.py ADDED
@@ -0,0 +1,166 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ FILE = Path(__file__).absolute()
4
+ sys.path.append(FILE.parents[1].as_posix()) # add kapao/ to path
5
+
6
+ import argparse
7
+ from pytube import YouTube
8
+ import os.path as osp
9
+ from utils.torch_utils import select_device, time_sync
10
+ from utils.general import check_img_size
11
+ from utils.datasets import LoadImages
12
+ from models.experimental import attempt_load
13
+ import torch
14
+ import cv2
15
+ import numpy as np
16
+ import yaml
17
+ from tqdm import tqdm
18
+ import imageio
19
+ from val import run_nms, post_process_batch
20
+
21
+
22
+ VIDEO_NAME = 'Crazy Uptown Funk Flashmob in Sydney for sydney domains campaign.mp4'
23
+ URL = 'https://www.youtube.com/watch?v=2DiQUX11YaY&ab_channel=CrazyDomains'
24
+ COLOR = (255, 0, 255) # purple
25
+ ALPHA = 0.5
26
+ SEG_THICK = 3
27
+ FPS_TEXT_SIZE = 2
28
+
29
+
30
+ if __name__ == '__main__':
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument('--data', type=str, default='data/coco-kp.yaml')
33
+ parser.add_argument('--imgsz', type=int, default=1280)
34
+ parser.add_argument('--weights', default='kapao_s_coco.pt')
35
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or cpu')
36
+ parser.add_argument('--half', action='store_true')
37
+ parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
38
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
39
+ parser.add_argument('--no-kp-dets', action='store_true', help='do not use keypoint objects')
40
+ parser.add_argument('--conf-thres-kp', type=float, default=0.5)
41
+ parser.add_argument('--conf-thres-kp-person', type=float, default=0.2)
42
+ parser.add_argument('--iou-thres-kp', type=float, default=0.45)
43
+ parser.add_argument('--overwrite-tol', type=int, default=50)
44
+ parser.add_argument('--scales', type=float, nargs='+', default=[1])
45
+ parser.add_argument('--flips', type=int, nargs='+', default=[-1])
46
+ parser.add_argument('--display', action='store_true', help='display inference results')
47
+ parser.add_argument('--fps', action='store_true', help='display fps')
48
+ parser.add_argument('--gif', action='store_true', help='create fig')
49
+ parser.add_argument('--start', type=int, default=68, help='start time (s)')
50
+ parser.add_argument('--end', type=int, default=98, help='end time (s)')
51
+ args = parser.parse_args()
52
+
53
+ with open(args.data) as f:
54
+ data = yaml.safe_load(f) # load data dict
55
+
56
+ # add inference settings to data dict
57
+ data['imgsz'] = args.imgsz
58
+ data['conf_thres'] = args.conf_thres
59
+ data['iou_thres'] = args.iou_thres
60
+ data['use_kp_dets'] = not args.no_kp_dets
61
+ data['conf_thres_kp'] = args.conf_thres_kp
62
+ data['iou_thres_kp'] = args.iou_thres_kp
63
+ data['conf_thres_kp_person'] = args.conf_thres_kp_person
64
+ data['overwrite_tol'] = args.overwrite_tol
65
+ data['scales'] = args.scales
66
+ data['flips'] = [None if f == -1 else f for f in args.flips]
67
+
68
+ if not osp.isfile(VIDEO_NAME):
69
+ yt = YouTube(URL)
70
+ # [print(s) for s in yt.streams]
71
+ stream = [s for s in yt.streams if s.itag == 136][0] # 720p, non-progressive
72
+ print('Downloading squash demo video...')
73
+ stream.download()
74
+ print('Done.')
75
+
76
+ device = select_device(args.device, batch_size=1)
77
+ print('Using device: {}'.format(device))
78
+
79
+ model = attempt_load(args.weights, map_location=device) # load FP32 model
80
+ half = args.half & (device.type != 'cpu')
81
+ if half: # half precision only supported on CUDA
82
+ model.half()
83
+ stride = int(model.stride.max()) # model stride
84
+
85
+ imgsz = check_img_size(args.imgsz, s=stride) # check image size
86
+ dataset = LoadImages('./{}'.format(VIDEO_NAME), img_size=imgsz, stride=stride, auto=True)
87
+
88
+ if device.type != 'cpu':
89
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
90
+
91
+ cap = dataset.cap
92
+ cap.set(cv2.CAP_PROP_POS_MSEC, args.start * 1000)
93
+ fps = cap.get(cv2.CAP_PROP_FPS)
94
+ n = int(fps * (args.end - args.start))
95
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
96
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
97
+ gif_frames = []
98
+ video_name = 'flash_mob_inference_{}'.format(osp.splitext(args.weights)[0])
99
+
100
+ if not args.display:
101
+ writer = cv2.VideoWriter(video_name + '.mp4',
102
+ cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
103
+ if not args.fps: # tqdm might slows down inference
104
+ dataset = tqdm(dataset, desc='Writing inference video', total=n)
105
+
106
+ t0 = time_sync()
107
+ for i, (path, img, im0, _) in enumerate(dataset):
108
+ img = torch.from_numpy(img).to(device)
109
+ img = img.half() if half else img.float() # uint8 to fp16/32
110
+ img = img / 255.0 # 0 - 255 to 0.0 - 1.0
111
+ if len(img.shape) == 3:
112
+ img = img[None] # expand for batch dim
113
+
114
+ out = model(img, augment=True, kp_flip=data['kp_flip'], scales=data['scales'], flips=data['flips'])[0]
115
+ person_dets, kp_dets = run_nms(data, out)
116
+ bboxes, poses, _, _, _ = post_process_batch(data, img, [], [[im0.shape[:2]]], person_dets, kp_dets)
117
+
118
+ im0_copy = im0.copy()
119
+
120
+ # DRAW POSES
121
+ for j, (bbox, pose) in enumerate(zip(bboxes, poses)):
122
+ x1, y1, x2, y2 = bbox
123
+ size = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
124
+ # if size < 450:
125
+ cv2.rectangle(im0_copy, (int(x1), int(y1)), (int(x2), int(y2)), COLOR, thickness=2)
126
+ for seg in data['segments'].values():
127
+ pt1 = (int(pose[seg[0], 0]), int(pose[seg[0], 1]))
128
+ pt2 = (int(pose[seg[1], 0]), int(pose[seg[1], 1]))
129
+ cv2.line(im0_copy, pt1, pt2, COLOR, SEG_THICK)
130
+ im0 = cv2.addWeighted(im0, ALPHA, im0_copy, 1 - ALPHA, gamma=0)
131
+
132
+ if i == 0:
133
+ t = time_sync() - t0
134
+ else:
135
+ t = time_sync() - t1
136
+
137
+ if args.fps:
138
+ s = FPS_TEXT_SIZE
139
+ cv2.putText(im0, '{:.1f} FPS'.format(1 / t), (5*s, 25*s),
140
+ cv2.FONT_HERSHEY_SIMPLEX, s, (255, 255, 255), thickness=2*s)
141
+
142
+ if args.gif:
143
+ gif_frames.append(cv2.resize(im0, dsize=None, fx=0.375, fy=0.375)[:, :, [2, 1, 0]])
144
+ elif not args.display:
145
+ writer.write(im0)
146
+ else:
147
+ cv2.imshow('', im0)
148
+ cv2.waitKey(1)
149
+
150
+ t1 = time_sync()
151
+ if i == n - 1:
152
+ break
153
+
154
+ cv2.destroyAllWindows()
155
+ cap.release()
156
+ if not args.display:
157
+ writer.release()
158
+
159
+ if args.gif:
160
+ print('Saving GIF...')
161
+ with imageio.get_writer(video_name + '.gif', mode="I", fps=fps) as writer:
162
+ for idx, frame in tqdm(enumerate(gif_frames)):
163
+ writer.append_data(frame)
164
+
165
+
166
+
demos/general.py ADDED
@@ -0,0 +1,165 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ FILE = Path(__file__).absolute()
4
+ sys.path.append(FILE.parents[1].as_posix()) # add kapao/ to path
5
+
6
+ import argparse
7
+ from pytube import YouTube
8
+ import os.path as osp
9
+ from utils.torch_utils import select_device, time_sync
10
+ from utils.general import check_img_size
11
+ from utils.datasets import LoadImages
12
+ from models.experimental import attempt_load
13
+ import torch
14
+ import cv2
15
+ import numpy as np
16
+ import yaml
17
+ from tqdm import tqdm
18
+ import imageio
19
+ from val import run_nms, post_process_batch
20
+
21
+
22
+ VIDEO_NAME = 'Crazy Uptown Funk Flashmob in Sydney for sydney domains campaign.mp4'
23
+ URL = 'https://www.youtube.com/watch?v=2DiQUX11YaY&ab_channel=CrazyDomains'
24
+ COLOR = (255, 0, 255) # purple
25
+ ALPHA = 0.5
26
+ SEG_THICK = 3
27
+ FPS_TEXT_SIZE = 2
28
+
29
+
30
+ if __name__ == '__main__':
31
+ parser = argparse.ArgumentParser()
32
+ parser.add_argument('--vid', type=str, default='')
33
+ parser.add_argument('--data', type=str, default='data/coco-kp.yaml')
34
+ parser.add_argument('--imgsz', type=int, default=1280)
35
+ parser.add_argument('--weights', default='kapao_s_coco.pt')
36
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or cpu')
37
+ parser.add_argument('--half', action='store_true')
38
+ parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
39
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
40
+ parser.add_argument('--no-kp-dets', action='store_true', help='do not use keypoint objects')
41
+ parser.add_argument('--conf-thres-kp', type=float, default=0.5)
42
+ parser.add_argument('--conf-thres-kp-person', type=float, default=0.2)
43
+ parser.add_argument('--iou-thres-kp', type=float, default=0.45)
44
+ parser.add_argument('--overwrite-tol', type=int, default=50)
45
+ parser.add_argument('--scales', type=float, nargs='+', default=[1])
46
+ parser.add_argument('--flips', type=int, nargs='+', default=[-1])
47
+ parser.add_argument('--display', action='store_true', help='display inference results')
48
+ parser.add_argument('--fps', action='store_true', help='display fps')
49
+ parser.add_argument('--gif', action='store_true', help='create fig')
50
+ parser.add_argument('--start', type=int, default=68, help='start time (s)')
51
+ parser.add_argument('--end', type=int, default=98, help='end time (s)')
52
+ args = parser.parse_args()
53
+
54
+ with open(args.data) as f:
55
+ data = yaml.safe_load(f) # load data dict
56
+
57
+ # add inference settings to data dict
58
+ data['imgsz'] = args.imgsz
59
+ data['conf_thres'] = args.conf_thres
60
+ data['iou_thres'] = args.iou_thres
61
+ data['use_kp_dets'] = not args.no_kp_dets
62
+ data['conf_thres_kp'] = args.conf_thres_kp
63
+ data['iou_thres_kp'] = args.iou_thres_kp
64
+ data['conf_thres_kp_person'] = args.conf_thres_kp_person
65
+ data['overwrite_tol'] = args.overwrite_tol
66
+ data['scales'] = args.scales
67
+ data['flips'] = [None if f == -1 else f for f in args.flips]
68
+
69
+ if not osp.isfile(VIDEO_NAME):
70
+ yt = YouTube(URL)
71
+ # [print(s) for s in yt.streams]
72
+ stream = [s for s in yt.streams if s.itag == 136][0] # 720p, non-progressive
73
+ print('Downloading squash demo video...')
74
+ stream.download()
75
+ print('Done.')
76
+
77
+ device = select_device(args.device, batch_size=1)
78
+ print('Using device: {}'.format(device))
79
+
80
+ model = attempt_load(args.weights, map_location=device) # load FP32 model
81
+ half = args.half & (device.type != 'cpu')
82
+ if half: # half precision only supported on CUDA
83
+ model.half()
84
+ stride = int(model.stride.max()) # model stride
85
+
86
+ imgsz = check_img_size(args.imgsz, s=stride) # check image size
87
+ dataset = LoadImages('./{}'.format(args.vid), img_size=imgsz, stride=stride, auto=True)
88
+
89
+ if device.type != 'cpu':
90
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
91
+
92
+ cap = dataset.cap
93
+ cap.set(cv2.CAP_PROP_POS_MSEC, args.start * 1000)
94
+ fps = cap.get(cv2.CAP_PROP_FPS)
95
+ n = int(fps * (args.end - args.start))
96
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
97
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
98
+ gif_frames = []
99
+ video_name = 'flash_mob_inference_{}'.format(osp.splitext(args.weights)[0])
100
+
101
+ if not args.display:
102
+ writer = cv2.VideoWriter(video_name + '.mp4',
103
+ cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
104
+ if not args.fps: # tqdm might slows down inference
105
+ dataset = tqdm(dataset, desc='Writing inference video', total=n)
106
+
107
+ t0 = time_sync()
108
+ for i, (path, img, im0, _) in enumerate(dataset):
109
+ img = torch.from_numpy(img).to(device)
110
+ img = img.half() if half else img.float() # uint8 to fp16/32
111
+ img = img / 255.0 # 0 - 255 to 0.0 - 1.0
112
+ if len(img.shape) == 3:
113
+ img = img[None] # expand for batch dim
114
+
115
+ out = model(img, augment=True, kp_flip=data['kp_flip'], scales=data['scales'], flips=data['flips'])[0]
116
+ person_dets, kp_dets = run_nms(data, out)
117
+ bboxes, poses, _, _, _ = post_process_batch(data, img, [], [[im0.shape[:2]]], person_dets, kp_dets)
118
+
119
+ im0_copy = im0.copy()
120
+
121
+ # DRAW POSES
122
+ for j, (bbox, pose) in enumerate(zip(bboxes, poses)):
123
+ x1, y1, x2, y2 = bbox
124
+ size = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
125
+ # if size < 450:
126
+ cv2.rectangle(im0_copy, (int(x1), int(y1)), (int(x2), int(y2)), COLOR, thickness=2)
127
+ for seg in data['segments'].values():
128
+ pt1 = (int(pose[seg[0], 0]), int(pose[seg[0], 1]))
129
+ pt2 = (int(pose[seg[1], 0]), int(pose[seg[1], 1]))
130
+ cv2.line(im0_copy, pt1, pt2, COLOR, SEG_THICK)
131
+ im0 = cv2.addWeighted(im0, ALPHA, im0_copy, 1 - ALPHA, gamma=0)
132
+
133
+ if i == 0:
134
+ t = time_sync() - t0
135
+ else:
136
+ t = time_sync() - t1
137
+
138
+ if args.fps:
139
+ s = FPS_TEXT_SIZE
140
+ cv2.putText(im0, '{:.1f} FPS'.format(1 / t), (5*s, 25*s),
141
+ cv2.FONT_HERSHEY_SIMPLEX, s, (255, 255, 255), thickness=2*s)
142
+
143
+ if args.gif:
144
+ gif_frames.append(cv2.resize(im0, dsize=None, fx=0.375, fy=0.375)[:, :, [2, 1, 0]])
145
+ elif not args.display:
146
+ writer.write(im0)
147
+ else:
148
+ cv2.imshow('', im0)
149
+ cv2.waitKey(1)
150
+
151
+ t1 = time_sync()
152
+ if i == n - 1:
153
+ break
154
+
155
+ cv2.destroyAllWindows()
156
+ cap.release()
157
+ if not args.display:
158
+ writer.release()
159
+
160
+ if args.gif:
161
+ print('Saving GIF...')
162
+ with imageio.get_writer(video_name + '.gif', mode="I", fps=fps) as writer:
163
+ for idx, frame in tqdm(enumerate(gif_frames)):
164
+ writer.append_data(frame)
165
+
demos/squash.py ADDED
@@ -0,0 +1,243 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+ FILE = Path(__file__).absolute()
4
+ sys.path.append(FILE.parents[1].as_posix()) # add kapao/ to path
5
+
6
+ import argparse
7
+ from pytube import YouTube
8
+ import os.path as osp
9
+ from utils.torch_utils import select_device, time_sync
10
+ from utils.general import check_img_size
11
+ from utils.datasets import LoadImages
12
+ from models.experimental import attempt_load
13
+ import torch
14
+ import cv2
15
+ import numpy as np
16
+ import yaml
17
+ from tqdm import tqdm
18
+ import imageio
19
+ from val import run_nms, post_process_batch
20
+
21
+
22
+ VIDEO_NAME = 'Squash MegaRally 176 ReDux - Slow Mo Edition.mp4'
23
+ URL = 'https://www.youtube.com/watch?v=Dy62-eTNvY4&ab_channel=PSASQUASHTV'
24
+
25
+ GRAY = (200, 200, 200)
26
+ CROWD_THRES = 450 # max bbox size for crowd classification
27
+ CROWD_ALPHA = 0.5
28
+ CROWD_KP_SIZE = 2
29
+ CROWD_KP_THICK = 2
30
+ CROWD_SEG_THICK = 2
31
+
32
+ BLUE = (245, 140, 66)
33
+ ORANGE = (66, 140, 245)
34
+ PLAYER_ALPHA_BOX = 0.85
35
+ PLAYER_ALPHA_POSE = 0.3
36
+ PLAYER_KP_SIZE = 4
37
+ PLAYER_KP_THICK = 4
38
+ PLAYER_SEG_THICK = 4
39
+ FPS_TEXT_SIZE = 3
40
+
41
+
42
+ if __name__ == '__main__':
43
+ parser = argparse.ArgumentParser()
44
+ parser.add_argument('--data', type=str, default='data/coco-kp.yaml')
45
+ parser.add_argument('--imgsz', type=int, default=1280)
46
+ parser.add_argument('--weights', default='kapao_s_coco.pt')
47
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or cpu')
48
+ parser.add_argument('--half', action='store_true')
49
+ parser.add_argument('--conf-thres', type=float, default=0.5, help='confidence threshold')
50
+ parser.add_argument('--iou-thres', type=float, default=0.45, help='NMS IoU threshold')
51
+ parser.add_argument('--no-kp-dets', action='store_true', help='do not use keypoint objects')
52
+ parser.add_argument('--conf-thres-kp', type=float, default=0.5)
53
+ parser.add_argument('--conf-thres-kp-person', type=float, default=0.2)
54
+ parser.add_argument('--iou-thres-kp', type=float, default=0.45)
55
+ parser.add_argument('--overwrite-tol', type=int, default=50)
56
+ parser.add_argument('--scales', type=float, nargs='+', default=[1])
57
+ parser.add_argument('--flips', type=int, nargs='+', default=[-1])
58
+ parser.add_argument('--display', action='store_true', help='display inference results')
59
+ parser.add_argument('--fps', action='store_true', help='display fps')
60
+ parser.add_argument('--gif', action='store_true', help='create fig')
61
+ parser.add_argument('--start', type=int, default=20, help='start time (s)')
62
+ parser.add_argument('--end', type=int, default=80, help='end time (s)')
63
+ args = parser.parse_args()
64
+
65
+ with open(args.data) as f:
66
+ data = yaml.safe_load(f) # load data dict
67
+
68
+ # add inference settings to data dict
69
+ data['imgsz'] = args.imgsz
70
+ data['conf_thres'] = args.conf_thres
71
+ data['iou_thres'] = args.iou_thres
72
+ data['use_kp_dets'] = not args.no_kp_dets
73
+ data['conf_thres_kp'] = args.conf_thres_kp
74
+ data['iou_thres_kp'] = args.iou_thres_kp
75
+ data['conf_thres_kp_person'] = args.conf_thres_kp_person
76
+ data['overwrite_tol'] = args.overwrite_tol
77
+ data['scales'] = args.scales
78
+ data['flips'] = [None if f == -1 else f for f in args.flips]
79
+
80
+ if not osp.isfile(VIDEO_NAME):
81
+ yt = YouTube(URL)
82
+ # [print(s) for s in yt.streams]
83
+ stream = [s for s in yt.streams if s.itag == 137][0] # 1080p, non-progressive
84
+ print('Downloading squash demo video...')
85
+ stream.download()
86
+ print('Done.')
87
+
88
+ device = select_device(args.device, batch_size=1)
89
+ print('Using device: {}'.format(device))
90
+
91
+ model = attempt_load(args.weights, map_location=device) # load FP32 model
92
+ half = args.half & (device.type != 'cpu')
93
+ if half: # half precision only supported on CUDA
94
+ model.half()
95
+ stride = int(model.stride.max()) # model stride
96
+
97
+ imgsz = check_img_size(args.imgsz, s=stride) # check image size
98
+ dataset = LoadImages('./{}'.format(VIDEO_NAME), img_size=imgsz, stride=stride, auto=True)
99
+
100
+ if device.type != 'cpu':
101
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
102
+
103
+ cap = dataset.cap
104
+ cap.set(cv2.CAP_PROP_POS_MSEC, args.start * 1000)
105
+ fps = cap.get(cv2.CAP_PROP_FPS)
106
+ n = int(fps * (args.end - args.start))
107
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
108
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
109
+ gif_frames = []
110
+ video_name = 'squash_inference_{}'.format(osp.splitext(args.weights)[0])
111
+
112
+ if not args.display:
113
+ writer = cv2.VideoWriter(video_name + '.mp4',
114
+ cv2.VideoWriter_fourcc(*'mp4v'), fps, (w, h))
115
+ if not args.fps: # tqdm might slows down inference
116
+ dataset = tqdm(dataset, desc='Writing inference video', total=n)
117
+
118
+ t0 = time_sync()
119
+ for i, (path, img, im0, _) in enumerate(dataset):
120
+ img = torch.from_numpy(img).to(device)
121
+ img = img.half() if half else img.float() # uint8 to fp16/32
122
+ img = img / 255.0 # 0 - 255 to 0.0 - 1.0
123
+ if len(img.shape) == 3:
124
+ img = img[None] # expand for batch dim
125
+
126
+ out = model(img, augment=True, kp_flip=data['kp_flip'], scales=data['scales'], flips=data['flips'])[0]
127
+ person_dets, kp_dets = run_nms(data, out)
128
+ bboxes, poses, _, _, _ = post_process_batch(data, img, [], [[im0.shape[:2]]], person_dets, kp_dets)
129
+
130
+ bboxes = np.array(bboxes)
131
+ poses = np.array(poses)
132
+
133
+ im0_copy = im0.copy()
134
+ player_idx = []
135
+
136
+ # DRAW CROWD POSES
137
+ for j, (bbox, pose) in enumerate(zip(bboxes, poses)):
138
+ x1, y1, x2, y2 = bbox
139
+ size = ((x2 - x1) ** 2 + (y2 - y1) ** 2) ** 0.5
140
+ if size < CROWD_THRES:
141
+ cv2.rectangle(im0_copy, (int(x1), int(y1)), (int(x2), int(y2)), GRAY, thickness=2)
142
+ for x, y, _ in pose[:5]:
143
+ cv2.circle(im0_copy, (int(x), int(y)), CROWD_KP_SIZE, GRAY, CROWD_KP_THICK)
144
+ for seg in data['segments'].values():
145
+ pt1 = (int(pose[seg[0], 0]), int(pose[seg[0], 1]))
146
+ pt2 = (int(pose[seg[1], 0]), int(pose[seg[1], 1]))
147
+ cv2.line(im0_copy, pt1, pt2, GRAY, CROWD_SEG_THICK)
148
+ else:
149
+ player_idx.append(j)
150
+ im0 = cv2.addWeighted(im0, CROWD_ALPHA, im0_copy, 1 - CROWD_ALPHA, gamma=0)
151
+
152
+ # DRAW PLAYER POSES
153
+ player_bboxes = bboxes[player_idx][:2]
154
+ player_poses = poses[player_idx][:2]
155
+
156
+ def draw_player_poses(im0, missing=-1):
157
+ for j, (bbox, pose, color) in enumerate(zip(
158
+ player_bboxes[[orange_player, blue_player]],
159
+ player_poses[[orange_player, blue_player]],
160
+ [ORANGE, BLUE])):
161
+ if j == missing:
162
+ continue
163
+ im0_copy = im0.copy()
164
+ x1, y1, x2, y2 = bbox
165
+ cv2.rectangle(im0_copy, (int(x1), int(y1)), (int(x2), int(y2)), color, thickness=-1)
166
+ im0 = cv2.addWeighted(im0, PLAYER_ALPHA_BOX, im0_copy, 1 - PLAYER_ALPHA_BOX, gamma=0)
167
+ im0_copy = im0.copy()
168
+ for x, y, _ in pose:
169
+ cv2.circle(im0_copy, (int(x), int(y)), PLAYER_KP_SIZE, color, PLAYER_KP_THICK)
170
+ for seg in data['segments'].values():
171
+ pt1 = (int(pose[seg[0], 0]), int(pose[seg[0], 1]))
172
+ pt2 = (int(pose[seg[1], 0]), int(pose[seg[1], 1]))
173
+ cv2.line(im0_copy, pt1, pt2, color, PLAYER_SEG_THICK)
174
+ im0 = cv2.addWeighted(im0, PLAYER_ALPHA_POSE, im0_copy, 1 - PLAYER_ALPHA_POSE, gamma=0)
175
+ return im0
176
+
177
+ if i == 0:
178
+ # orange player on left at start
179
+ orange_player = np.argmin(player_bboxes[:, 0])
180
+ blue_player = int(not orange_player)
181
+ im0 = draw_player_poses(im0)
182
+ else:
183
+ # simple player tracking based on frame-to-frame pose difference
184
+ dist = []
185
+ for pose in poses_last:
186
+ dist.append(np.mean(np.linalg.norm(player_poses[0, :, :2] - pose[:, :2], axis=-1)))
187
+ if np.argmin(dist) == 0:
188
+ orange_player = 0
189
+ else:
190
+ orange_player = 1
191
+ blue_player = int(not orange_player)
192
+
193
+ # if only one player detected, find which player is missing
194
+ missing = -1
195
+ if len(player_poses) == 1:
196
+ if orange_player == 0: # missing blue player
197
+ player_poses = np.concatenate((player_poses, poses_last[1:]), axis=0)
198
+ player_bboxes = np.concatenate((player_bboxes, bboxes_last[1:]), axis=0)
199
+ missing = 1
200
+ else: # missing orange player
201
+ player_poses = np.concatenate((player_poses, poses_last[:1]), axis=0)
202
+ player_bboxes = np.concatenate((player_bboxes, bboxes_last[:1]), axis=0)
203
+ missing = 0
204
+ im0 = draw_player_poses(im0, missing)
205
+
206
+ bboxes_last = player_bboxes[[orange_player, blue_player]]
207
+ poses_last = player_poses[[orange_player, blue_player]]
208
+
209
+ if i == 0:
210
+ t = time_sync() - t0
211
+ else:
212
+ t = time_sync() - t1
213
+
214
+ if args.fps:
215
+ s = FPS_TEXT_SIZE
216
+ cv2.putText(im0, '{:.1f} FPS'.format(1 / t), (5*s, 25*s),
217
+ cv2.FONT_HERSHEY_SIMPLEX, s, (255, 255, 255), thickness=2*s)
218
+
219
+ if args.gif:
220
+ gif_frames.append(cv2.resize(im0, dsize=None, fx=0.25, fy=0.25)[:, :, [2, 1, 0]])
221
+ elif not args.display:
222
+ writer.write(im0)
223
+ else:
224
+ cv2.imshow('', cv2.resize(im0, dsize=None, fx=0.5, fy=0.5))
225
+ cv2.waitKey(1)
226
+
227
+ t1 = time_sync()
228
+ if i == n - 1:
229
+ break
230
+
231
+ cv2.destroyAllWindows()
232
+ cap.release()
233
+ if not args.display:
234
+ writer.release()
235
+
236
+ if args.gif:
237
+ print('Saving GIF...')
238
+ with imageio.get_writer(video_name + '.gif', mode="I", fps=fps) as writer:
239
+ for idx, frame in tqdm(enumerate(gif_frames)):
240
+ writer.append_data(frame)
241
+
242
+
243
+
models/common.py ADDED
@@ -0,0 +1,452 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Common modules
4
+ """
5
+
6
+ import logging
7
+ import math
8
+ import warnings
9
+ from copy import copy
10
+ from pathlib import Path
11
+
12
+ import numpy as np
13
+ import pandas as pd
14
+ import requests
15
+ import torch
16
+ import torch.nn as nn
17
+ from PIL import Image
18
+ from torch.cuda import amp
19
+
20
+ from utils.datasets import exif_transpose, letterbox
21
+ from utils.general import colorstr, increment_path, is_ascii, make_divisible, non_max_suppression, save_one_box, \
22
+ scale_coords, xyxy2xywh
23
+ from utils.plots import Annotator, colors
24
+ from utils.torch_utils import time_sync
25
+
26
+ LOGGER = logging.getLogger(__name__)
27
+
28
+
29
+ def autopad(k, p=None): # kernel, padding
30
+ # Pad to 'same'
31
+ if p is None:
32
+ p = k // 2 if isinstance(k, int) else [x // 2 for x in k] # auto-pad
33
+ return p
34
+
35
+
36
+ class Conv(nn.Module):
37
+ # Standard convolution
38
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
39
+ super().__init__()
40
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g, bias=False)
41
+ self.bn = nn.BatchNorm2d(c2)
42
+ self.act = nn.SiLU() if act is True else (act if isinstance(act, nn.Module) else nn.Identity())
43
+
44
+ def forward(self, x):
45
+ return self.act(self.bn(self.conv(x)))
46
+
47
+ def forward_fuse(self, x):
48
+ return self.act(self.conv(x))
49
+
50
+
51
+ class DWConv(Conv):
52
+ # Depth-wise convolution class
53
+ def __init__(self, c1, c2, k=1, s=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
54
+ super().__init__(c1, c2, k, s, g=math.gcd(c1, c2), act=act)
55
+
56
+
57
+ class TransformerLayer(nn.Module):
58
+ # Transformer layer https://arxiv.org/abs/2010.11929 (LayerNorm layers removed for better performance)
59
+ def __init__(self, c, num_heads):
60
+ super().__init__()
61
+ self.q = nn.Linear(c, c, bias=False)
62
+ self.k = nn.Linear(c, c, bias=False)
63
+ self.v = nn.Linear(c, c, bias=False)
64
+ self.ma = nn.MultiheadAttention(embed_dim=c, num_heads=num_heads)
65
+ self.fc1 = nn.Linear(c, c, bias=False)
66
+ self.fc2 = nn.Linear(c, c, bias=False)
67
+
68
+ def forward(self, x):
69
+ x = self.ma(self.q(x), self.k(x), self.v(x))[0] + x
70
+ x = self.fc2(self.fc1(x)) + x
71
+ return x
72
+
73
+
74
+ class TransformerBlock(nn.Module):
75
+ # Vision Transformer https://arxiv.org/abs/2010.11929
76
+ def __init__(self, c1, c2, num_heads, num_layers):
77
+ super().__init__()
78
+ self.conv = None
79
+ if c1 != c2:
80
+ self.conv = Conv(c1, c2)
81
+ self.linear = nn.Linear(c2, c2) # learnable position embedding
82
+ self.tr = nn.Sequential(*[TransformerLayer(c2, num_heads) for _ in range(num_layers)])
83
+ self.c2 = c2
84
+
85
+ def forward(self, x):
86
+ if self.conv is not None:
87
+ x = self.conv(x)
88
+ b, _, w, h = x.shape
89
+ p = x.flatten(2).unsqueeze(0).transpose(0, 3).squeeze(3)
90
+ return self.tr(p + self.linear(p)).unsqueeze(3).transpose(0, 3).reshape(b, self.c2, w, h)
91
+
92
+
93
+ class Bottleneck(nn.Module):
94
+ # Standard bottleneck
95
+ def __init__(self, c1, c2, shortcut=True, g=1, e=0.5): # ch_in, ch_out, shortcut, groups, expansion
96
+ super().__init__()
97
+ c_ = int(c2 * e) # hidden channels
98
+ self.cv1 = Conv(c1, c_, 1, 1)
99
+ self.cv2 = Conv(c_, c2, 3, 1, g=g)
100
+ self.add = shortcut and c1 == c2
101
+
102
+ def forward(self, x):
103
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
104
+
105
+
106
+ class BottleneckCSP(nn.Module):
107
+ # CSP Bottleneck https://github.com/WongKinYiu/CrossStagePartialNetworks
108
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
109
+ super().__init__()
110
+ c_ = int(c2 * e) # hidden channels
111
+ self.cv1 = Conv(c1, c_, 1, 1)
112
+ self.cv2 = nn.Conv2d(c1, c_, 1, 1, bias=False)
113
+ self.cv3 = nn.Conv2d(c_, c_, 1, 1, bias=False)
114
+ self.cv4 = Conv(2 * c_, c2, 1, 1)
115
+ self.bn = nn.BatchNorm2d(2 * c_) # applied to cat(cv2, cv3)
116
+ self.act = nn.LeakyReLU(0.1, inplace=True)
117
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
118
+
119
+ def forward(self, x):
120
+ y1 = self.cv3(self.m(self.cv1(x)))
121
+ y2 = self.cv2(x)
122
+ return self.cv4(self.act(self.bn(torch.cat((y1, y2), dim=1))))
123
+
124
+
125
+ class C3(nn.Module):
126
+ # CSP Bottleneck with 3 convolutions
127
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5): # ch_in, ch_out, number, shortcut, groups, expansion
128
+ super().__init__()
129
+ c_ = int(c2 * e) # hidden channels
130
+ self.cv1 = Conv(c1, c_, 1, 1)
131
+ self.cv2 = Conv(c1, c_, 1, 1)
132
+ self.cv3 = Conv(2 * c_, c2, 1) # act=FReLU(c2)
133
+ self.m = nn.Sequential(*[Bottleneck(c_, c_, shortcut, g, e=1.0) for _ in range(n)])
134
+ # self.m = nn.Sequential(*[CrossConv(c_, c_, 3, 1, g, 1.0, shortcut) for _ in range(n)])
135
+
136
+ def forward(self, x):
137
+ return self.cv3(torch.cat((self.m(self.cv1(x)), self.cv2(x)), dim=1))
138
+
139
+
140
+ class C3TR(C3):
141
+ # C3 module with TransformerBlock()
142
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
143
+ super().__init__(c1, c2, n, shortcut, g, e)
144
+ c_ = int(c2 * e)
145
+ self.m = TransformerBlock(c_, c_, 4, n)
146
+
147
+
148
+ class C3SPP(C3):
149
+ # C3 module with SPP()
150
+ def __init__(self, c1, c2, k=(5, 9, 13), n=1, shortcut=True, g=1, e=0.5):
151
+ super().__init__(c1, c2, n, shortcut, g, e)
152
+ c_ = int(c2 * e)
153
+ self.m = SPP(c_, c_, k)
154
+
155
+
156
+ class C3Ghost(C3):
157
+ # C3 module with GhostBottleneck()
158
+ def __init__(self, c1, c2, n=1, shortcut=True, g=1, e=0.5):
159
+ super().__init__(c1, c2, n, shortcut, g, e)
160
+ c_ = int(c2 * e) # hidden channels
161
+ self.m = nn.Sequential(*[GhostBottleneck(c_, c_) for _ in range(n)])
162
+
163
+
164
+ class SPP(nn.Module):
165
+ # Spatial Pyramid Pooling (SPP) layer https://arxiv.org/abs/1406.4729
166
+ def __init__(self, c1, c2, k=(5, 9, 13)):
167
+ super().__init__()
168
+ c_ = c1 // 2 # hidden channels
169
+ self.cv1 = Conv(c1, c_, 1, 1)
170
+ self.cv2 = Conv(c_ * (len(k) + 1), c2, 1, 1)
171
+ self.m = nn.ModuleList([nn.MaxPool2d(kernel_size=x, stride=1, padding=x // 2) for x in k])
172
+
173
+ def forward(self, x):
174
+ x = self.cv1(x)
175
+ with warnings.catch_warnings():
176
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
177
+ return self.cv2(torch.cat([x] + [m(x) for m in self.m], 1))
178
+
179
+
180
+ class SPPF(nn.Module):
181
+ # Spatial Pyramid Pooling - Fast (SPPF) layer for YOLOv5 by Glenn Jocher
182
+ def __init__(self, c1, c2, k=5): # equivalent to SPP(k=(5, 9, 13))
183
+ super().__init__()
184
+ c_ = c1 // 2 # hidden channels
185
+ self.cv1 = Conv(c1, c_, 1, 1)
186
+ self.cv2 = Conv(c_ * 4, c2, 1, 1)
187
+ self.m = nn.MaxPool2d(kernel_size=k, stride=1, padding=k // 2)
188
+
189
+ def forward(self, x):
190
+ x = self.cv1(x)
191
+ with warnings.catch_warnings():
192
+ warnings.simplefilter('ignore') # suppress torch 1.9.0 max_pool2d() warning
193
+ y1 = self.m(x)
194
+ y2 = self.m(y1)
195
+ return self.cv2(torch.cat([x, y1, y2, self.m(y2)], 1))
196
+
197
+
198
+ class Focus(nn.Module):
199
+ # Focus wh information into c-space
200
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1, act=True): # ch_in, ch_out, kernel, stride, padding, groups
201
+ super().__init__()
202
+ self.conv = Conv(c1 * 4, c2, k, s, p, g, act)
203
+ # self.contract = Contract(gain=2)
204
+
205
+ def forward(self, x): # x(b,c,w,h) -> y(b,4c,w/2,h/2)
206
+ return self.conv(torch.cat([x[..., ::2, ::2], x[..., 1::2, ::2], x[..., ::2, 1::2], x[..., 1::2, 1::2]], 1))
207
+ # return self.conv(self.contract(x))
208
+
209
+
210
+ class GhostConv(nn.Module):
211
+ # Ghost Convolution https://github.com/huawei-noah/ghostnet
212
+ def __init__(self, c1, c2, k=1, s=1, g=1, act=True): # ch_in, ch_out, kernel, stride, groups
213
+ super().__init__()
214
+ c_ = c2 // 2 # hidden channels
215
+ self.cv1 = Conv(c1, c_, k, s, None, g, act)
216
+ self.cv2 = Conv(c_, c_, 5, 1, None, c_, act)
217
+
218
+ def forward(self, x):
219
+ y = self.cv1(x)
220
+ return torch.cat([y, self.cv2(y)], 1)
221
+
222
+
223
+ class GhostBottleneck(nn.Module):
224
+ # Ghost Bottleneck https://github.com/huawei-noah/ghostnet
225
+ def __init__(self, c1, c2, k=3, s=1): # ch_in, ch_out, kernel, stride
226
+ super().__init__()
227
+ c_ = c2 // 2
228
+ self.conv = nn.Sequential(GhostConv(c1, c_, 1, 1), # pw
229
+ DWConv(c_, c_, k, s, act=False) if s == 2 else nn.Identity(), # dw
230
+ GhostConv(c_, c2, 1, 1, act=False)) # pw-linear
231
+ self.shortcut = nn.Sequential(DWConv(c1, c1, k, s, act=False),
232
+ Conv(c1, c2, 1, 1, act=False)) if s == 2 else nn.Identity()
233
+
234
+ def forward(self, x):
235
+ return self.conv(x) + self.shortcut(x)
236
+
237
+
238
+ class Contract(nn.Module):
239
+ # Contract width-height into channels, i.e. x(1,64,80,80) to x(1,256,40,40)
240
+ def __init__(self, gain=2):
241
+ super().__init__()
242
+ self.gain = gain
243
+
244
+ def forward(self, x):
245
+ b, c, h, w = x.size() # assert (h / s == 0) and (W / s == 0), 'Indivisible gain'
246
+ s = self.gain
247
+ x = x.view(b, c, h // s, s, w // s, s) # x(1,64,40,2,40,2)
248
+ x = x.permute(0, 3, 5, 1, 2, 4).contiguous() # x(1,2,2,64,40,40)
249
+ return x.view(b, c * s * s, h // s, w // s) # x(1,256,40,40)
250
+
251
+
252
+ class Expand(nn.Module):
253
+ # Expand channels into width-height, i.e. x(1,64,80,80) to x(1,16,160,160)
254
+ def __init__(self, gain=2):
255
+ super().__init__()
256
+ self.gain = gain
257
+
258
+ def forward(self, x):
259
+ b, c, h, w = x.size() # assert C / s ** 2 == 0, 'Indivisible gain'
260
+ s = self.gain
261
+ x = x.view(b, s, s, c // s ** 2, h, w) # x(1,2,2,16,80,80)
262
+ x = x.permute(0, 3, 4, 1, 5, 2).contiguous() # x(1,16,80,2,80,2)
263
+ return x.view(b, c // s ** 2, h * s, w * s) # x(1,16,160,160)
264
+
265
+
266
+ class Concat(nn.Module):
267
+ # Concatenate a list of tensors along dimension
268
+ def __init__(self, dimension=1):
269
+ super().__init__()
270
+ self.d = dimension
271
+
272
+ def forward(self, x):
273
+ return torch.cat(x, self.d)
274
+
275
+
276
+ class AutoShape(nn.Module):
277
+ # YOLOv5 input-robust model wrapper for passing cv2/np/PIL/torch inputs. Includes preprocessing, inference and NMS
278
+ conf = 0.25 # NMS confidence threshold
279
+ iou = 0.45 # NMS IoU threshold
280
+ classes = None # (optional list) filter by class
281
+ max_det = 1000 # maximum number of detections per image
282
+
283
+ def __init__(self, model):
284
+ super().__init__()
285
+ self.model = model.eval()
286
+
287
+ def autoshape(self):
288
+ LOGGER.info('AutoShape already enabled, skipping... ') # model already converted to model.autoshape()
289
+ return self
290
+
291
+ @torch.no_grad()
292
+ def forward(self, imgs, size=640, augment=False, profile=False):
293
+ # Inference from various sources. For height=640, width=1280, RGB images example inputs are:
294
+ # file: imgs = 'data/images/zidane.jpg' # str or PosixPath
295
+ # URI: = 'https://ultralytics.com/images/zidane.jpg'
296
+ # OpenCV: = cv2.imread('image.jpg')[:,:,::-1] # HWC BGR to RGB x(640,1280,3)
297
+ # PIL: = Image.open('image.jpg') or ImageGrab.grab() # HWC x(640,1280,3)
298
+ # numpy: = np.zeros((640,1280,3)) # HWC
299
+ # torch: = torch.zeros(16,3,320,640) # BCHW (scaled to size=640, 0-1 values)
300
+ # multiple: = [Image.open('image1.jpg'), Image.open('image2.jpg'), ...] # list of images
301
+
302
+ t = [time_sync()]
303
+ p = next(self.model.parameters()) # for device and type
304
+ if isinstance(imgs, torch.Tensor): # torch
305
+ with amp.autocast(enabled=p.device.type != 'cpu'):
306
+ return self.model(imgs.to(p.device).type_as(p), augment, profile) # inference
307
+
308
+ # Pre-process
309
+ n, imgs = (len(imgs), imgs) if isinstance(imgs, list) else (1, [imgs]) # number of images, list of images
310
+ shape0, shape1, files = [], [], [] # image and inference shapes, filenames
311
+ for i, im in enumerate(imgs):
312
+ f = f'image{i}' # filename
313
+ if isinstance(im, (str, Path)): # filename or uri
314
+ im, f = Image.open(requests.get(im, stream=True).raw if str(im).startswith('http') else im), im
315
+ im = np.asarray(exif_transpose(im))
316
+ elif isinstance(im, Image.Image): # PIL Image
317
+ im, f = np.asarray(exif_transpose(im)), getattr(im, 'filename', f) or f
318
+ files.append(Path(f).with_suffix('.jpg').name)
319
+ if im.shape[0] < 5: # image in CHW
320
+ im = im.transpose((1, 2, 0)) # reverse dataloader .transpose(2, 0, 1)
321
+ im = im[..., :3] if im.ndim == 3 else np.tile(im[..., None], 3) # enforce 3ch input
322
+ s = im.shape[:2] # HWC
323
+ shape0.append(s) # image shape
324
+ g = (size / max(s)) # gain
325
+ shape1.append([y * g for y in s])
326
+ imgs[i] = im if im.data.contiguous else np.ascontiguousarray(im) # update
327
+ shape1 = [make_divisible(x, int(self.stride.max())) for x in np.stack(shape1, 0).max(0)] # inference shape
328
+ x = [letterbox(im, new_shape=shape1, auto=False)[0] for im in imgs] # pad
329
+ x = np.stack(x, 0) if n > 1 else x[0][None] # stack
330
+ x = np.ascontiguousarray(x.transpose((0, 3, 1, 2))) # BHWC to BCHW
331
+ x = torch.from_numpy(x).to(p.device).type_as(p) / 255. # uint8 to fp16/32
332
+ t.append(time_sync())
333
+
334
+ with amp.autocast(enabled=p.device.type != 'cpu'):
335
+ # Inference
336
+ y = self.model(x, augment, profile)[0] # forward
337
+ t.append(time_sync())
338
+
339
+ # Post-process
340
+ y = non_max_suppression(y, self.conf, iou_thres=self.iou, classes=self.classes, max_det=self.max_det) # NMS
341
+ for i in range(n):
342
+ scale_coords(shape1, y[i][:, :4], shape0[i])
343
+
344
+ t.append(time_sync())
345
+ return Detections(imgs, y, files, t, self.names, x.shape)
346
+
347
+
348
+ class Detections:
349
+ # YOLOv5 detections class for inference results
350
+ def __init__(self, imgs, pred, files, times=None, names=None, shape=None):
351
+ super().__init__()
352
+ d = pred[0].device # device
353
+ gn = [torch.tensor([*[im.shape[i] for i in [1, 0, 1, 0]], 1., 1.], device=d) for im in imgs] # normalizations
354
+ self.imgs = imgs # list of images as numpy arrays
355
+ self.pred = pred # list of tensors pred[0] = (xyxy, conf, cls)
356
+ self.names = names # class names
357
+ self.ascii = is_ascii(names) # names are ascii (use PIL for UTF-8)
358
+ self.files = files # image filenames
359
+ self.xyxy = pred # xyxy pixels
360
+ self.xywh = [xyxy2xywh(x) for x in pred] # xywh pixels
361
+ self.xyxyn = [x / g for x, g in zip(self.xyxy, gn)] # xyxy normalized
362
+ self.xywhn = [x / g for x, g in zip(self.xywh, gn)] # xywh normalized
363
+ self.n = len(self.pred) # number of images (batch size)
364
+ self.t = tuple((times[i + 1] - times[i]) * 1000 / self.n for i in range(3)) # timestamps (ms)
365
+ self.s = shape # inference BCHW shape
366
+
367
+ def display(self, pprint=False, show=False, save=False, crop=False, render=False, save_dir=Path('')):
368
+ for i, (im, pred) in enumerate(zip(self.imgs, self.pred)):
369
+ str = f'image {i + 1}/{len(self.pred)}: {im.shape[0]}x{im.shape[1]} '
370
+ if pred.shape[0]:
371
+ for c in pred[:, -1].unique():
372
+ n = (pred[:, -1] == c).sum() # detections per class
373
+ str += f"{n} {self.names[int(c)]}{'s' * (n > 1)}, " # add to string
374
+ if show or save or render or crop:
375
+ annotator = Annotator(im, pil=not self.ascii)
376
+ for *box, conf, cls in reversed(pred): # xyxy, confidence, class
377
+ label = f'{self.names[int(cls)]} {conf:.2f}'
378
+ if crop:
379
+ save_one_box(box, im, file=save_dir / 'crops' / self.names[int(cls)] / self.files[i])
380
+ else: # all others
381
+ annotator.box_label(box, label, color=colors(cls))
382
+ im = annotator.im
383
+ else:
384
+ str += '(no detections)'
385
+
386
+ im = Image.fromarray(im.astype(np.uint8)) if isinstance(im, np.ndarray) else im # from np
387
+ if pprint:
388
+ LOGGER.info(str.rstrip(', '))
389
+ if show:
390
+ im.show(self.files[i]) # show
391
+ if save:
392
+ f = self.files[i]
393
+ im.save(save_dir / f) # save
394
+ if i == self.n - 1:
395
+ LOGGER.info(f"Saved {self.n} image{'s' * (self.n > 1)} to {colorstr('bold', save_dir)}")
396
+ if render:
397
+ self.imgs[i] = np.asarray(im)
398
+
399
+ def print(self):
400
+ self.display(pprint=True) # print results
401
+ LOGGER.info(f'Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {tuple(self.s)}' %
402
+ self.t)
403
+
404
+ def show(self):
405
+ self.display(show=True) # show results
406
+
407
+ def save(self, save_dir='runs/detect/exp'):
408
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
409
+ self.display(save=True, save_dir=save_dir) # save results
410
+
411
+ def crop(self, save_dir='runs/detect/exp'):
412
+ save_dir = increment_path(save_dir, exist_ok=save_dir != 'runs/detect/exp', mkdir=True) # increment save_dir
413
+ self.display(crop=True, save_dir=save_dir) # crop results
414
+ LOGGER.info(f'Saved results to {save_dir}\n')
415
+
416
+ def render(self):
417
+ self.display(render=True) # render results
418
+ return self.imgs
419
+
420
+ def pandas(self):
421
+ # return detections as pandas DataFrames, i.e. print(results.pandas().xyxy[0])
422
+ new = copy(self) # return copy
423
+ ca = 'xmin', 'ymin', 'xmax', 'ymax', 'confidence', 'class', 'name' # xyxy columns
424
+ cb = 'xcenter', 'ycenter', 'width', 'height', 'confidence', 'class', 'name' # xywh columns
425
+ for k, c in zip(['xyxy', 'xyxyn', 'xywh', 'xywhn'], [ca, ca, cb, cb]):
426
+ a = [[x[:5] + [int(x[5]), self.names[int(x[5])]] for x in x.tolist()] for x in getattr(self, k)] # update
427
+ setattr(new, k, [pd.DataFrame(x, columns=c) for x in a])
428
+ return new
429
+
430
+ def tolist(self):
431
+ # return a list of Detections objects, i.e. 'for result in results.tolist():'
432
+ x = [Detections([self.imgs[i]], [self.pred[i]], self.names, self.s) for i in range(self.n)]
433
+ for d in x:
434
+ for k in ['imgs', 'pred', 'xyxy', 'xyxyn', 'xywh', 'xywhn']:
435
+ setattr(d, k, getattr(d, k)[0]) # pop out of list
436
+ return x
437
+
438
+ def __len__(self):
439
+ return self.n
440
+
441
+
442
+ class Classify(nn.Module):
443
+ # Classification head, i.e. x(b,c1,20,20) to x(b,c2)
444
+ def __init__(self, c1, c2, k=1, s=1, p=None, g=1): # ch_in, ch_out, kernel, stride, padding, groups
445
+ super().__init__()
446
+ self.aap = nn.AdaptiveAvgPool2d(1) # to x(b,c1,1,1)
447
+ self.conv = nn.Conv2d(c1, c2, k, s, autopad(k, p), groups=g) # to x(b,c2,1,1)
448
+ self.flat = nn.Flatten()
449
+
450
+ def forward(self, x):
451
+ z = torch.cat([self.aap(y) for y in (x if isinstance(x, list) else [x])], 1) # cat if list
452
+ return self.flat(self.conv(z)) # flatten to x(b,c2)
models/experimental.py ADDED
@@ -0,0 +1,115 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Experimental modules
4
+ """
5
+
6
+ import numpy as np
7
+ import torch
8
+ import torch.nn as nn
9
+
10
+ from models.common import Conv
11
+ from utils.downloads import attempt_download
12
+
13
+
14
+ class CrossConv(nn.Module):
15
+ # Cross Convolution Downsample
16
+ def __init__(self, c1, c2, k=3, s=1, g=1, e=1.0, shortcut=False):
17
+ # ch_in, ch_out, kernel, stride, groups, expansion, shortcut
18
+ super().__init__()
19
+ c_ = int(c2 * e) # hidden channels
20
+ self.cv1 = Conv(c1, c_, (1, k), (1, s))
21
+ self.cv2 = Conv(c_, c2, (k, 1), (s, 1), g=g)
22
+ self.add = shortcut and c1 == c2
23
+
24
+ def forward(self, x):
25
+ return x + self.cv2(self.cv1(x)) if self.add else self.cv2(self.cv1(x))
26
+
27
+
28
+ class Sum(nn.Module):
29
+ # Weighted sum of 2 or more layers https://arxiv.org/abs/1911.09070
30
+ def __init__(self, n, weight=False): # n: number of inputs
31
+ super().__init__()
32
+ self.weight = weight # apply weights boolean
33
+ self.iter = range(n - 1) # iter object
34
+ if weight:
35
+ self.w = nn.Parameter(-torch.arange(1., n) / 2, requires_grad=True) # layer weights
36
+
37
+ def forward(self, x):
38
+ y = x[0] # no weight
39
+ if self.weight:
40
+ w = torch.sigmoid(self.w) * 2
41
+ for i in self.iter:
42
+ y = y + x[i + 1] * w[i]
43
+ else:
44
+ for i in self.iter:
45
+ y = y + x[i + 1]
46
+ return y
47
+
48
+
49
+ class MixConv2d(nn.Module):
50
+ # Mixed Depth-wise Conv https://arxiv.org/abs/1907.09595
51
+ def __init__(self, c1, c2, k=(1, 3), s=1, equal_ch=True):
52
+ super().__init__()
53
+ groups = len(k)
54
+ if equal_ch: # equal c_ per group
55
+ i = torch.linspace(0, groups - 1E-6, c2).floor() # c2 indices
56
+ c_ = [(i == g).sum() for g in range(groups)] # intermediate channels
57
+ else: # equal weight.numel() per group
58
+ b = [c2] + [0] * groups
59
+ a = np.eye(groups + 1, groups, k=-1)
60
+ a -= np.roll(a, 1, axis=1)
61
+ a *= np.array(k) ** 2
62
+ a[0] = 1
63
+ c_ = np.linalg.lstsq(a, b, rcond=None)[0].round() # solve for equal weight indices, ax = b
64
+
65
+ self.m = nn.ModuleList([nn.Conv2d(c1, int(c_[g]), k[g], s, k[g] // 2, bias=False) for g in range(groups)])
66
+ self.bn = nn.BatchNorm2d(c2)
67
+ self.act = nn.LeakyReLU(0.1, inplace=True)
68
+
69
+ def forward(self, x):
70
+ return x + self.act(self.bn(torch.cat([m(x) for m in self.m], 1)))
71
+
72
+
73
+ class Ensemble(nn.ModuleList):
74
+ # Ensemble of models
75
+ def __init__(self):
76
+ super().__init__()
77
+
78
+ def forward(self, x, augment=False, profile=False, visualize=False):
79
+ y = []
80
+ for module in self:
81
+ y.append(module(x, augment, profile, visualize)[0])
82
+ # y = torch.stack(y).max(0)[0] # max ensemble
83
+ # y = torch.stack(y).mean(0) # mean ensemble
84
+ y = torch.cat(y, 1) # nms ensemble
85
+ return y, None # inference, train output
86
+
87
+
88
+ def attempt_load(weights, map_location=None, inplace=True, fuse=True):
89
+ from models.yolo import Detect, Model
90
+
91
+ # Loads an ensemble of models weights=[a,b,c] or a single model weights=[a] or weights=a
92
+ model = Ensemble()
93
+ for w in weights if isinstance(weights, list) else [weights]:
94
+ ckpt = torch.load(attempt_download(w), map_location=map_location) # load
95
+ if fuse:
96
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().fuse().eval()) # FP32 model
97
+ else:
98
+ model.append(ckpt['ema' if ckpt.get('ema') else 'model'].float().eval()) # without layer fuse
99
+
100
+
101
+ # Compatibility updates
102
+ for m in model.modules():
103
+ if type(m) in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6, nn.SiLU, Detect, Model]:
104
+ m.inplace = inplace # pytorch 1.7.0 compatibility
105
+ elif type(m) is Conv:
106
+ m._non_persistent_buffers_set = set() # pytorch 1.6.0 compatibility
107
+
108
+ if len(model) == 1:
109
+ return model[-1] # return model
110
+ else:
111
+ print(f'Ensemble created with {weights}\n')
112
+ for k in ['names']:
113
+ setattr(model, k, getattr(model[-1], k))
114
+ model.stride = model[torch.argmax(torch.tensor([m.stride.max() for m in model])).int()].stride # max stride
115
+ return model # return ensemble
models/yolo.py ADDED
@@ -0,0 +1,327 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ YOLO-specific modules
4
+
5
+ Usage:
6
+ $ python path/to/models/yolo.py --cfg yolov5s.yaml
7
+ """
8
+
9
+ import argparse
10
+ import sys
11
+ from copy import deepcopy
12
+ from pathlib import Path
13
+
14
+ FILE = Path(__file__).absolute()
15
+ sys.path.append(FILE.parents[1].as_posix()) # add yolov5/ to path
16
+
17
+ from models.common import *
18
+ from models.experimental import *
19
+ from utils.autoanchor import check_anchor_order
20
+ from utils.general import make_divisible, check_file, set_logging
21
+ from utils.plots import feature_visualization
22
+ from utils.torch_utils import time_sync, fuse_conv_and_bn, model_info, scale_img, initialize_weights, \
23
+ select_device, copy_attr
24
+
25
+ try:
26
+ import thop # for FLOPs computation
27
+ except ImportError:
28
+ thop = None
29
+
30
+ LOGGER = logging.getLogger(__name__)
31
+
32
+
33
+ class Detect(nn.Module):
34
+ stride = None # strides computed during build
35
+ onnx_dynamic = False # ONNX export parameter
36
+
37
+ def __init__(self, nc=80, anchors=(), ch=(), inplace=True, num_coords=0): # detection layer
38
+ super().__init__()
39
+ self.nc = nc # number of classes
40
+ self.no = nc + 5 # number of outputs per anchor
41
+ self.nl = len(anchors) # number of detection layers
42
+ self.na = len(anchors[0]) // 2 # number of anchors
43
+ self.grid = [torch.zeros(1)] * self.nl # init grid
44
+ a = torch.tensor(anchors).float().view(self.nl, -1, 2)
45
+ self.register_buffer('anchors', a) # shape(nl,na,2)
46
+ self.register_buffer('anchor_grid', a.clone().view(self.nl, 1, -1, 1, 1, 2)) # shape(nl,1,na,1,1,2)
47
+ self.m = nn.ModuleList(nn.Conv2d(x, self.no * self.na, 1) for x in ch) # output conv
48
+ self.inplace = inplace # use in-place ops (e.g. slice assignment)
49
+ self.num_coords = num_coords
50
+
51
+ def forward(self, x):
52
+ z = [] # inference output
53
+ for i in range(self.nl):
54
+ x[i] = self.m[i](x[i]) # conv
55
+ bs, _, ny, nx = x[i].shape # x(bs,255,20,20) to x(bs,3,20,20,85)
56
+ x[i] = x[i].view(bs, self.na, self.no, ny, nx).permute(0, 1, 3, 4, 2).contiguous()
57
+
58
+ if not self.training: # inference
59
+ if self.grid[i].shape[2:4] != x[i].shape[2:4] or self.onnx_dynamic:
60
+ self.grid[i] = self._make_grid(nx, ny).to(x[i].device)
61
+
62
+ y = x[i].sigmoid()
63
+ if self.inplace:
64
+ y[..., 0:2] = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
65
+ y[..., 2:4] = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i] # wh
66
+
67
+ if hasattr(self, 'num_coords') and self.num_coords:
68
+ y[..., -self.num_coords:] = y[..., -self.num_coords:] * 4. - 2.
69
+ y[..., -self.num_coords:] *= self.anchor_grid[i].repeat((1, 1, 1, 1, self.num_coords // 2))
70
+ y[..., -self.num_coords:] += (self.grid[i] * self.stride[i]).repeat((1, 1, 1, 1, self.num_coords // 2))
71
+
72
+ else: # for YOLOv5 on AWS Inferentia https://github.com/ultralytics/yolov5/pull/2953
73
+ xy = (y[..., 0:2] * 2. - 0.5 + self.grid[i]) * self.stride[i] # xy
74
+ wh = (y[..., 2:4] * 2) ** 2 * self.anchor_grid[i].view(1, self.na, 1, 1, 2) # wh
75
+ y = torch.cat((xy, wh, y[..., 4:]), -1)
76
+ z.append(y.view(bs, -1, self.no))
77
+ # z.append(y)
78
+
79
+ return x if self.training else (torch.cat(z, 1), x)
80
+ # return x if self.training else (z, x)
81
+
82
+ @staticmethod
83
+ def _make_grid(nx=20, ny=20):
84
+ yv, xv = torch.meshgrid([torch.arange(ny), torch.arange(nx)])
85
+ return torch.stack((xv, yv), 2).view((1, 1, ny, nx, 2)).float()
86
+
87
+
88
+ class Model(nn.Module):
89
+ def __init__(self, cfg='yolov5s.yaml', ch=3, nc=None, anchors=None, num_coords=0, autobalance=False): # model, input channels, number of classes
90
+ super().__init__()
91
+ if isinstance(cfg, dict):
92
+ self.yaml = cfg # model dict
93
+ else: # is *.yaml
94
+ import yaml # for torch hub
95
+ self.yaml_file = Path(cfg).name
96
+ with open(cfg) as f:
97
+ self.yaml = yaml.safe_load(f) # model dict
98
+
99
+ # Define model
100
+ ch = self.yaml['ch'] = self.yaml.get('ch', ch) # input channels
101
+ if nc + num_coords and nc + num_coords != self.yaml['nc']:
102
+ LOGGER.info(f"Overriding model.yaml nc={self.yaml['nc']} with nc={nc + num_coords}")
103
+ self.yaml['nc'] = nc + num_coords # override yaml value
104
+ if anchors:
105
+ LOGGER.info(f'Overriding model.yaml anchors with anchors={anchors}')
106
+ self.yaml['anchors'] = round(anchors) # override yaml value
107
+ self.model, self.save = parse_model(deepcopy(self.yaml), ch=[ch]) # model, savelist
108
+ self.names = [str(i) for i in range(self.yaml['nc'])] # default names
109
+ self.inplace = self.yaml.get('inplace', True)
110
+ self.num_coords = num_coords
111
+ if autobalance:
112
+ self.loss_coeffs = nn.Parameter(torch.zeros(2))
113
+ # LOGGER.info([x.shape for x in self.forward(torch.zeros(1, ch, 64, 64))])
114
+
115
+ # Build strides, anchors
116
+ m = self.model[-1] # Detect()
117
+ if isinstance(m, Detect):
118
+ s = 256 # 2x min stride
119
+ m.inplace = self.inplace
120
+ m.stride = torch.tensor([s / x.shape[-2] for x in self.forward(torch.zeros(1, ch, s, s))]) # forward
121
+ m.anchors /= m.stride.view(-1, 1, 1)
122
+ check_anchor_order(m)
123
+ self.stride = m.stride
124
+ m.num_coords = self.num_coords
125
+ m.nc = nc
126
+ self._initialize_biases() # only run once
127
+ # LOGGER.info('Strides: %s' % m.stride.tolist())
128
+
129
+ # Init weights, biases
130
+ initialize_weights(self)
131
+ self.info()
132
+ LOGGER.info('')
133
+
134
+ def forward(self, x, augment=False, profile=False, visualize=False, kp_flip=None,
135
+ scales=[0.5, 1, 2], flips=[None, 3, None]):
136
+ if augment:
137
+ return self.forward_augment(x, kp_flip, s=scales, f=flips) # augmented inference, None
138
+ return self.forward_once(x, profile, visualize) # single-scale inference, train
139
+
140
+ def forward_augment(self, x, kp_flip, s=[0.5, 1, 2], f=[None, 3, None]):
141
+ img_size = x.shape[-2:] # height, width
142
+ # s = [1, 0.83, 0.67] # scales
143
+ # f = [None, 3, None] # flips (2-ud, 3-lr)
144
+ y = [] # outputs
145
+ train_out = None
146
+ for si, fi in zip(s, f):
147
+ xi = scale_img(x.flip(fi) if fi else x, si, gs=int(self.stride.max()))
148
+ yi, train_out_i = self.forward_once(xi) # forward
149
+ if si == 1 and fi is None:
150
+ train_out = train_out_i
151
+ # cv2.imwrite(f'img_{si}.jpg', 255 * xi[0].cpu().numpy().transpose((1, 2, 0))[:, :, ::-1]) # save
152
+ yi = self._descale_pred(yi, fi, si, img_size, kp_flip)
153
+ y.append(yi)
154
+ return torch.cat(y, 1), train_out # augmented inference, train
155
+
156
+ def forward_once(self, x, profile=False, visualize=False):
157
+ y, dt = [], [] # outputs
158
+ for m in self.model:
159
+ if m.f != -1: # if not from previous layer
160
+ x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in m.f] # from earlier layers
161
+
162
+ if profile:
163
+ c = isinstance(m, Detect) # copy input as inplace fix
164
+ o = thop.profile(m, inputs=(x.copy() if c else x,), verbose=False)[0] / 1E9 * 2 if thop else 0 # FLOPs
165
+ t = time_sync()
166
+ for _ in range(10):
167
+ m(x.copy() if c else x)
168
+ dt.append((time_sync() - t) * 100)
169
+ if m == self.model[0]:
170
+ LOGGER.info(f"{'time (ms)':>10s} {'GFLOPs':>10s} {'params':>10s} {'module'}")
171
+ LOGGER.info(f'{dt[-1]:10.2f} {o:10.2f} {m.np:10.0f} {m.type}')
172
+
173
+ x = m(x) # run
174
+ y.append(x if m.i in self.save else None) # save output
175
+
176
+ if visualize:
177
+ feature_visualization(x, m.type, m.i, save_dir=visualize)
178
+
179
+ if profile:
180
+ LOGGER.info('%.1fms total' % sum(dt))
181
+ return x
182
+
183
+ def _descale_pred(self, p, flips, scale, img_size, kp_flip):
184
+ # de-scale predictions following augmented inference (inverse operation)
185
+ if self.inplace:
186
+ p[..., :4] /= scale # de-scale bbox
187
+ if kp_flip:
188
+ p[..., -self.num_coords:] /= scale # de-scale kp
189
+ if flips == 2:
190
+ p[..., 1] = img_size[0] - p[..., 1] # de-flip ud
191
+ elif flips == 3:
192
+ p[..., 0] = img_size[1] - p[..., 0] # de-flip lr
193
+ if kp_flip:
194
+ p[..., 6:6 + self.nc - 1] = p[..., 6:6 + self.nc - 1][..., kp_flip] # de-flip bbox conf
195
+ p[..., -self.num_coords::2] = img_size[1] - p[..., -self.num_coords::2] # de-flip kp x
196
+ p[..., -self.num_coords::2] = p[..., -self.num_coords::2][..., kp_flip] # swap lr kp (x)
197
+ p[..., -self.num_coords + 1::2] = p[..., -self.num_coords + 1::2][..., kp_flip] # swap lr kp (y)
198
+
199
+ else:
200
+ x, y, wh = p[..., 0:1] / scale, p[..., 1:2] / scale, p[..., 2:4] / scale # de-scale
201
+ if flips == 2:
202
+ y = img_size[0] - y # de-flip ud
203
+ elif flips == 3:
204
+ x = img_size[1] - x # de-flip lr
205
+ p = torch.cat((x, y, wh, p[..., 4:]), -1)
206
+ return p
207
+
208
+ def _initialize_biases(self, cf=None): # initialize biases into Detect(), cf is class frequency
209
+ # https://arxiv.org/abs/1708.02002 section 3.3
210
+ # cf = torch.bincount(torch.tensor(np.concatenate(dataset.labels, 0)[:, 0]).long(), minlength=nc) + 1.
211
+ m = self.model[-1] # Detect() module
212
+ for mi, s in zip(m.m, m.stride): # from
213
+ b = mi.bias.view(m.na, -1) # conv.bias(255) to (3,85)
214
+ b.data[:, 4] += math.log(8 / (640 / s) ** 2) # obj (8 objects per 640 image)
215
+ b.data[:, 5:5+m.nc] += math.log(0.6 / (m.nc - 0.99)) if cf is None else torch.log(cf / cf.sum()) # cls
216
+ mi.bias = torch.nn.Parameter(b.view(-1), requires_grad=True)
217
+
218
+ def _print_biases(self):
219
+ m = self.model[-1] # Detect() module
220
+ for mi in m.m: # from
221
+ b = mi.bias.detach().view(m.na, -1).T # conv.bias(255) to (3,85)
222
+ LOGGER.info(
223
+ ('%6g Conv2d.bias:' + '%10.3g' * 6) % (mi.weight.shape[1], *b[:5].mean(1).tolist(), b[5:].mean()))
224
+
225
+ # def _print_weights(self):
226
+ # for m in self.model.modules():
227
+ # if type(m) is Bottleneck:
228
+ # LOGGER.info('%10.3g' % (m.w.detach().sigmoid() * 2)) # shortcut weights
229
+
230
+ def fuse(self): # fuse model Conv2d() + BatchNorm2d() layers
231
+ LOGGER.info('Fusing layers... ')
232
+ for m in self.model.modules():
233
+ if isinstance(m, (Conv, DWConv)) and hasattr(m, 'bn'):
234
+ m.conv = fuse_conv_and_bn(m.conv, m.bn) # update conv
235
+ delattr(m, 'bn') # remove batchnorm
236
+ m.forward = m.forward_fuse # update forward
237
+ self.info()
238
+ return self
239
+
240
+ def autoshape(self): # add AutoShape module
241
+ LOGGER.info('Adding AutoShape... ')
242
+ m = AutoShape(self) # wrap model
243
+ copy_attr(m, self, include=('yaml', 'nc', 'hyp', 'names', 'stride'), exclude=()) # copy attributes
244
+ return m
245
+
246
+ def info(self, verbose=False, img_size=640): # print model information
247
+ model_info(self, verbose, img_size)
248
+
249
+
250
+ def parse_model(d, ch): # model_dict, input_channels(3)
251
+ LOGGER.info('\n%3s%18s%3s%10s %-40s%-30s' % ('', 'from', 'n', 'params', 'module', 'arguments'))
252
+ anchors, nc, gd, gw = d['anchors'], d['nc'], d['depth_multiple'], d['width_multiple']
253
+ na = (len(anchors[0]) // 2) if isinstance(anchors, list) else anchors # number of anchors
254
+ no = na * (nc + 5) # number of outputs = anchors * (classes + 5)
255
+
256
+ layers, save, c2 = [], [], ch[-1] # layers, savelist, ch out
257
+ for i, (f, n, m, args) in enumerate(d['backbone'] + d['head']): # from, number, module, args
258
+ m = eval(m) if isinstance(m, str) else m # eval strings
259
+ for j, a in enumerate(args):
260
+ try:
261
+ args[j] = eval(a) if isinstance(a, str) else a # eval strings
262
+ except:
263
+ pass
264
+
265
+ n = n_ = max(round(n * gd), 1) if n > 1 else n # depth gain
266
+ if m in [Conv, GhostConv, Bottleneck, GhostBottleneck, SPP, SPPF, DWConv, MixConv2d, Focus, CrossConv,
267
+ BottleneckCSP, C3, C3TR, C3SPP, C3Ghost]:
268
+ c1, c2 = ch[f], args[0]
269
+ if c2 != no: # if not output
270
+ c2 = make_divisible(c2 * gw, 8)
271
+
272
+ args = [c1, c2, *args[1:]]
273
+ if m in [BottleneckCSP, C3, C3TR, C3Ghost]:
274
+ args.insert(2, n) # number of repeats
275
+ n = 1
276
+ elif m is nn.BatchNorm2d:
277
+ args = [ch[f]]
278
+ elif m is Concat:
279
+ c2 = sum([ch[x] for x in f])
280
+ elif m is Detect:
281
+ args.append([ch[x] for x in f])
282
+ if isinstance(args[1], int): # number of anchors
283
+ args[1] = [list(range(args[1] * 2))] * len(f)
284
+ elif m is Contract:
285
+ c2 = ch[f] * args[0] ** 2
286
+ elif m is Expand:
287
+ c2 = ch[f] // args[0] ** 2
288
+ else:
289
+ c2 = ch[f]
290
+
291
+ m_ = nn.Sequential(*[m(*args) for _ in range(n)]) if n > 1 else m(*args) # module
292
+ t = str(m)[8:-2].replace('__main__.', '') # module type
293
+ np = sum([x.numel() for x in m_.parameters()]) # number params
294
+ m_.i, m_.f, m_.type, m_.np = i, f, t, np # attach index, 'from' index, type, number params
295
+ LOGGER.info('%3s%18s%3s%10.0f %-40s%-30s' % (i, f, n_, np, t, args)) # print
296
+ save.extend(x % i for x in ([f] if isinstance(f, int) else f) if x != -1) # append to savelist
297
+ layers.append(m_)
298
+ if i == 0:
299
+ ch = []
300
+ ch.append(c2)
301
+ return nn.Sequential(*layers), sorted(save)
302
+
303
+
304
+ if __name__ == '__main__':
305
+ parser = argparse.ArgumentParser()
306
+ parser.add_argument('--cfg', type=str, default='yolov5s.yaml', help='model.yaml')
307
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
308
+ parser.add_argument('--profile', action='store_true', help='profile model speed')
309
+ opt = parser.parse_args()
310
+ opt.cfg = check_file(opt.cfg) # check file
311
+ set_logging()
312
+ device = select_device(opt.device)
313
+
314
+ # Create model
315
+ model = Model(opt.cfg).to(device)
316
+ model.train()
317
+
318
+ # Profile
319
+ if opt.profile:
320
+ img = torch.rand(8 if torch.cuda.is_available() else 1, 3, 640, 640).to(device)
321
+ y = model(img, profile=True)
322
+
323
+ # Tensorboard (not working https://github.com/ultralytics/yolov5/issues/2898)
324
+ # from torch.utils.tensorboard import SummaryWriter
325
+ # tb_writer = SummaryWriter('.')
326
+ # LOGGER.info("Run 'tensorboard --logdir=models' to view tensorboard at http://localhost:6006/")
327
+ # tb_writer.add_graph(torch.jit.trace(model, img, strict=False), []) # add model graph
models/yolov5l6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 1.0 # model depth multiple
6
+ width_multiple: 1.0 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 9, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 1, SPP, [1024, [3, 5, 7]]],
27
+ [-1, 3, C3, [1024, False]], # 11
28
+ ]
29
+
30
+ # YOLOv5 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/yolov5m6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.67 # model depth multiple
6
+ width_multiple: 0.75 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 9, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 1, SPP, [1024, [3, 5, 7]]],
27
+ [-1, 3, C3, [1024, False]], # 11
28
+ ]
29
+
30
+ # YOLOv5 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
models/yolov5s6.yaml ADDED
@@ -0,0 +1,60 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+
3
+ # Parameters
4
+ nc: 80 # number of classes
5
+ depth_multiple: 0.33 # model depth multiple
6
+ width_multiple: 0.50 # layer channel multiple
7
+ anchors:
8
+ - [19,27, 44,40, 38,94] # P3/8
9
+ - [96,68, 86,152, 180,137] # P4/16
10
+ - [140,301, 303,264, 238,542] # P5/32
11
+ - [436,615, 739,380, 925,792] # P6/64
12
+
13
+ # YOLOv5 backbone
14
+ backbone:
15
+ # [from, number, module, args]
16
+ [[-1, 1, Focus, [64, 3]], # 0-P1/2
17
+ [-1, 1, Conv, [128, 3, 2]], # 1-P2/4
18
+ [-1, 3, C3, [128]],
19
+ [-1, 1, Conv, [256, 3, 2]], # 3-P3/8
20
+ [-1, 9, C3, [256]],
21
+ [-1, 1, Conv, [512, 3, 2]], # 5-P4/16
22
+ [-1, 9, C3, [512]],
23
+ [-1, 1, Conv, [768, 3, 2]], # 7-P5/32
24
+ [-1, 3, C3, [768]],
25
+ [-1, 1, Conv, [1024, 3, 2]], # 9-P6/64
26
+ [-1, 1, SPP, [1024, [3, 5, 7]]],
27
+ [-1, 3, C3, [1024, False]], # 11
28
+ ]
29
+
30
+ # YOLOv5 head
31
+ head:
32
+ [[-1, 1, Conv, [768, 1, 1]],
33
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
34
+ [[-1, 8], 1, Concat, [1]], # cat backbone P5
35
+ [-1, 3, C3, [768, False]], # 15
36
+
37
+ [-1, 1, Conv, [512, 1, 1]],
38
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
39
+ [[-1, 6], 1, Concat, [1]], # cat backbone P4
40
+ [-1, 3, C3, [512, False]], # 19
41
+
42
+ [-1, 1, Conv, [256, 1, 1]],
43
+ [-1, 1, nn.Upsample, [None, 2, 'nearest']],
44
+ [[-1, 4], 1, Concat, [1]], # cat backbone P3
45
+ [-1, 3, C3, [256, False]], # 23 (P3/8-small)
46
+
47
+ [-1, 1, Conv, [256, 3, 2]],
48
+ [[-1, 20], 1, Concat, [1]], # cat head P4
49
+ [-1, 3, C3, [512, False]], # 26 (P4/16-medium)
50
+
51
+ [-1, 1, Conv, [512, 3, 2]],
52
+ [[-1, 16], 1, Concat, [1]], # cat head P5
53
+ [-1, 3, C3, [768, False]], # 29 (P5/32-large)
54
+
55
+ [-1, 1, Conv, [768, 3, 2]],
56
+ [[-1, 12], 1, Concat, [1]], # cat head P6
57
+ [-1, 3, C3, [1024, False]], # 32 (P6/64-xlarge)
58
+
59
+ [[23, 26, 29, 32], 1, Detect, [nc, anchors]], # Detect(P3, P4, P5, P6)
60
+ ]
train.py ADDED
@@ -0,0 +1,601 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import logging
3
+ import math
4
+ import os
5
+ import random
6
+ import sys
7
+ import time
8
+ from copy import deepcopy
9
+ from pathlib import Path
10
+
11
+ import numpy as np
12
+ import torch
13
+ import torch.distributed as dist
14
+ import torch.nn as nn
15
+ import yaml
16
+ from torch.cuda import amp
17
+ from torch.nn.parallel import DistributedDataParallel as DDP
18
+ from torch.optim import Adam, SGD, lr_scheduler
19
+ from tqdm import tqdm
20
+
21
+ FILE = Path(__file__).absolute()
22
+ sys.path.append(FILE.parents[0].as_posix()) # add yolov5/ to path
23
+
24
+ import val
25
+ from models.yolo import Model
26
+ from utils.autoanchor import check_anchors
27
+ from utils.datasets import create_dataloader
28
+ from utils.general import labels_to_class_weights, increment_path, labels_to_image_weights, init_seeds, \
29
+ strip_optimizer, get_latest_run, check_dataset, check_file, check_img_size, \
30
+ print_mutation, set_logging, one_cycle, colorstr, methods
31
+ from utils.downloads import attempt_download
32
+ from utils.loss import ComputeLoss
33
+ from utils.plots import plot_labels, plot_evolve
34
+ from utils.torch_utils import EarlyStopping, ModelEMA, de_parallel, intersect_dicts, select_device, \
35
+ torch_distributed_zero_first
36
+ from utils.metrics import fitness
37
+ from utils.loggers import Loggers
38
+ from utils.callbacks import Callbacks
39
+
40
+ LOGGER = logging.getLogger(__name__)
41
+ LOCAL_RANK = int(os.getenv('LOCAL_RANK', -1)) # https://pytorch.org/docs/stable/elastic/run.html
42
+ RANK = int(os.getenv('RANK', -1))
43
+ WORLD_SIZE = int(os.getenv('WORLD_SIZE', 1))
44
+
45
+
46
+ def train(hyp, # path/to/hyp.yaml or hyp dictionary
47
+ opt,
48
+ device,
49
+ callbacks=Callbacks()
50
+ ):
51
+ save_dir, epochs, batch_size, weights, single_cls, evolve, data, cfg, resume, noval, nosave, workers, freeze, \
52
+ val_scales, val_flips = \
53
+ Path(opt.save_dir), opt.epochs, opt.batch_size, opt.weights, opt.single_cls, opt.evolve, opt.data, opt.cfg, \
54
+ opt.resume, opt.noval, opt.nosave, opt.workers, opt.freeze, opt.val_scales, opt.val_flips
55
+
56
+ val_flips = [None if f == -1 else f for f in val_flips]
57
+
58
+ # Directories
59
+ w = save_dir / 'weights' # weights dir
60
+ w.mkdir(parents=True, exist_ok=True) # make dir
61
+ last, best = w / 'last.pt', w / 'best.pt'
62
+
63
+ # Hyperparameters
64
+ if isinstance(hyp, str):
65
+ with open(hyp) as f:
66
+ hyp = yaml.safe_load(f) # load hyps dict
67
+ LOGGER.info(colorstr('hyperparameters: ') + ', '.join(f'{k}={v}' for k, v in hyp.items()))
68
+
69
+ # Save run settings
70
+ with open(save_dir / 'hyp.yaml', 'w') as f:
71
+ yaml.safe_dump(hyp, f, sort_keys=False)
72
+ with open(save_dir / 'opt.yaml', 'w') as f:
73
+ yaml.safe_dump(vars(opt), f, sort_keys=False)
74
+ data_dict = None
75
+
76
+ # Loggers
77
+ if RANK in [-1, 0]:
78
+ loggers = Loggers(save_dir, weights, opt, hyp, LOGGER) # loggers instance
79
+ if loggers.wandb:
80
+ data_dict = loggers.wandb.data_dict
81
+ if resume:
82
+ weights, epochs, hyp = opt.weights, opt.epochs, opt.hyp
83
+
84
+ # Register actions
85
+ for k in methods(loggers):
86
+ callbacks.register_action(k, callback=getattr(loggers, k))
87
+
88
+ # Config
89
+ plots = not evolve # create plots
90
+ cuda = device.type != 'cpu'
91
+ init_seeds(1 + RANK)
92
+ with torch_distributed_zero_first(RANK):
93
+ data_dict = data_dict or check_dataset(data) # check if None
94
+ train_path, val_path = data_dict['train'], data_dict['val']
95
+ nc = 1 if single_cls else int(data_dict['nc']) # number of classes
96
+ names = ['item'] if single_cls and len(data_dict['names']) != 1 else data_dict['names'] # class names
97
+ assert len(names) == nc, f'{len(names)} names found for nc={nc} dataset in {data}' # check
98
+ is_coco = data.endswith('coco.yaml') and nc == 80 # COCO dataset
99
+
100
+ labels_dir = data_dict.get('labels', 'labels')
101
+ kp_flip = data_dict.get('kp_flip')
102
+ kp_bbox = data_dict.get('kp_bbox')
103
+ num_coords = data_dict.get('num_coords', 0)
104
+
105
+ # Model
106
+ pretrained = weights.endswith('.pt')
107
+ if pretrained:
108
+ with torch_distributed_zero_first(RANK):
109
+ weights = attempt_download(weights) # download if not found locally
110
+ ckpt = torch.load(weights, map_location=device) # load checkpoint
111
+ model = Model(cfg or ckpt['model'].yaml, ch=3, nc=nc, anchors=hyp.get('anchors'), num_coords=num_coords).to(device) # create
112
+ exclude = ['anchor'] if (cfg or hyp.get('anchors')) and not resume else [] # exclude keys
113
+ csd = ckpt['model'].float().state_dict() # checkpoint state_dict as FP32
114
+ csd = intersect_dicts(csd, model.state_dict(), exclude=exclude) # intersect
115
+ model.load_state_dict(csd, strict=False) # load
116
+ LOGGER.info(f'Transferred {len(csd)}/{len(model.state_dict())} items from {weights}') # report
117
+ else:
118
+ model = Model(cfg, ch=3, nc=nc, anchors=hyp.get('anchors'), num_coords=num_coords).to(device) # create
119
+
120
+ # Freeze
121
+ freeze = [f'model.{x}.' for x in range(freeze)] # layers to freeze
122
+ for k, v in model.named_parameters():
123
+ v.requires_grad = True # train all layers
124
+ if any(x in k for x in freeze):
125
+ print(f'freezing {k}')
126
+ v.requires_grad = False
127
+
128
+ # Optimizer
129
+ nbs = 64 # nominal batch size
130
+ accumulate = max(round(nbs / batch_size), 1) # accumulate loss before optimizing
131
+ hyp['weight_decay'] *= batch_size * accumulate / nbs # scale weight_decay
132
+ LOGGER.info(f"Scaled weight_decay = {hyp['weight_decay']}")
133
+
134
+ g0, g1, g2 = [], [], [] # optimizer parameter groups
135
+ for v in model.modules():
136
+ if hasattr(v, 'bias') and isinstance(v.bias, nn.Parameter): # bias
137
+ g2.append(v.bias)
138
+ if isinstance(v, nn.BatchNorm2d): # weight (no decay)
139
+ g0.append(v.weight)
140
+ elif hasattr(v, 'weight') and isinstance(v.weight, nn.Parameter): # weight (with decay)
141
+ g1.append(v.weight)
142
+
143
+ if opt.adam:
144
+ optimizer = Adam(g0, lr=hyp['lr0'], betas=(hyp['momentum'], 0.999)) # adjust beta1 to momentum
145
+ else:
146
+ optimizer = SGD(g0, lr=hyp['lr0'], momentum=hyp['momentum'], nesterov=True)
147
+
148
+ optimizer.add_param_group({'params': g1, 'weight_decay': hyp['weight_decay']}) # add g1 with weight_decay
149
+ optimizer.add_param_group({'params': g2}) # add g2 (biases)
150
+ # if opt.autobalance:
151
+ # optimizer.add_param_group({'params': model.loss_coeffs}) # for autobalancing if used
152
+
153
+ LOGGER.info(f"{colorstr('optimizer:')} {type(optimizer).__name__} with parameter groups "
154
+ f"{len(g0)} weight, {len(g1)} weight (no decay), {len(g2)} bias")
155
+ del g0, g1, g2
156
+
157
+ # Scheduler
158
+ if opt.linear_lr:
159
+ lf = lambda x: (1 - x / (epochs - 1)) * (1.0 - hyp['lrf']) + hyp['lrf'] # linear
160
+ else:
161
+ lf = one_cycle(1, hyp['lrf'], epochs) # cosine 1->hyp['lrf']
162
+ scheduler = lr_scheduler.LambdaLR(optimizer, lr_lambda=lf) # plot_lr_scheduler(optimizer, scheduler, epochs)
163
+
164
+ # EMA
165
+ ema = ModelEMA(model) if RANK in [-1, 0] else None
166
+
167
+ # Resume
168
+ start_epoch, best_fitness = 0, 0.0
169
+ if pretrained:
170
+ # Optimizer
171
+ if ckpt['optimizer'] is not None:
172
+ optimizer.load_state_dict(ckpt['optimizer'])
173
+ best_fitness = ckpt['best_fitness']
174
+
175
+ # EMA
176
+ if ema and ckpt.get('ema'):
177
+ ema.ema.load_state_dict(ckpt['ema'].float().state_dict())
178
+ ema.updates = ckpt['updates']
179
+
180
+ # Epochs
181
+ start_epoch = ckpt['epoch'] + 1
182
+ if resume:
183
+ assert start_epoch > 0, f'{weights} training to {epochs} epochs is finished, nothing to resume.'
184
+ if epochs < start_epoch:
185
+ LOGGER.info(f"{weights} has been trained for {ckpt['epoch']} epochs. Fine-tuning for {epochs} more epochs.")
186
+ epochs += ckpt['epoch'] # finetune additional epochs
187
+
188
+ del ckpt, csd
189
+
190
+ # Image sizes
191
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
192
+ nl = model.model[-1].nl # number of detection layers (used for scaling hyp['obj'])
193
+ imgsz = check_img_size(opt.imgsz, gs, floor=gs * 2) # verify imgsz is gs-multiple
194
+
195
+ # DP mode
196
+ if cuda and RANK == -1 and torch.cuda.device_count() > 1:
197
+ logging.warning('DP not recommended, instead use torch.distributed.run for best DDP Multi-GPU results.\n'
198
+ 'See Multi-GPU Tutorial at https://github.com/ultralytics/yolov5/issues/475 to get started.')
199
+ model = torch.nn.DataParallel(model)
200
+
201
+ # SyncBatchNorm
202
+ if opt.sync_bn and cuda and RANK != -1:
203
+ model = torch.nn.SyncBatchNorm.convert_sync_batchnorm(model).to(device)
204
+ LOGGER.info('Using SyncBatchNorm()')
205
+
206
+ # Trainloader
207
+ train_loader, dataset = create_dataloader(train_path, labels_dir, imgsz, batch_size // WORLD_SIZE, gs, single_cls,
208
+ hyp=hyp, augment=True, cache=opt.cache, rect=opt.rect, rank=RANK,
209
+ workers=workers, image_weights=opt.image_weights, quad=opt.quad,
210
+ prefix=colorstr('train: '), kp_flip=kp_flip, kp_bbox=kp_bbox)
211
+ mlc = int(np.concatenate(dataset.labels, 0)[:, 0].max()) # max label class
212
+ nb = len(train_loader) # number of batches
213
+ assert mlc < nc, f'Label class {mlc} exceeds nc={nc} in {data}. Possible class labels are 0-{nc - 1}'
214
+
215
+ # Process 0
216
+ if RANK in [-1, 0]:
217
+ val_loader = create_dataloader(val_path, labels_dir, imgsz, batch_size // WORLD_SIZE, gs, single_cls,
218
+ hyp=hyp, cache=None if noval else opt.cache, rect=False, rank=-1,
219
+ workers=workers, pad=0.5,
220
+ prefix=colorstr('val: '), kp_flip=kp_flip, kp_bbox=kp_bbox)[0]
221
+
222
+ if not resume:
223
+ # labels = np.concatenate(dataset.labels, 0)
224
+ # c = torch.tensor(labels[:, 0]) # classes
225
+ # cf = torch.bincount(c.long(), minlength=nc) + 1. # frequency
226
+ # model._initialize_biases(cf.to(device))
227
+ # if plots:
228
+ # plot_labels(labels, names, save_dir)
229
+
230
+ # Anchors
231
+ if not opt.noautoanchor:
232
+ check_anchors(dataset, model=model, thr=hyp['anchor_t'], imgsz=imgsz)
233
+ model.half().float() # pre-reduce anchor precision
234
+
235
+ callbacks.on_pretrain_routine_end()
236
+
237
+ # DDP mode
238
+ if cuda and RANK != -1:
239
+ model = DDP(model, device_ids=[LOCAL_RANK], output_device=LOCAL_RANK)
240
+
241
+ # Model parameters
242
+ hyp['box'] *= 3. / nl # scale to layers
243
+ hyp['cls'] *= nc / 80. * 3. / nl # scale to classes and layers
244
+ hyp['obj'] *= (imgsz / 640) ** 2 * 3. / nl # scale to image size and layers
245
+ hyp['kp'] *= 3. / nl
246
+ hyp['label_smoothing'] = opt.label_smoothing
247
+ model.nc = nc # attach number of classes to model
248
+ model.hyp = hyp # attach hyperparameters to model
249
+ model.class_weights = labels_to_class_weights(dataset.labels, nc).to(device) * nc # attach class weights
250
+ model.names = names
251
+
252
+ # Start training
253
+ t0 = time.time()
254
+ nw = max(round(hyp['warmup_epochs'] * nb), 1000) # number of warmup iterations, max(3 epochs, 1k iterations)
255
+ # nw = min(nw, (epochs - start_epoch) / 2 * nb) # limit warmup to < 1/2 of training
256
+ last_opt_step = -1
257
+ maps = np.zeros(nc) # mAP per class
258
+ results = (0, 0, 0, 0, 0, 0, 0, 0) # P, R, mAP@.5, mAP@.5-.95, val_loss(box, obj, cls, kp)
259
+ scheduler.last_epoch = start_epoch - 1 # do not move
260
+ scaler = amp.GradScaler(enabled=cuda)
261
+ stopper = EarlyStopping(patience=opt.patience)
262
+ compute_loss = ComputeLoss(model, autobalance=False, num_coords=num_coords) # init loss class
263
+ LOGGER.info(f'Image sizes {imgsz} train, {imgsz} val\n'
264
+ f'Using {train_loader.num_workers} dataloader workers\n'
265
+ f"Logging results to {colorstr('bold', save_dir)}\n"
266
+ f'Starting training for {epochs} epochs...')
267
+
268
+ for epoch in range(start_epoch, epochs): # epoch ------------------------------------------------------------------
269
+ model.train()
270
+
271
+ # Update image weights (optional, single-GPU only)
272
+ if opt.image_weights:
273
+ cw = model.class_weights.cpu().numpy() * (1 - maps) ** 2 / nc # class weights
274
+ iw = labels_to_image_weights(dataset.labels, nc=nc, class_weights=cw) # image weights
275
+ dataset.indices = random.choices(range(dataset.n), weights=iw, k=dataset.n) # rand weighted idx
276
+
277
+ # Update mosaic border (optional)
278
+ # b = int(random.uniform(0.25 * imgsz, 0.75 * imgsz + gs) // gs * gs)
279
+ # dataset.mosaic_border = [b - imgsz, -b] # height, width borders
280
+
281
+ mloss = torch.zeros(4, device=device) # mean losses
282
+ if RANK != -1:
283
+ train_loader.sampler.set_epoch(epoch)
284
+ pbar = enumerate(train_loader)
285
+ LOGGER.info(('\n' + '%10s' * 8) % ('Epoch', 'gpu_mem', 'box', 'obj', 'cls', 'kps', 'labels', 'img_size'))
286
+ if RANK in [-1, 0]:
287
+ pbar = tqdm(pbar, total=nb) # progress bar
288
+ optimizer.zero_grad()
289
+ for i, (imgs, targets, paths, _) in pbar: # batch -------------------------------------------------------------
290
+ ni = i + nb * epoch # number integrated batches (since train start)
291
+ imgs = imgs.to(device, non_blocking=True).float() / 255.0 # uint8 to float32, 0-255 to 0.0-1.0
292
+
293
+ # Warmup
294
+ if ni <= nw:
295
+ xi = [0, nw] # x interp
296
+ # compute_loss.gr = np.interp(ni, xi, [0.0, 1.0]) # iou loss ratio (obj_loss = 1.0 or iou)
297
+ accumulate = max(1, np.interp(ni, xi, [1, nbs / batch_size]).round())
298
+ for j, x in enumerate(optimizer.param_groups):
299
+ # bias lr falls from 0.1 to lr0, all other lrs rise from 0.0 to lr0
300
+ x['lr'] = np.interp(ni, xi, [hyp['warmup_bias_lr'] if j == 2 else 0.0, x['initial_lr'] * lf(epoch)])
301
+ if 'momentum' in x:
302
+ x['momentum'] = np.interp(ni, xi, [hyp['warmup_momentum'], hyp['momentum']])
303
+
304
+ # Multi-scale
305
+ if opt.multi_scale:
306
+ sz = random.randrange(imgsz * 0.5, imgsz * 1.5 + gs) // gs * gs # size
307
+ sf = sz / max(imgs.shape[2:]) # scale factor
308
+ if sf != 1:
309
+ ns = [math.ceil(x * sf / gs) * gs for x in imgs.shape[2:]] # new shape (stretched to gs-multiple)
310
+ imgs = nn.functional.interpolate(imgs, size=ns, mode='bilinear', align_corners=False)
311
+
312
+ # Forward
313
+ with amp.autocast(enabled=cuda):
314
+ pred = model(imgs) # forward
315
+ loss, loss_items = compute_loss(pred, targets.to(device)) # loss scaled by batch_size
316
+ if RANK != -1:
317
+ loss *= WORLD_SIZE # gradient averaged between devices in DDP mode
318
+ if opt.quad:
319
+ loss *= 4.
320
+
321
+ # Backward
322
+ scaler.scale(loss).backward()
323
+
324
+ # Optimize
325
+ if ni - last_opt_step >= accumulate:
326
+ scaler.step(optimizer) # optimizer.step
327
+ scaler.update()
328
+ optimizer.zero_grad()
329
+ if ema:
330
+ ema.update(model)
331
+ last_opt_step = ni
332
+
333
+ # Log
334
+ if RANK in [-1, 0]:
335
+ mloss = (mloss * i + loss_items) / (i + 1) # update mean losses
336
+ mem = f'{torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0:.3g}G' # (GB)
337
+ pbar.set_description(('%10s' * 2 + '%10.4g' * 6) % (
338
+ f'{epoch}/{epochs - 1}', mem, *mloss, targets.shape[0], imgs.shape[-1]))
339
+ callbacks.on_train_batch_end(ni, model, imgs, targets, paths, plots, opt.sync_bn)
340
+ # end batch ------------------------------------------------------------------------------------------------
341
+
342
+ # Scheduler
343
+ lr = [x['lr'] for x in optimizer.param_groups[:3]] # for loggers
344
+ scheduler.step()
345
+
346
+ if RANK in [-1, 0]:
347
+ # mAP
348
+ callbacks.on_train_epoch_end(epoch=epoch)
349
+ ema.update_attr(model, include=['yaml', 'nc', 'hyp', 'names', 'stride', 'class_weights'])
350
+ final_epoch = (epoch + 1 == epochs) or stopper.possible_stop
351
+ if not noval or final_epoch: # Calculate mAP
352
+ results, maps, _ = val.run(data_dict,
353
+ batch_size=batch_size // WORLD_SIZE,
354
+ imgsz=imgsz,
355
+ conf_thres=0.01,
356
+ model=ema.ema,
357
+ dataloader=val_loader,
358
+ compute_loss=compute_loss,
359
+ scales=val_scales,
360
+ flips=val_flips)
361
+
362
+ # Update best mAP
363
+ fi = fitness(np.array(results).reshape(1, -1)) # weighted combination of [P, R, mAP@.5, mAP@.5-.95]
364
+ if fi > best_fitness:
365
+ best_fitness = fi
366
+ log_vals = list(mloss) + list(results) + lr
367
+ callbacks.on_fit_epoch_end(log_vals, epoch, best_fitness, fi)
368
+
369
+ # Save model
370
+ if (not nosave) or (final_epoch and not evolve): # if save
371
+ ckpt = {'epoch': epoch,
372
+ 'best_fitness': best_fitness,
373
+ 'model': deepcopy(de_parallel(model)).half(),
374
+ 'ema': deepcopy(ema.ema).half(),
375
+ 'updates': ema.updates,
376
+ 'optimizer': optimizer.state_dict(),
377
+ 'wandb_id': loggers.wandb.wandb_run.id if loggers.wandb else None}
378
+
379
+ # Save last, best and delete
380
+ torch.save(ckpt, last)
381
+ if best_fitness == fi:
382
+ torch.save(ckpt, best)
383
+ del ckpt
384
+ callbacks.on_model_save(last, epoch, final_epoch, best_fitness, fi)
385
+
386
+ # Stop Single-GPU
387
+ if RANK == -1 and stopper(epoch=epoch, fitness=fi):
388
+ break
389
+
390
+ # Stop DDP TODO: known issues shttps://github.com/ultralytics/yolov5/pull/4576
391
+ # stop = stopper(epoch=epoch, fitness=fi)
392
+ # if RANK == 0:
393
+ # dist.broadcast_object_list([stop], 0) # broadcast 'stop' to all ranks
394
+
395
+ # Stop DPP
396
+ # with torch_distributed_zero_first(RANK):
397
+ # if stop:
398
+ # break # must break all DDP ranks
399
+
400
+ # end epoch ----------------------------------------------------------------------------------------------------
401
+ # end training -----------------------------------------------------------------------------------------------------
402
+ if RANK in [-1, 0]:
403
+ LOGGER.info(f'\n{epoch - start_epoch + 1} epochs completed in {(time.time() - t0) / 3600:.3f} hours.')
404
+ if not evolve:
405
+ # Strip optimizers
406
+ for f in last, best:
407
+ if f.exists():
408
+ strip_optimizer(f) # strip optimizers
409
+ callbacks.on_train_end(last, best, plots, epoch)
410
+ LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}")
411
+
412
+ torch.cuda.empty_cache()
413
+ return results
414
+
415
+
416
+ def parse_opt(known=False):
417
+ parser = argparse.ArgumentParser()
418
+ parser.add_argument('--weights', type=str, default='yolov5s6.pt', help='initial weights path')
419
+ parser.add_argument('--cfg', type=str, default='', help='model.yaml path')
420
+ parser.add_argument('--data', type=str, default='data/coco-kp.yaml', help='dataset.yaml path')
421
+ parser.add_argument('--hyp', type=str, default='data/hyps/hyp.kp-p6.yaml', help='hyperparameters path')
422
+ parser.add_argument('--epochs', type=int, default=300)
423
+ parser.add_argument('--batch-size', type=int, default=8, help='total batch size for all GPUs')
424
+ parser.add_argument('--imgsz', '--img', '--img-size', type=int, default=1280, help='train, val image size (pixels)')
425
+ parser.add_argument('--rect', action='store_true', help='rectangular training')
426
+ parser.add_argument('--resume', nargs='?', const=True, default=False, help='resume most recent training')
427
+ parser.add_argument('--nosave', action='store_true', help='only save final checkpoint')
428
+ parser.add_argument('--noval', action='store_true', help='only validate final epoch')
429
+ parser.add_argument('--noautoanchor', action='store_true', help='disable autoanchor check')
430
+ parser.add_argument('--evolve', type=int, nargs='?', const=300, help='evolve hyperparameters for x generations')
431
+ parser.add_argument('--bucket', type=str, default='', help='gsutil bucket')
432
+ parser.add_argument('--cache', type=str, nargs='?', const='ram', help='--cache images in "ram" (default) or "disk"')
433
+ parser.add_argument('--image-weights', action='store_true', help='use weighted image selection for training')
434
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
435
+ parser.add_argument('--multi-scale', action='store_true', help='vary img-size +/- 50%%')
436
+ parser.add_argument('--single-cls', action='store_true', help='train multi-class data as single-class')
437
+ parser.add_argument('--adam', action='store_true', help='use torch.optim.Adam() optimizer')
438
+ parser.add_argument('--sync-bn', action='store_true', help='use SyncBatchNorm, only available in DDP mode')
439
+ parser.add_argument('--workers', type=int, default=8, help='maximum number of dataloader workers')
440
+ parser.add_argument('--project', default='runs/train', help='save to project/name')
441
+ parser.add_argument('--entity', default=None, help='W&B entity')
442
+ parser.add_argument('--name', default='exp', help='save to project/name')
443
+ parser.add_argument('--exist-ok', action='store_true', help='existing project/name ok, do not increment')
444
+ parser.add_argument('--quad', action='store_true', help='quad dataloader')
445
+ parser.add_argument('--linear-lr', action='store_true', help='linear LR')
446
+ parser.add_argument('--label-smoothing', type=float, default=0.0, help='Label smoothing epsilon')
447
+ parser.add_argument('--upload_dataset', action='store_true', help='Upload dataset as W&B artifact table')
448
+ parser.add_argument('--bbox_interval', type=int, default=-1, help='Set bounding-box image logging interval for W&B')
449
+ parser.add_argument('--save_period', type=int, default=-1, help='Log model after every "save_period" epoch')
450
+ parser.add_argument('--artifact_alias', type=str, default="latest", help='version of dataset artifact to be used')
451
+ parser.add_argument('--local_rank', type=int, default=-1, help='DDP parameter, do not modify')
452
+ parser.add_argument('--freeze', type=int, default=0, help='Number of layers to freeze. backbone=10, all=24')
453
+ parser.add_argument('--patience', type=int, default=100, help='EarlyStopping patience (epochs without improvement)')
454
+ parser.add_argument('--val-scales', type=float, nargs='+', default=[1])
455
+ parser.add_argument('--val-flips', type=int, nargs='+', default=[-1])
456
+ parser.add_argument('--autobalance', action='store_true', help='Learn keypoint and object loss scaling')
457
+ opt = parser.parse_known_args()[0] if known else parser.parse_args()
458
+ return opt
459
+
460
+
461
+ def main(opt):
462
+ # Checks
463
+ set_logging(RANK)
464
+ if RANK in [-1, 0]:
465
+ print(colorstr('train: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
466
+ # check_git_status()
467
+ # check_requirements(requirements=FILE.parent / 'requirements.txt', exclude=['thop'])
468
+
469
+ # Resume
470
+ if opt.resume and not opt.evolve: # resume an interrupted run
471
+ ckpt = opt.resume if isinstance(opt.resume, str) else get_latest_run() # specified or most recent path
472
+ assert os.path.isfile(ckpt), 'ERROR: --resume checkpoint does not exist'
473
+ with open(Path(ckpt).parent.parent / 'opt.yaml') as f:
474
+ opt = argparse.Namespace(**yaml.safe_load(f)) # replace
475
+ opt.cfg, opt.weights, opt.resume = '', ckpt, True # reinstate
476
+ LOGGER.info(f'Resuming training from {ckpt}')
477
+ else:
478
+ opt.data, opt.cfg, opt.hyp = check_file(opt.data), check_file(opt.cfg), check_file(opt.hyp) # check files
479
+ assert len(opt.cfg) or len(opt.weights), 'either --cfg or --weights must be specified'
480
+ if opt.evolve:
481
+ opt.project = 'runs/evolve'
482
+ opt.exist_ok = opt.resume
483
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok))
484
+
485
+ # DDP mode
486
+ device = select_device(opt.device, batch_size=opt.batch_size)
487
+ if LOCAL_RANK != -1:
488
+ from datetime import timedelta
489
+ assert torch.cuda.device_count() > LOCAL_RANK, 'insufficient CUDA devices for DDP command'
490
+ assert opt.batch_size % WORLD_SIZE == 0, '--batch-size must be multiple of CUDA device count'
491
+ assert not opt.image_weights, '--image-weights argument is not compatible with DDP training'
492
+ assert not opt.evolve, '--evolve argument is not compatible with DDP training'
493
+ torch.cuda.set_device(LOCAL_RANK)
494
+ device = torch.device('cuda', LOCAL_RANK)
495
+ dist.init_process_group(backend="nccl" if dist.is_nccl_available() else "gloo")
496
+
497
+ # Train
498
+ if not opt.evolve:
499
+ train(opt.hyp, opt, device)
500
+ if WORLD_SIZE > 1 and RANK == 0:
501
+ _ = [print('Destroying process group... ', end=''), dist.destroy_process_group(), print('Done.')]
502
+
503
+ # Evolve hyperparameters (optional)
504
+ else:
505
+ # Hyperparameter evolution metadata (mutation scale 0-1, lower_limit, upper_limit)
506
+ meta = {'lr0': (1, 1e-5, 1e-1), # initial learning rate (SGD=1E-2, Adam=1E-3)
507
+ 'lrf': (1, 0.01, 1.0), # final OneCycleLR learning rate (lr0 * lrf)
508
+ 'momentum': (0.3, 0.6, 0.98), # SGD momentum/Adam beta1
509
+ 'weight_decay': (1, 0.0, 0.001), # optimizer weight decay
510
+ 'warmup_epochs': (1, 0.0, 5.0), # warmup epochs (fractions ok)
511
+ 'warmup_momentum': (1, 0.0, 0.95), # warmup initial momentum
512
+ 'warmup_bias_lr': (1, 0.0, 0.2), # warmup initial bias lr
513
+ 'box': (1, 0.02, 0.2), # box loss gain
514
+ 'cls': (1, 0.2, 4.0), # cls loss gain
515
+ 'cls_pw': (1, 0.5, 2.0), # cls BCELoss positive_weight
516
+ 'obj': (1, 0.2, 4.0), # obj loss gain (scale with pixels)
517
+ 'obj_pw': (1, 0.5, 2.0), # obj BCELoss positive_weight
518
+ 'iou_t': (0, 0.1, 0.7), # IoU training threshold
519
+ 'anchor_t': (1, 2.0, 8.0), # anchor-multiple threshold
520
+ 'anchors': (2, 2.0, 10.0), # anchors per output grid (0 to ignore)
521
+ 'fl_gamma': (0, 0.0, 2.0), # focal loss gamma (efficientDet default gamma=1.5)
522
+ 'hsv_h': (1, 0.0, 0.1), # image HSV-Hue augmentation (fraction)
523
+ 'hsv_s': (1, 0.0, 0.9), # image HSV-Saturation augmentation (fraction)
524
+ 'hsv_v': (1, 0.0, 0.9), # image HSV-Value augmentation (fraction)
525
+ 'degrees': (1, 0.0, 45.0), # image rotation (+/- deg)
526
+ 'translate': (1, 0.0, 0.9), # image translation (+/- fraction)
527
+ 'scale': (1, 0.0, 0.9), # image scale (+/- gain)
528
+ 'shear': (1, 0.0, 10.0), # image shear (+/- deg)
529
+ 'perspective': (0, 0.0, 0.001), # image perspective (+/- fraction), range 0-0.001
530
+ 'flipud': (1, 0.0, 1.0), # image flip up-down (probability)
531
+ 'fliplr': (0, 0.0, 1.0), # image flip left-right (probability)
532
+ 'mosaic': (1, 0.0, 1.0), # image mixup (probability)
533
+ 'mixup': (1, 0.0, 1.0), # image mixup (probability)
534
+ 'copy_paste': (1, 0.0, 1.0)} # segment copy-paste (probability)
535
+
536
+ with open(opt.hyp) as f:
537
+ hyp = yaml.safe_load(f) # load hyps dict
538
+ if 'anchors' not in hyp: # anchors commented in hyp.yaml
539
+ hyp['anchors'] = 3
540
+ opt.noval, opt.nosave, save_dir = True, True, Path(opt.save_dir) # only val/save final epoch
541
+ # ei = [isinstance(x, (int, float)) for x in hyp.values()] # evolvable indices
542
+ evolve_yaml, evolve_csv = save_dir / 'hyp_evolve.yaml', save_dir / 'evolve.csv'
543
+ if opt.bucket:
544
+ os.system(f'gsutil cp gs://{opt.bucket}/evolve.csv {save_dir}') # download evolve.csv if exists
545
+
546
+ for _ in range(opt.evolve): # generations to evolve
547
+ if evolve_csv.exists(): # if evolve.csv exists: select best hyps and mutate
548
+ # Select parent(s)
549
+ parent = 'single' # parent selection method: 'single' or 'weighted'
550
+ x = np.loadtxt(evolve_csv, ndmin=2, delimiter=',', skiprows=1)
551
+ n = min(5, len(x)) # number of previous results to consider
552
+ x = x[np.argsort(-fitness(x))][:n] # top n mutations
553
+ w = fitness(x) - fitness(x).min() + 1E-6 # weights (sum > 0)
554
+ if parent == 'single' or len(x) == 1:
555
+ # x = x[random.randint(0, n - 1)] # random selection
556
+ x = x[random.choices(range(n), weights=w)[0]] # weighted selection
557
+ elif parent == 'weighted':
558
+ x = (x * w.reshape(n, 1)).sum(0) / w.sum() # weighted combination
559
+
560
+ # Mutate
561
+ mp, s = 0.8, 0.2 # mutation probability, sigma
562
+ npr = np.random
563
+ npr.seed(int(time.time()))
564
+ g = np.array([meta[k][0] for k in hyp.keys()]) # gains 0-1
565
+ ng = len(meta)
566
+ v = np.ones(ng)
567
+ while all(v == 1): # mutate until a change occurs (prevent duplicates)
568
+ v = (g * (npr.random(ng) < mp) * npr.randn(ng) * npr.random() * s + 1).clip(0.3, 3.0)
569
+ for i, k in enumerate(hyp.keys()): # plt.hist(v.ravel(), 300)
570
+ hyp[k] = float(x[i + 7] * v[i]) # mutate
571
+
572
+ # Constrain to limits
573
+ for k, v in meta.items():
574
+ hyp[k] = max(hyp[k], v[1]) # lower limit
575
+ hyp[k] = min(hyp[k], v[2]) # upper limit
576
+ hyp[k] = round(hyp[k], 5) # significant digits
577
+
578
+ # Train mutation
579
+ results = train(hyp.copy(), opt, device)
580
+
581
+ # Write mutation results
582
+ print_mutation(results, hyp.copy(), save_dir, opt.bucket)
583
+
584
+ # Plot results
585
+ plot_evolve(evolve_csv)
586
+ print(f'Hyperparameter evolution finished\n'
587
+ f"Results saved to {colorstr('bold', save_dir)}\n"
588
+ f'Use best hyperparameters example: $ python train.py --hyp {evolve_yaml}')
589
+
590
+
591
+ def run(**kwargs):
592
+ # Usage: import train; train.run(data='coco128.yaml', imgsz=320, weights='yolov5m.pt')
593
+ opt = parse_opt(True)
594
+ for k, v in kwargs.items():
595
+ setattr(opt, k, v)
596
+ main(opt)
597
+
598
+
599
+ if __name__ == "__main__":
600
+ opt = parse_opt()
601
+ main(opt)
utils/.DS_Store ADDED
Binary file (6.15 kB). View file
 
utils/activations.py ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Activation functions
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ import torch.nn.functional as F
9
+
10
+
11
+ # SiLU https://arxiv.org/pdf/1606.08415.pdf ----------------------------------------------------------------------------
12
+ class SiLU(nn.Module): # export-friendly version of nn.SiLU()
13
+ @staticmethod
14
+ def forward(x):
15
+ return x * torch.sigmoid(x)
16
+
17
+
18
+ class Hardswish(nn.Module): # export-friendly version of nn.Hardswish()
19
+ @staticmethod
20
+ def forward(x):
21
+ # return x * F.hardsigmoid(x) # for torchscript and CoreML
22
+ return x * F.hardtanh(x + 3, 0., 6.) / 6. # for torchscript, CoreML and ONNX
23
+
24
+
25
+ # Mish https://github.com/digantamisra98/Mish --------------------------------------------------------------------------
26
+ class Mish(nn.Module):
27
+ @staticmethod
28
+ def forward(x):
29
+ return x * F.softplus(x).tanh()
30
+
31
+
32
+ class MemoryEfficientMish(nn.Module):
33
+ class F(torch.autograd.Function):
34
+ @staticmethod
35
+ def forward(ctx, x):
36
+ ctx.save_for_backward(x)
37
+ return x.mul(torch.tanh(F.softplus(x))) # x * tanh(ln(1 + exp(x)))
38
+
39
+ @staticmethod
40
+ def backward(ctx, grad_output):
41
+ x = ctx.saved_tensors[0]
42
+ sx = torch.sigmoid(x)
43
+ fx = F.softplus(x).tanh()
44
+ return grad_output * (fx + x * sx * (1 - fx * fx))
45
+
46
+ def forward(self, x):
47
+ return self.F.apply(x)
48
+
49
+
50
+ # FReLU https://arxiv.org/abs/2007.11824 -------------------------------------------------------------------------------
51
+ class FReLU(nn.Module):
52
+ def __init__(self, c1, k=3): # ch_in, kernel
53
+ super().__init__()
54
+ self.conv = nn.Conv2d(c1, c1, k, 1, 1, groups=c1, bias=False)
55
+ self.bn = nn.BatchNorm2d(c1)
56
+
57
+ def forward(self, x):
58
+ return torch.max(x, self.bn(self.conv(x)))
59
+
60
+
61
+ # ACON https://arxiv.org/pdf/2009.04759.pdf ----------------------------------------------------------------------------
62
+ class AconC(nn.Module):
63
+ r""" ACON activation (activate or not).
64
+ AconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is a learnable parameter
65
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
66
+ """
67
+
68
+ def __init__(self, c1):
69
+ super().__init__()
70
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
71
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
72
+ self.beta = nn.Parameter(torch.ones(1, c1, 1, 1))
73
+
74
+ def forward(self, x):
75
+ dpx = (self.p1 - self.p2) * x
76
+ return dpx * torch.sigmoid(self.beta * dpx) + self.p2 * x
77
+
78
+
79
+ class MetaAconC(nn.Module):
80
+ r""" ACON activation (activate or not).
81
+ MetaAconC: (p1*x-p2*x) * sigmoid(beta*(p1*x-p2*x)) + p2*x, beta is generated by a small network
82
+ according to "Activate or Not: Learning Customized Activation" <https://arxiv.org/pdf/2009.04759.pdf>.
83
+ """
84
+
85
+ def __init__(self, c1, k=1, s=1, r=16): # ch_in, kernel, stride, r
86
+ super().__init__()
87
+ c2 = max(r, c1 // r)
88
+ self.p1 = nn.Parameter(torch.randn(1, c1, 1, 1))
89
+ self.p2 = nn.Parameter(torch.randn(1, c1, 1, 1))
90
+ self.fc1 = nn.Conv2d(c1, c2, k, s, bias=True)
91
+ self.fc2 = nn.Conv2d(c2, c1, k, s, bias=True)
92
+ # self.bn1 = nn.BatchNorm2d(c2)
93
+ # self.bn2 = nn.BatchNorm2d(c1)
94
+
95
+ def forward(self, x):
96
+ y = x.mean(dim=2, keepdims=True).mean(dim=3, keepdims=True)
97
+ # batch-size 1 bug/instabilities https://github.com/ultralytics/yolov5/issues/2891
98
+ # beta = torch.sigmoid(self.bn2(self.fc2(self.bn1(self.fc1(y))))) # bug/unstable
99
+ beta = torch.sigmoid(self.fc2(self.fc1(y))) # bug patch BN layers removed
100
+ dpx = (self.p1 - self.p2) * x
101
+ return dpx * torch.sigmoid(beta * dpx) + self.p2 * x
utils/augmentations.py ADDED
@@ -0,0 +1,321 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Image augmentation functions
4
+ """
5
+
6
+ import logging
7
+ import math
8
+ import random
9
+
10
+ import cv2
11
+ import numpy as np
12
+
13
+ from utils.general import colorstr, segment2box, resample_segments, check_version
14
+ from utils.metrics import bbox_ioa
15
+
16
+
17
+ class Albumentations:
18
+ # YOLOv5 Albumentations class (optional, only used if package is installed)
19
+ def __init__(self):
20
+ self.transform = None
21
+ try:
22
+ import albumentations as A
23
+ check_version(A.__version__, '1.0.3') # version requirement
24
+
25
+ self.transform = A.Compose([
26
+ A.Blur(p=0.1),
27
+ A.MedianBlur(p=0.1),
28
+ A.ToGray(p=0.01)],
29
+ bbox_params=A.BboxParams(format='yolo', label_fields=['class_labels']))
30
+
31
+ logging.info(colorstr('albumentations: ') + ', '.join(f'{x}' for x in self.transform.transforms if x.p))
32
+ except ImportError: # package not installed, skip
33
+ pass
34
+ except Exception as e:
35
+ logging.info(colorstr('albumentations: ') + f'{e}')
36
+
37
+ def __call__(self, im, labels, p=1.0):
38
+ if self.transform and random.random() < p:
39
+ new = self.transform(image=im, bboxes=labels[:, 1:], class_labels=labels[:, 0]) # transformed
40
+ im, labels = new['image'], np.array([[c, *b] for c, b in zip(new['class_labels'], new['bboxes'])])
41
+ return im, labels
42
+
43
+
44
+ def augment_hsv(im, hgain=0.5, sgain=0.5, vgain=0.5):
45
+ # HSV color-space augmentation
46
+ if hgain or sgain or vgain:
47
+ r = np.random.uniform(-1, 1, 3) * [hgain, sgain, vgain] + 1 # random gains
48
+ hue, sat, val = cv2.split(cv2.cvtColor(im, cv2.COLOR_BGR2HSV))
49
+ dtype = im.dtype # uint8
50
+
51
+ x = np.arange(0, 256, dtype=r.dtype)
52
+ lut_hue = ((x * r[0]) % 180).astype(dtype)
53
+ lut_sat = np.clip(x * r[1], 0, 255).astype(dtype)
54
+ lut_val = np.clip(x * r[2], 0, 255).astype(dtype)
55
+
56
+ im_hsv = cv2.merge((cv2.LUT(hue, lut_hue), cv2.LUT(sat, lut_sat), cv2.LUT(val, lut_val)))
57
+ cv2.cvtColor(im_hsv, cv2.COLOR_HSV2BGR, dst=im) # no return needed
58
+
59
+
60
+ def hist_equalize(im, clahe=True, bgr=False):
61
+ # Equalize histogram on BGR image 'im' with im.shape(n,m,3) and range 0-255
62
+ yuv = cv2.cvtColor(im, cv2.COLOR_BGR2YUV if bgr else cv2.COLOR_RGB2YUV)
63
+ if clahe:
64
+ c = cv2.createCLAHE(clipLimit=2.0, tileGridSize=(8, 8))
65
+ yuv[:, :, 0] = c.apply(yuv[:, :, 0])
66
+ else:
67
+ yuv[:, :, 0] = cv2.equalizeHist(yuv[:, :, 0]) # equalize Y channel histogram
68
+ return cv2.cvtColor(yuv, cv2.COLOR_YUV2BGR if bgr else cv2.COLOR_YUV2RGB) # convert YUV image to RGB
69
+
70
+
71
+ def replicate(im, labels):
72
+ # Replicate labels
73
+ h, w = im.shape[:2]
74
+ boxes = labels[:, 1:].astype(int)
75
+ x1, y1, x2, y2 = boxes.T
76
+ s = ((x2 - x1) + (y2 - y1)) / 2 # side length (pixels)
77
+ for i in s.argsort()[:round(s.size * 0.5)]: # smallest indices
78
+ x1b, y1b, x2b, y2b = boxes[i]
79
+ bh, bw = y2b - y1b, x2b - x1b
80
+ yc, xc = int(random.uniform(0, h - bh)), int(random.uniform(0, w - bw)) # offset x, y
81
+ x1a, y1a, x2a, y2a = [xc, yc, xc + bw, yc + bh]
82
+ im[y1a:y2a, x1a:x2a] = im[y1b:y2b, x1b:x2b] # im4[ymin:ymax, xmin:xmax]
83
+ labels = np.append(labels, [[labels[i, 0], x1a, y1a, x2a, y2a]], axis=0)
84
+
85
+ return im, labels
86
+
87
+
88
+ def letterbox(im, new_shape=(640, 640), color=(114, 114, 114), auto=True, scaleFill=False, scaleup=True, stride=32):
89
+ # Resize and pad image while meeting stride-multiple constraints
90
+ shape = im.shape[:2] # current shape [height, width]
91
+ if isinstance(new_shape, int):
92
+ new_shape = (new_shape, new_shape)
93
+
94
+ # Scale ratio (new / old)
95
+ r = min(new_shape[0] / shape[0], new_shape[1] / shape[1])
96
+ if not scaleup: # only scale down, do not scale up (for better val mAP)
97
+ r = min(r, 1.0)
98
+
99
+ # Compute padding
100
+ ratio = r, r # width, height ratios
101
+ new_unpad = int(round(shape[1] * r)), int(round(shape[0] * r))
102
+ dw, dh = new_shape[1] - new_unpad[0], new_shape[0] - new_unpad[1] # wh padding
103
+ if auto: # minimum rectangle
104
+ dw, dh = np.mod(dw, stride), np.mod(dh, stride) # wh padding
105
+ elif scaleFill: # stretch
106
+ dw, dh = 0.0, 0.0
107
+ new_unpad = (new_shape[1], new_shape[0])
108
+ ratio = new_shape[1] / shape[1], new_shape[0] / shape[0] # width, height ratios
109
+
110
+ dw /= 2 # divide padding into 2 sides
111
+ dh /= 2
112
+
113
+ if shape[::-1] != new_unpad: # resize
114
+ im = cv2.resize(im, new_unpad, interpolation=cv2.INTER_LINEAR)
115
+ top, bottom = int(round(dh - 0.1)), int(round(dh + 0.1))
116
+ left, right = int(round(dw - 0.1)), int(round(dw + 0.1))
117
+ im = cv2.copyMakeBorder(im, top, bottom, left, right, cv2.BORDER_CONSTANT, value=color) # add border
118
+ return im, ratio, (dw, dh)
119
+
120
+
121
+ def random_perspective(im, targets=(), segments=(), degrees=10, translate=.1, scale=.1, shear=10, perspective=0.0,
122
+ border=(0, 0), kp_bbox=None):
123
+ # torchvision.transforms.RandomAffine(degrees=(-10, 10), translate=(.1, .1), scale=(.9, 1.1), shear=(-10, 10))
124
+ # targets = [cls, xyxy]
125
+
126
+ height = im.shape[0] + border[0] * 2 # shape(h,w,c)
127
+ width = im.shape[1] + border[1] * 2
128
+
129
+ # Center
130
+ C = np.eye(3)
131
+ C[0, 2] = -im.shape[1] / 2 # x translation (pixels)
132
+ C[1, 2] = -im.shape[0] / 2 # y translation (pixels)
133
+
134
+ # Perspective
135
+ P = np.eye(3)
136
+ P[2, 0] = random.uniform(-perspective, perspective) # x perspective (about y)
137
+ P[2, 1] = random.uniform(-perspective, perspective) # y perspective (about x)
138
+
139
+ # Rotation and Scale
140
+ R = np.eye(3)
141
+ a = random.uniform(-degrees, degrees)
142
+ # a += random.choice([-180, -90, 0, 90]) # add 90deg rotations to small rotations
143
+ s = random.uniform(1 - scale, 1 + scale)
144
+ # s = 2 ** random.uniform(-scale, scale)
145
+ R[:2] = cv2.getRotationMatrix2D(angle=a, center=(0, 0), scale=s)
146
+
147
+ # Shear
148
+ S = np.eye(3)
149
+ S[0, 1] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # x shear (deg)
150
+ S[1, 0] = math.tan(random.uniform(-shear, shear) * math.pi / 180) # y shear (deg)
151
+
152
+ # Translation
153
+ T = np.eye(3)
154
+ T[0, 2] = random.uniform(0.5 - translate, 0.5 + translate) * width # x translation (pixels)
155
+ T[1, 2] = random.uniform(0.5 - translate, 0.5 + translate) * height # y translation (pixels)
156
+
157
+ # Combined rotation matrix
158
+ M = T @ S @ R @ P @ C # order of operations (right to left) is IMPORTANT
159
+ if (border[0] != 0) or (border[1] != 0) or (M != np.eye(3)).any(): # image changed
160
+ if perspective:
161
+ im = cv2.warpPerspective(im, M, dsize=(width, height), borderValue=(114, 114, 114))
162
+ else: # affine
163
+ im = cv2.warpAffine(im, M[:2], dsize=(width, height), borderValue=(114, 114, 114))
164
+
165
+ # Visualize
166
+ # import matplotlib.pyplot as plt
167
+ # ax = plt.subplots(1, 2, figsize=(12, 6))[1].ravel()
168
+ # ax[0].imshow(im[:, :, ::-1]) # base
169
+ # ax[1].imshow(im2[:, :, ::-1]) # warped
170
+
171
+ # Transform label coordinates
172
+ n = len(targets)
173
+ if n:
174
+ use_segments = any(x.any() for x in segments)
175
+ new = np.zeros((n, 4))
176
+ if use_segments: # warp segments
177
+ segments = resample_segments(segments) # upsample
178
+ for i, segment in enumerate(segments):
179
+ xy = np.ones((len(segment), 3))
180
+ xy[:, :2] = segment
181
+ xy = xy @ M.T # transform
182
+ xy = xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2] # perspective rescale or affine
183
+
184
+ # clip
185
+ new[i] = segment2box(xy, width, height)
186
+
187
+ else: # warp boxes
188
+ xy = np.ones((n * 4, 3))
189
+ xy[:, :2] = targets[:, [1, 2, 3, 4, 1, 4, 3, 2]].reshape(n * 4, 2) # x1y1, x2y2, x1y2, x2y1
190
+ xy = xy @ M.T # transform
191
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]).reshape(n, 8) # perspective rescale or affine
192
+
193
+ # create new boxes
194
+ x = xy[:, [0, 2, 4, 6]]
195
+ y = xy[:, [1, 3, 5, 7]]
196
+ new = np.concatenate((x.min(1), y.min(1), x.max(1), y.max(1))).reshape(4, n).T
197
+
198
+ # clip
199
+ new[:, [0, 2]] = new[:, [0, 2]].clip(0, width)
200
+ new[:, [1, 3]] = new[:, [1, 3]].clip(0, height)
201
+
202
+ # filter candidates
203
+ i = box_candidates(box1=targets[:, 1:5].T * s, box2=new.T, area_thr=0.01 if use_segments else 0.10)
204
+ targets = targets[i]
205
+ targets[:, 1:5] = new[i]
206
+
207
+ n = len(targets)
208
+ if n and targets.shape[1] > 5:
209
+ # warp keypoints in person object
210
+ person_mask = targets[:, 0] == 0
211
+ person_targets = targets[person_mask]
212
+ if len(person_targets) > 0:
213
+ xy = person_targets[:, 5:].reshape(-1, 3)
214
+ vis = xy[:, 2:].copy()
215
+ xy[:, 2:] = 1
216
+ xy = xy @ M.T # transform
217
+ xy = (xy[:, :2] / xy[:, 2:3] if perspective else xy[:, :2]) # perspective rescale or affine
218
+ out_mask = (
219
+ (xy[:, 0] < 0) |
220
+ (xy[:, 1] < 0) |
221
+ (xy[:, 0] > width) |
222
+ (xy[:, 1] > height)
223
+ )
224
+ vis[out_mask] = 0
225
+ keypoints = np.concatenate((xy, vis), axis=-1)
226
+ targets[person_mask, 5:] = keypoints.reshape(person_targets.shape[0], -1)
227
+
228
+ # resize keypoint bbox sizes back to original
229
+ if n and kp_bbox is not None:
230
+ for i in range(int(targets[:, 0].max()) + 1):
231
+ if i > 0:
232
+ if isinstance(kp_bbox, list):
233
+ kp_bbox_i = kp_bbox[i - 1]
234
+ else:
235
+ kp_bbox_i = kp_bbox
236
+
237
+ kp_mask = targets[:, 0] == i
238
+ kp_targets = targets[kp_mask]
239
+
240
+ xc = kp_targets[:, [1, 3]].mean(axis=-1)
241
+ yc = kp_targets[:, [2, 4]].mean(axis=-1)
242
+
243
+ kp_targets[:, 1] = xc - (kp_bbox_i * width) / 2
244
+ kp_targets[:, 2] = yc - (kp_bbox_i * height) / 2
245
+ kp_targets[:, 3] = xc + (kp_bbox_i * width) / 2
246
+ kp_targets[:, 4] = yc + (kp_bbox_i * height) / 2
247
+
248
+ targets[kp_mask] = kp_targets
249
+
250
+ # clip
251
+ targets[:, [1, 3]] = targets[:, [1, 3]].clip(0, width)
252
+ targets[:, [2, 4]] = targets[:, [2, 4]].clip(0, height)
253
+
254
+ return im, targets
255
+
256
+
257
+ def copy_paste(im, labels, segments, p=0.5):
258
+ # Implement Copy-Paste augmentation https://arxiv.org/abs/2012.07177, labels as nx5 np.array(cls, xyxy)
259
+ n = len(segments)
260
+ if p and n:
261
+ h, w, c = im.shape # height, width, channels
262
+ im_new = np.zeros(im.shape, np.uint8)
263
+ for j in random.sample(range(n), k=round(p * n)):
264
+ l, s = labels[j], segments[j]
265
+ box = w - l[3], l[2], w - l[1], l[4]
266
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
267
+ if (ioa < 0.30).all(): # allow 30% obscuration of existing labels
268
+ labels = np.concatenate((labels, [[l[0], *box]]), 0)
269
+ segments.append(np.concatenate((w - s[:, 0:1], s[:, 1:2]), 1))
270
+ cv2.drawContours(im_new, [segments[j].astype(np.int32)], -1, (255, 255, 255), cv2.FILLED)
271
+
272
+ result = cv2.bitwise_and(src1=im, src2=im_new)
273
+ result = cv2.flip(result, 1) # augment segments (flip left-right)
274
+ i = result > 0 # pixels to replace
275
+ # i[:, :] = result.max(2).reshape(h, w, 1) # act over ch
276
+ im[i] = result[i] # cv2.imwrite('debug.jpg', im) # debug
277
+
278
+ return im, labels, segments
279
+
280
+
281
+ def cutout(im, labels, p=0.5):
282
+ # Applies image cutout augmentation https://arxiv.org/abs/1708.04552
283
+ if random.random() < p:
284
+ h, w = im.shape[:2]
285
+ scales = [0.5] * 1 + [0.25] * 2 + [0.125] * 4 + [0.0625] * 8 + [0.03125] * 16 # image size fraction
286
+ for s in scales:
287
+ mask_h = random.randint(1, int(h * s)) # create random masks
288
+ mask_w = random.randint(1, int(w * s))
289
+
290
+ # box
291
+ xmin = max(0, random.randint(0, w) - mask_w // 2)
292
+ ymin = max(0, random.randint(0, h) - mask_h // 2)
293
+ xmax = min(w, xmin + mask_w)
294
+ ymax = min(h, ymin + mask_h)
295
+
296
+ # apply random color mask
297
+ im[ymin:ymax, xmin:xmax] = [random.randint(64, 191) for _ in range(3)]
298
+
299
+ # return unobscured labels
300
+ if len(labels) and s > 0.03:
301
+ box = np.array([xmin, ymin, xmax, ymax], dtype=np.float32)
302
+ ioa = bbox_ioa(box, labels[:, 1:5]) # intersection over area
303
+ labels = labels[ioa < 0.60] # remove >60% obscured labels
304
+
305
+ return labels
306
+
307
+
308
+ def mixup(im, labels, im2, labels2):
309
+ # Applies MixUp augmentation https://arxiv.org/pdf/1710.09412.pdf
310
+ r = np.random.beta(32.0, 32.0) # mixup ratio, alpha=beta=32.0
311
+ im = (im * r + im2 * (1 - r)).astype(np.uint8)
312
+ labels = np.concatenate((labels, labels2), 0)
313
+ return im, labels
314
+
315
+
316
+ def box_candidates(box1, box2, wh_thr=2, ar_thr=20, area_thr=0.1, eps=1e-16): # box1(4,n), box2(4,n)
317
+ # Compute candidate boxes: box1 before augment, box2 after augment, wh_thr (pixels), aspect_ratio_thr, area_ratio
318
+ w1, h1 = box1[2] - box1[0], box1[3] - box1[1]
319
+ w2, h2 = box2[2] - box2[0], box2[3] - box2[1]
320
+ ar = np.maximum(w2 / (h2 + eps), h2 / (w2 + eps)) # aspect ratio
321
+ return (w2 > wh_thr) & (h2 > wh_thr) & (w2 * h2 / (w1 * h1 + eps) > area_thr) & (ar < ar_thr) # candidates
utils/autoanchor.py ADDED
@@ -0,0 +1,164 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Auto-anchor utils
4
+ """
5
+
6
+ import random
7
+
8
+ import numpy as np
9
+ import torch
10
+ import yaml
11
+ from tqdm import tqdm
12
+
13
+ from utils.general import colorstr
14
+
15
+
16
+ def check_anchor_order(m):
17
+ # Check anchor order against stride order for YOLOv5 Detect() module m, and correct if necessary
18
+ a = m.anchor_grid.prod(-1).view(-1) # anchor area
19
+ da = a[-1] - a[0] # delta a
20
+ ds = m.stride[-1] - m.stride[0] # delta s
21
+ if da.sign() != ds.sign(): # same order
22
+ print('Reversing anchor order')
23
+ m.anchors[:] = m.anchors.flip(0)
24
+ m.anchor_grid[:] = m.anchor_grid.flip(0)
25
+
26
+
27
+ def check_anchors(dataset, model, thr=4.0, imgsz=640):
28
+ # Check anchor fit to data, recompute if necessary
29
+ prefix = colorstr('autoanchor: ')
30
+ print(f'\n{prefix}Analyzing anchors... ', end='')
31
+ m = model.module.model[-1] if hasattr(model, 'module') else model.model[-1] # Detect()
32
+ shapes = imgsz * dataset.shapes / dataset.shapes.max(1, keepdims=True)
33
+ scale = np.random.uniform(0.9, 1.1, size=(shapes.shape[0], 1)) # augment scale
34
+ wh = torch.tensor(np.concatenate([l[:, 3:5] * s for s, l in zip(shapes * scale, dataset.labels)])).float() # wh
35
+
36
+ def metric(k): # compute metric
37
+ r = wh[:, None] / k[None]
38
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
39
+ best = x.max(1)[0] # best_x
40
+ aat = (x > 1. / thr).float().sum(1).mean() # anchors above threshold
41
+ bpr = (best > 1. / thr).float().mean() # best possible recall
42
+ return bpr, aat
43
+
44
+ anchors = m.anchor_grid.clone().cpu().view(-1, 2) # current anchors
45
+ bpr, aat = metric(anchors)
46
+ print(f'anchors/target = {aat:.2f}, Best Possible Recall (BPR) = {bpr:.4f}', end='')
47
+ if bpr < 0.98: # threshold to recompute
48
+ print('. Attempting to improve anchors, please wait...')
49
+ na = m.anchor_grid.numel() // 2 # number of anchors
50
+ try:
51
+ anchors = kmean_anchors(dataset, n=na, img_size=imgsz, thr=thr, gen=1000, verbose=False)
52
+ except Exception as e:
53
+ print(f'{prefix}ERROR: {e}')
54
+ new_bpr = metric(anchors)[0]
55
+ if new_bpr > bpr: # replace anchors
56
+ anchors = torch.tensor(anchors, device=m.anchors.device).type_as(m.anchors)
57
+ m.anchor_grid[:] = anchors.clone().view_as(m.anchor_grid) # for inference
58
+ m.anchors[:] = anchors.clone().view_as(m.anchors) / m.stride.to(m.anchors.device).view(-1, 1, 1) # loss
59
+ check_anchor_order(m)
60
+ print(f'{prefix}New anchors saved to model. Update model *.yaml to use these anchors in the future.')
61
+ else:
62
+ print(f'{prefix}Original anchors better than new anchors. Proceeding with original anchors.')
63
+ print('') # newline
64
+
65
+
66
+ def kmean_anchors(dataset='./data/coco128.yaml', n=9, img_size=640, thr=4.0, gen=1000, verbose=True):
67
+ """ Creates kmeans-evolved anchors from training dataset
68
+
69
+ Arguments:
70
+ dataset: path to data.yaml, or a loaded dataset
71
+ n: number of anchors
72
+ img_size: image size used for training
73
+ thr: anchor-label wh ratio threshold hyperparameter hyp['anchor_t'] used for training, default=4.0
74
+ gen: generations to evolve anchors using genetic algorithm
75
+ verbose: print all results
76
+
77
+ Return:
78
+ k: kmeans evolved anchors
79
+
80
+ Usage:
81
+ from utils.autoanchor import *; _ = kmean_anchors()
82
+ """
83
+ from scipy.cluster.vq import kmeans
84
+
85
+ thr = 1. / thr
86
+ prefix = colorstr('autoanchor: ')
87
+
88
+ def metric(k, wh): # compute metrics
89
+ r = wh[:, None] / k[None]
90
+ x = torch.min(r, 1. / r).min(2)[0] # ratio metric
91
+ # x = wh_iou(wh, torch.tensor(k)) # iou metric
92
+ return x, x.max(1)[0] # x, best_x
93
+
94
+ def anchor_fitness(k): # mutation fitness
95
+ _, best = metric(torch.tensor(k, dtype=torch.float32), wh)
96
+ return (best * (best > thr).float()).mean() # fitness
97
+
98
+ def print_results(k):
99
+ k = k[np.argsort(k.prod(1))] # sort small to large
100
+ x, best = metric(k, wh0)
101
+ bpr, aat = (best > thr).float().mean(), (x > thr).float().mean() * n # best possible recall, anch > thr
102
+ print(f'{prefix}thr={thr:.2f}: {bpr:.4f} best possible recall, {aat:.2f} anchors past thr')
103
+ print(f'{prefix}n={n}, img_size={img_size}, metric_all={x.mean():.3f}/{best.mean():.3f}-mean/best, '
104
+ f'past_thr={x[x > thr].mean():.3f}-mean: ', end='')
105
+ for i, x in enumerate(k):
106
+ print('%i,%i' % (round(x[0]), round(x[1])), end=', ' if i < len(k) - 1 else '\n') # use in *.cfg
107
+ return k
108
+
109
+ if isinstance(dataset, str): # *.yaml file
110
+ with open(dataset, errors='ignore') as f:
111
+ data_dict = yaml.safe_load(f) # model dict
112
+ from utils.datasets import LoadImagesAndLabels
113
+ dataset = LoadImagesAndLabels(data_dict['train'], augment=True, rect=True)
114
+
115
+ # Get label wh
116
+ shapes = img_size * dataset.shapes / dataset.shapes.max(1, keepdims=True)
117
+ wh0 = np.concatenate([l[:, 3:5] * s for s, l in zip(shapes, dataset.labels)]) # wh
118
+
119
+ # Filter
120
+ i = (wh0 < 3.0).any(1).sum()
121
+ if i:
122
+ print(f'{prefix}WARNING: Extremely small objects found. {i} of {len(wh0)} labels are < 3 pixels in size.')
123
+ wh = wh0[(wh0 >= 2.0).any(1)] # filter > 2 pixels
124
+ # wh = wh * (np.random.rand(wh.shape[0], 1) * 0.9 + 0.1) # multiply by random scale 0-1
125
+
126
+ # Kmeans calculation
127
+ print(f'{prefix}Running kmeans for {n} anchors on {len(wh)} points...')
128
+ s = wh.std(0) # sigmas for whitening
129
+ k, dist = kmeans(wh / s, n, iter=30) # points, mean distance
130
+ assert len(k) == n, print(f'{prefix}ERROR: scipy.cluster.vq.kmeans requested {n} points but returned only {len(k)}')
131
+ k *= s
132
+ wh = torch.tensor(wh, dtype=torch.float32) # filtered
133
+ wh0 = torch.tensor(wh0, dtype=torch.float32) # unfiltered
134
+ k = print_results(k)
135
+
136
+ # Plot
137
+ # k, d = [None] * 20, [None] * 20
138
+ # for i in tqdm(range(1, 21)):
139
+ # k[i-1], d[i-1] = kmeans(wh / s, i) # points, mean distance
140
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7), tight_layout=True)
141
+ # ax = ax.ravel()
142
+ # ax[0].plot(np.arange(1, 21), np.array(d) ** 2, marker='.')
143
+ # fig, ax = plt.subplots(1, 2, figsize=(14, 7)) # plot wh
144
+ # ax[0].hist(wh[wh[:, 0]<100, 0],400)
145
+ # ax[1].hist(wh[wh[:, 1]<100, 1],400)
146
+ # fig.savefig('wh.png', dpi=200)
147
+
148
+ # Evolve
149
+ npr = np.random
150
+ f, sh, mp, s = anchor_fitness(k), k.shape, 0.9, 0.1 # fitness, generations, mutation prob, sigma
151
+ pbar = tqdm(range(gen), desc=f'{prefix}Evolving anchors with Genetic Algorithm:') # progress bar
152
+ for _ in pbar:
153
+ v = np.ones(sh)
154
+ while (v == 1).all(): # mutate until a change occurs (prevent duplicates)
155
+ v = ((npr.random(sh) < mp) * random.random() * npr.randn(*sh) * s + 1).clip(0.3, 3.0)
156
+ kg = (k.copy() * v).clip(min=2.0)
157
+ fg = anchor_fitness(kg)
158
+ if fg > f:
159
+ f, k = fg, kg.copy()
160
+ pbar.desc = f'{prefix}Evolving anchors with Genetic Algorithm: fitness = {f:.4f}'
161
+ if verbose:
162
+ print_results(k)
163
+
164
+ return print_results(k)
utils/callbacks.py ADDED
@@ -0,0 +1,179 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Callback utils
4
+ """
5
+
6
+
7
+ class Callbacks:
8
+ """"
9
+ Handles all registered callbacks for YOLOv5 Hooks
10
+ """
11
+
12
+ _callbacks = {
13
+ 'on_pretrain_routine_start': [],
14
+ 'on_pretrain_routine_end': [],
15
+
16
+ 'on_train_start': [],
17
+ 'on_train_epoch_start': [],
18
+ 'on_train_batch_start': [],
19
+ 'optimizer_step': [],
20
+ 'on_before_zero_grad': [],
21
+ 'on_train_batch_end': [],
22
+ 'on_train_epoch_end': [],
23
+
24
+ 'on_val_start': [],
25
+ 'on_val_batch_start': [],
26
+ 'on_val_image_end': [],
27
+ 'on_val_batch_end': [],
28
+ 'on_val_end': [],
29
+
30
+ 'on_fit_epoch_end': [], # fit = train + val
31
+ 'on_model_save': [],
32
+ 'on_train_end': [],
33
+
34
+ 'teardown': [],
35
+ }
36
+
37
+ def __init__(self):
38
+ return
39
+
40
+ def register_action(self, hook, name='', callback=None):
41
+ """
42
+ Register a new action to a callback hook
43
+
44
+ Args:
45
+ hook The callback hook name to register the action to
46
+ name The name of the action
47
+ callback The callback to fire
48
+ """
49
+ assert hook in self._callbacks, f"hook '{hook}' not found in callbacks {self._callbacks}"
50
+ assert callable(callback), f"callback '{callback}' is not callable"
51
+ self._callbacks[hook].append({'name': name, 'callback': callback})
52
+
53
+ def get_registered_actions(self, hook=None):
54
+ """"
55
+ Returns all the registered actions by callback hook
56
+
57
+ Args:
58
+ hook The name of the hook to check, defaults to all
59
+ """
60
+ if hook:
61
+ return self._callbacks[hook]
62
+ else:
63
+ return self._callbacks
64
+
65
+ def run_callbacks(self, hook, *args, **kwargs):
66
+ """
67
+ Loop through the registered actions and fire all callbacks
68
+ """
69
+ for logger in self._callbacks[hook]:
70
+ # print(f"Running callbacks.{logger['callback'].__name__}()")
71
+ logger['callback'](*args, **kwargs)
72
+
73
+ def on_pretrain_routine_start(self, *args, **kwargs):
74
+ """
75
+ Fires all registered callbacks at the start of each pretraining routine
76
+ """
77
+ self.run_callbacks('on_pretrain_routine_start', *args, **kwargs)
78
+
79
+ def on_pretrain_routine_end(self, *args, **kwargs):
80
+ """
81
+ Fires all registered callbacks at the end of each pretraining routine
82
+ """
83
+ self.run_callbacks('on_pretrain_routine_end', *args, **kwargs)
84
+
85
+ def on_train_start(self, *args, **kwargs):
86
+ """
87
+ Fires all registered callbacks at the start of each training
88
+ """
89
+ self.run_callbacks('on_train_start', *args, **kwargs)
90
+
91
+ def on_train_epoch_start(self, *args, **kwargs):
92
+ """
93
+ Fires all registered callbacks at the start of each training epoch
94
+ """
95
+ self.run_callbacks('on_train_epoch_start', *args, **kwargs)
96
+
97
+ def on_train_batch_start(self, *args, **kwargs):
98
+ """
99
+ Fires all registered callbacks at the start of each training batch
100
+ """
101
+ self.run_callbacks('on_train_batch_start', *args, **kwargs)
102
+
103
+ def optimizer_step(self, *args, **kwargs):
104
+ """
105
+ Fires all registered callbacks on each optimizer step
106
+ """
107
+ self.run_callbacks('optimizer_step', *args, **kwargs)
108
+
109
+ def on_before_zero_grad(self, *args, **kwargs):
110
+ """
111
+ Fires all registered callbacks before zero grad
112
+ """
113
+ self.run_callbacks('on_before_zero_grad', *args, **kwargs)
114
+
115
+ def on_train_batch_end(self, *args, **kwargs):
116
+ """
117
+ Fires all registered callbacks at the end of each training batch
118
+ """
119
+ self.run_callbacks('on_train_batch_end', *args, **kwargs)
120
+
121
+ def on_train_epoch_end(self, *args, **kwargs):
122
+ """
123
+ Fires all registered callbacks at the end of each training epoch
124
+ """
125
+ self.run_callbacks('on_train_epoch_end', *args, **kwargs)
126
+
127
+ def on_val_start(self, *args, **kwargs):
128
+ """
129
+ Fires all registered callbacks at the start of the validation
130
+ """
131
+ self.run_callbacks('on_val_start', *args, **kwargs)
132
+
133
+ def on_val_batch_start(self, *args, **kwargs):
134
+ """
135
+ Fires all registered callbacks at the start of each validation batch
136
+ """
137
+ self.run_callbacks('on_val_batch_start', *args, **kwargs)
138
+
139
+ def on_val_image_end(self, *args, **kwargs):
140
+ """
141
+ Fires all registered callbacks at the end of each val image
142
+ """
143
+ self.run_callbacks('on_val_image_end', *args, **kwargs)
144
+
145
+ def on_val_batch_end(self, *args, **kwargs):
146
+ """
147
+ Fires all registered callbacks at the end of each validation batch
148
+ """
149
+ self.run_callbacks('on_val_batch_end', *args, **kwargs)
150
+
151
+ def on_val_end(self, *args, **kwargs):
152
+ """
153
+ Fires all registered callbacks at the end of the validation
154
+ """
155
+ self.run_callbacks('on_val_end', *args, **kwargs)
156
+
157
+ def on_fit_epoch_end(self, *args, **kwargs):
158
+ """
159
+ Fires all registered callbacks at the end of each fit (train+val) epoch
160
+ """
161
+ self.run_callbacks('on_fit_epoch_end', *args, **kwargs)
162
+
163
+ def on_model_save(self, *args, **kwargs):
164
+ """
165
+ Fires all registered callbacks after each model save
166
+ """
167
+ self.run_callbacks('on_model_save', *args, **kwargs)
168
+
169
+ def on_train_end(self, *args, **kwargs):
170
+ """
171
+ Fires all registered callbacks at the end of training
172
+ """
173
+ self.run_callbacks('on_train_end', *args, **kwargs)
174
+
175
+ def teardown(self, *args, **kwargs):
176
+ """
177
+ Fires all registered callbacks before teardown
178
+ """
179
+ self.run_callbacks('teardown', *args, **kwargs)
utils/datasets.py ADDED
@@ -0,0 +1,1056 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Dataloaders and dataset utils
4
+ """
5
+
6
+ import glob
7
+ import hashlib
8
+ import json
9
+ import logging
10
+ import os
11
+ import random
12
+ import shutil
13
+ import time
14
+ from itertools import repeat
15
+ from multiprocessing.pool import ThreadPool, Pool
16
+ from pathlib import Path
17
+ from threading import Thread
18
+
19
+ import cv2
20
+ import numpy as np
21
+ import torch
22
+ import torch.nn.functional as F
23
+ import yaml
24
+ from PIL import Image, ExifTags
25
+ from torch.utils.data import Dataset
26
+ from tqdm import tqdm
27
+
28
+ from utils.augmentations import Albumentations, augment_hsv, copy_paste, letterbox, mixup, random_perspective
29
+ from utils.general import check_requirements, check_file, check_dataset, xywh2xyxy, xywhn2xyxy, xyxy2xywhn, \
30
+ xyn2xy, segments2boxes, clean_str
31
+ from utils.torch_utils import torch_distributed_zero_first
32
+
33
+ # Parameters
34
+ HELP_URL = 'https://github.com/ultralytics/yolov5/wiki/Train-Custom-Data'
35
+ IMG_FORMATS = ['bmp', 'jpg', 'jpeg', 'png', 'tif', 'tiff', 'dng', 'webp', 'mpo'] # acceptable image suffixes
36
+ VID_FORMATS = ['mov', 'avi', 'mp4', 'mpg', 'mpeg', 'm4v', 'wmv', 'mkv'] # acceptable video suffixes
37
+ NUM_THREADS = os.cpu_count() # number of multiprocessing threads
38
+
39
+
40
+ # Get orientation exif tag
41
+ for orientation in ExifTags.TAGS.keys():
42
+ if ExifTags.TAGS[orientation] == 'Orientation':
43
+ break
44
+
45
+
46
+ def get_hash(paths):
47
+ # Returns a single hash value of a list of paths (files or dirs)
48
+ size = sum(os.path.getsize(p) for p in paths if os.path.exists(p)) # sizes
49
+ h = hashlib.md5(str(size).encode()) # hash sizes
50
+ h.update(''.join(paths).encode()) # hash paths
51
+ return h.hexdigest() # return hash
52
+
53
+
54
+ def exif_size(img):
55
+ # Returns exif-corrected PIL size
56
+ s = img.size # (width, height)
57
+ try:
58
+ rotation = dict(img._getexif().items())[orientation]
59
+ if rotation == 6: # rotation 270
60
+ s = (s[1], s[0])
61
+ elif rotation == 8: # rotation 90
62
+ s = (s[1], s[0])
63
+ except:
64
+ pass
65
+
66
+ return s
67
+
68
+
69
+ def exif_transpose(image):
70
+ """
71
+ Transpose a PIL image accordingly if it has an EXIF Orientation tag.
72
+ From https://github.com/python-pillow/Pillow/blob/master/src/PIL/ImageOps.py
73
+
74
+ :param image: The image to transpose.
75
+ :return: An image.
76
+ """
77
+ exif = image.getexif()
78
+ orientation = exif.get(0x0112, 1) # default 1
79
+ if orientation > 1:
80
+ method = {2: Image.FLIP_LEFT_RIGHT,
81
+ 3: Image.ROTATE_180,
82
+ 4: Image.FLIP_TOP_BOTTOM,
83
+ 5: Image.TRANSPOSE,
84
+ 6: Image.ROTATE_270,
85
+ 7: Image.TRANSVERSE,
86
+ 8: Image.ROTATE_90,
87
+ }.get(orientation)
88
+ if method is not None:
89
+ image = image.transpose(method)
90
+ del exif[0x0112]
91
+ image.info["exif"] = exif.tobytes()
92
+ return image
93
+
94
+
95
+ def create_dataloader(path, labels_dir, imgsz, batch_size, stride, single_cls=False, hyp=None, augment=False, cache=False, pad=0.0,
96
+ rect=False, rank=-1, workers=8, image_weights=False, quad=False, prefix='',
97
+ kp_flip=None, kp_bbox=None):
98
+ # Make sure only the first process in DDP process the dataset first, and the following others can use the cache
99
+ with torch_distributed_zero_first(rank):
100
+ dataset = LoadImagesAndLabels(path, labels_dir, imgsz, batch_size,
101
+ augment=augment, # augment images
102
+ hyp=hyp, # augmentation hyperparameters
103
+ rect=rect, # rectangular training
104
+ cache_images=cache,
105
+ single_cls=single_cls,
106
+ stride=int(stride),
107
+ pad=pad,
108
+ image_weights=image_weights,
109
+ prefix=prefix,
110
+ kp_flip=kp_flip,
111
+ kp_bbox=kp_bbox)
112
+
113
+ # for i in range(10):
114
+ # dataset.__getitem__(i)
115
+ # import sys
116
+ # sys.exit()
117
+
118
+ batch_size = min(batch_size, len(dataset))
119
+ nw = min([os.cpu_count(), batch_size if batch_size > 1 else 0, workers]) # number of workers
120
+ sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None
121
+ loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader
122
+ # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()
123
+ dataloader = loader(dataset,
124
+ batch_size=batch_size,
125
+ num_workers=nw,
126
+ sampler=sampler,
127
+ pin_memory=True,
128
+ collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)
129
+ return dataloader, dataset
130
+
131
+
132
+ class InfiniteDataLoader(torch.utils.data.dataloader.DataLoader):
133
+ """ Dataloader that reuses workers
134
+
135
+ Uses same syntax as vanilla DataLoader
136
+ """
137
+
138
+ def __init__(self, *args, **kwargs):
139
+ super().__init__(*args, **kwargs)
140
+ object.__setattr__(self, 'batch_sampler', _RepeatSampler(self.batch_sampler))
141
+ self.iterator = super().__iter__()
142
+
143
+ def __len__(self):
144
+ return len(self.batch_sampler.sampler)
145
+
146
+ def __iter__(self):
147
+ for i in range(len(self)):
148
+ yield next(self.iterator)
149
+
150
+
151
+ class _RepeatSampler(object):
152
+ """ Sampler that repeats forever
153
+
154
+ Args:
155
+ sampler (Sampler)
156
+ """
157
+
158
+ def __init__(self, sampler):
159
+ self.sampler = sampler
160
+
161
+ def __iter__(self):
162
+ while True:
163
+ yield from iter(self.sampler)
164
+
165
+
166
+ class LoadImages: # for inference
167
+ def __init__(self, path, img_size=640, stride=32, auto=True):
168
+ p = str(Path(path).absolute()) # os-agnostic absolute path
169
+ if p.endswith('.txt'):
170
+ with open(p, 'r') as f:
171
+ files = f.readlines()
172
+ files = [l.strip() for l in files]
173
+ elif '*' in p:
174
+ files = sorted(glob.glob(p, recursive=True)) # glob
175
+ elif os.path.isdir(p):
176
+ files = sorted(glob.glob(os.path.join(p, '*.*'))) # dir
177
+ elif os.path.isfile(p):
178
+ files = [p] # files
179
+ else:
180
+ raise Exception(f'ERROR: {p} does not exist')
181
+
182
+ images = [x for x in files if x.split('.')[-1].lower() in IMG_FORMATS]
183
+ videos = [x for x in files if x.split('.')[-1].lower() in VID_FORMATS]
184
+ ni, nv = len(images), len(videos)
185
+
186
+ self.img_size = img_size
187
+ self.stride = stride
188
+ self.files = images + videos
189
+ self.nf = ni + nv # number of files
190
+ self.video_flag = [False] * ni + [True] * nv
191
+ self.mode = 'image'
192
+ self.auto = auto
193
+ if any(videos):
194
+ self.new_video(videos[0]) # new video
195
+ else:
196
+ self.cap = None
197
+ assert self.nf > 0, f'No images or videos found in {p}. ' \
198
+ f'Supported formats are:\nimages: {IMG_FORMATS}\nvideos: {VID_FORMATS}'
199
+
200
+ def __iter__(self):
201
+ self.count = 0
202
+ return self
203
+
204
+ def __next__(self):
205
+ if self.count == self.nf:
206
+ raise StopIteration
207
+ path = self.files[self.count]
208
+
209
+ if self.video_flag[self.count]:
210
+ # Read video
211
+ self.mode = 'video'
212
+ ret_val, img0 = self.cap.read()
213
+ if not ret_val:
214
+ self.count += 1
215
+ self.cap.release()
216
+ if self.count == self.nf: # last video
217
+ raise StopIteration
218
+ else:
219
+ path = self.files[self.count]
220
+ self.new_video(path)
221
+ ret_val, img0 = self.cap.read()
222
+
223
+ self.frame += 1
224
+ # print(f'video {self.count + 1}/{self.nf} ({self.frame}/{self.frames}) {path}: ', end='')
225
+
226
+ else:
227
+ # Read image
228
+ self.count += 1
229
+ img0 = cv2.imread(path) # BGR
230
+ assert img0 is not None, 'Image Not Found ' + path
231
+ print(f'image {self.count}/{self.nf} {path}: ', end='')
232
+
233
+ # Padded resize
234
+ img = letterbox(img0, self.img_size, stride=self.stride, auto=self.auto)[0]
235
+
236
+ # Convert
237
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
238
+ img = np.ascontiguousarray(img)
239
+
240
+ return path, img, img0, self.cap
241
+
242
+ def new_video(self, path):
243
+ self.frame = 0
244
+ self.cap = cv2.VideoCapture(path)
245
+ self.frames = int(self.cap.get(cv2.CAP_PROP_FRAME_COUNT))
246
+
247
+ def __len__(self):
248
+ return self.nf # number of files
249
+
250
+
251
+ class LoadWebcam: # for inference
252
+ def __init__(self, pipe='0', img_size=640, stride=32):
253
+ self.img_size = img_size
254
+ self.stride = stride
255
+ self.pipe = eval(pipe) if pipe.isnumeric() else pipe
256
+ self.cap = cv2.VideoCapture(self.pipe) # video capture object
257
+ self.cap.set(cv2.CAP_PROP_BUFFERSIZE, 3) # set buffer size
258
+
259
+ def __iter__(self):
260
+ self.count = -1
261
+ return self
262
+
263
+ def __next__(self):
264
+ self.count += 1
265
+ if cv2.waitKey(1) == ord('q'): # q to quit
266
+ self.cap.release()
267
+ cv2.destroyAllWindows()
268
+ raise StopIteration
269
+
270
+ # Read frame
271
+ ret_val, img0 = self.cap.read()
272
+ img0 = cv2.flip(img0, 1) # flip left-right
273
+
274
+ # Print
275
+ assert ret_val, f'Camera Error {self.pipe}'
276
+ img_path = 'webcam.jpg'
277
+ print(f'webcam {self.count}: ', end='')
278
+
279
+ # Padded resize
280
+ img = letterbox(img0, self.img_size, stride=self.stride)[0]
281
+
282
+ # Convert
283
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
284
+ img = np.ascontiguousarray(img)
285
+
286
+ return img_path, img, img0, None
287
+
288
+ def __len__(self):
289
+ return 0
290
+
291
+
292
+ class LoadStreams: # multiple IP or RTSP cameras
293
+ def __init__(self, sources='streams.txt', img_size=640, stride=32, auto=True):
294
+ self.mode = 'stream'
295
+ self.img_size = img_size
296
+ self.stride = stride
297
+
298
+ if os.path.isfile(sources):
299
+ with open(sources, 'r') as f:
300
+ sources = [x.strip() for x in f.read().strip().splitlines() if len(x.strip())]
301
+ else:
302
+ sources = [sources]
303
+
304
+ n = len(sources)
305
+ self.imgs, self.fps, self.frames, self.threads = [None] * n, [0] * n, [0] * n, [None] * n
306
+ self.sources = [clean_str(x) for x in sources] # clean source names for later
307
+ self.auto = auto
308
+ for i, s in enumerate(sources): # index, source
309
+ # Start thread to read frames from video stream
310
+ print(f'{i + 1}/{n}: {s}... ', end='')
311
+ if 'youtube.com/' in s or 'youtu.be/' in s: # if source is YouTube video
312
+ check_requirements(('pafy', 'youtube_dl'))
313
+ import pafy
314
+ s = pafy.new(s).getbest(preftype="mp4").url # YouTube URL
315
+ s = eval(s) if s.isnumeric() else s # i.e. s = '0' local webcam
316
+ cap = cv2.VideoCapture(s)
317
+ assert cap.isOpened(), f'Failed to open {s}'
318
+ w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
319
+ h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
320
+ self.fps[i] = max(cap.get(cv2.CAP_PROP_FPS) % 100, 0) or 30.0 # 30 FPS fallback
321
+ self.frames[i] = max(int(cap.get(cv2.CAP_PROP_FRAME_COUNT)), 0) or float('inf') # infinite stream fallback
322
+
323
+ _, self.imgs[i] = cap.read() # guarantee first frame
324
+ self.threads[i] = Thread(target=self.update, args=([i, cap]), daemon=True)
325
+ print(f" success ({self.frames[i]} frames {w}x{h} at {self.fps[i]:.2f} FPS)")
326
+ self.threads[i].start()
327
+ print('') # newline
328
+
329
+ # check for common shapes
330
+ s = np.stack([letterbox(x, self.img_size, stride=self.stride, auto=self.auto)[0].shape for x in self.imgs])
331
+ self.rect = np.unique(s, axis=0).shape[0] == 1 # rect inference if all shapes equal
332
+ if not self.rect:
333
+ print('WARNING: Different stream shapes detected. For optimal performance supply similarly-shaped streams.')
334
+
335
+ def update(self, i, cap):
336
+ # Read stream `i` frames in daemon thread
337
+ n, f, read = 0, self.frames[i], 1 # frame number, frame array, inference every 'read' frame
338
+ while cap.isOpened() and n < f:
339
+ n += 1
340
+ # _, self.imgs[index] = cap.read()
341
+ cap.grab()
342
+ if n % read == 0:
343
+ success, im = cap.retrieve()
344
+ self.imgs[i] = im if success else self.imgs[i] * 0
345
+ time.sleep(1 / self.fps[i]) # wait time
346
+
347
+ def __iter__(self):
348
+ self.count = -1
349
+ return self
350
+
351
+ def __next__(self):
352
+ self.count += 1
353
+ if not all(x.is_alive() for x in self.threads) or cv2.waitKey(1) == ord('q'): # q to quit
354
+ cv2.destroyAllWindows()
355
+ raise StopIteration
356
+
357
+ # Letterbox
358
+ img0 = self.imgs.copy()
359
+ img = [letterbox(x, self.img_size, stride=self.stride, auto=self.rect and self.auto)[0] for x in img0]
360
+
361
+ # Stack
362
+ img = np.stack(img, 0)
363
+
364
+ # Convert
365
+ img = img[..., ::-1].transpose((0, 3, 1, 2)) # BGR to RGB, BHWC to BCHW
366
+ img = np.ascontiguousarray(img)
367
+
368
+ return self.sources, img, img0, None
369
+
370
+ def __len__(self):
371
+ return len(self.sources) # 1E12 frames = 32 streams at 30 FPS for 30 years
372
+
373
+
374
+ def img2label_paths(img_paths, image_dir='images', labels_dir='labels'):
375
+ return [os.path.splitext(s.replace(image_dir, labels_dir))[0] + '.txt' for s in img_paths]
376
+
377
+
378
+ class LoadImagesAndLabels(Dataset): # for training/testing
379
+ def __init__(self, path, labels_dir='labels', img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,
380
+ cache_images=False, single_cls=False, stride=32, pad=0.0, prefix='',
381
+ kp_flip=None, kp_bbox=None):
382
+ self.labels_dir = labels_dir
383
+ self.img_size = img_size
384
+ self.augment = augment
385
+ self.hyp = hyp
386
+ self.image_weights = image_weights
387
+ self.rect = False if image_weights else rect
388
+ self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)
389
+ self.mosaic_border = [-img_size // 2, -img_size // 2]
390
+ self.stride = stride
391
+ self.path = path
392
+ self.albumentations = Albumentations() if augment else None
393
+ self.kp_flip = kp_flip
394
+ self.kp_bbox = kp_bbox
395
+ self.num_coords = len(kp_flip) * 2
396
+
397
+ if self.kp_flip:
398
+ self.obj_flip = {0: 0}
399
+ for i in range(len(self.kp_flip)):
400
+ self.obj_flip[i + 1] = self.kp_flip[i] + 1
401
+ else:
402
+ self.obj_flip = None
403
+
404
+ try:
405
+ f = [] # image files
406
+ for p in path if isinstance(path, list) else [path]:
407
+ p = Path(p) # os-agnostic
408
+ if p.is_dir(): # dir
409
+ f += glob.glob(str(p / '**' / '*.*'), recursive=True)
410
+ # f = list(p.rglob('**/*.*')) # pathlib
411
+ elif p.is_file(): # file
412
+ with open(p, 'r') as t:
413
+ t = t.read().strip().splitlines()
414
+ parent = str(p.parent) + os.sep
415
+ f += [x.replace('./', parent) if x.startswith('./') else x for x in t] # local to global path
416
+ # f += [p.parent / x.lstrip(os.sep) for x in t] # local to global path (pathlib)
417
+ else:
418
+ raise Exception(f'{prefix}{p} does not exist')
419
+ self.img_files = sorted([x.replace('/', os.sep) for x in f if x.split('.')[-1].lower() in IMG_FORMATS])
420
+ # self.img_files = sorted([x for x in f if x.suffix[1:].lower() in img_formats]) # pathlib
421
+ assert self.img_files, f'{prefix}No images found'
422
+ except Exception as e:
423
+ raise Exception(f'{prefix}Error loading data from {path}: {e}\nSee {HELP_URL}')
424
+
425
+ # Check cache
426
+ self.label_files = img2label_paths(self.img_files, labels_dir=self.labels_dir) # labels
427
+ cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache')
428
+ try:
429
+ cache, exists = np.load(cache_path, allow_pickle=True).item(), True # load dict
430
+ assert cache['version'] == 0.4 and cache['hash'] == get_hash(self.label_files + self.img_files)
431
+ except:
432
+ cache, exists = self.cache_labels(cache_path, prefix), False # cache
433
+
434
+ # Display cache
435
+ nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total
436
+ if exists:
437
+ d = f"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted"
438
+ tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results
439
+ if cache['msgs']:
440
+ logging.info('\n'.join(cache['msgs'])) # display warnings
441
+ assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {HELP_URL}'
442
+
443
+ # Read cache
444
+ [cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
445
+ labels, shapes, self.segments = zip(*cache.values())
446
+ self.labels = list(labels)
447
+ self.shapes = np.array(shapes, dtype=np.float64)
448
+ self.img_files = list(cache.keys()) # update
449
+ self.label_files = img2label_paths(cache.keys(), labels_dir=self.labels_dir) # update
450
+ if single_cls:
451
+ for x in self.labels:
452
+ x[:, 0] = 0
453
+
454
+ n = len(shapes) # number of images
455
+ bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index
456
+ nb = bi[-1] + 1 # number of batches
457
+ self.batch = bi # batch index of image
458
+ self.n = n
459
+ self.indices = range(n)
460
+
461
+ # Rectangular Training
462
+ if self.rect:
463
+ # Sort by aspect ratio
464
+ s = self.shapes # wh
465
+ ar = s[:, 1] / s[:, 0] # aspect ratio
466
+ irect = ar.argsort()
467
+ self.img_files = [self.img_files[i] for i in irect]
468
+ self.label_files = [self.label_files[i] for i in irect]
469
+ self.labels = [self.labels[i] for i in irect]
470
+ self.shapes = s[irect] # wh
471
+ ar = ar[irect]
472
+
473
+ # Set training image shapes
474
+ shapes = [[1, 1]] * nb
475
+ for i in range(nb):
476
+ ari = ar[bi == i]
477
+ mini, maxi = ari.min(), ari.max()
478
+ if maxi < 1:
479
+ shapes[i] = [maxi, 1]
480
+ elif mini > 1:
481
+ shapes[i] = [1, 1 / mini]
482
+
483
+ self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride
484
+
485
+ # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)
486
+ self.imgs, self.img_npy = [None] * n, [None] * n
487
+ if cache_images:
488
+ if cache_images == 'disk':
489
+ self.im_cache_dir = Path(Path(self.img_files[0]).parent.as_posix() + '_npy')
490
+ self.img_npy = [self.im_cache_dir / Path(f).with_suffix('.npy').name for f in self.img_files]
491
+ self.im_cache_dir.mkdir(parents=True, exist_ok=True)
492
+ gb = 0 # Gigabytes of cached images
493
+ self.img_hw0, self.img_hw = [None] * n, [None] * n
494
+ results = ThreadPool(NUM_THREADS).imap(lambda x: load_image(*x), zip(repeat(self), range(n)))
495
+ pbar = tqdm(enumerate(results), total=n)
496
+ for i, x in pbar:
497
+ if cache_images == 'disk':
498
+ if not self.img_npy[i].exists():
499
+ np.save(self.img_npy[i].as_posix(), x[0])
500
+ gb += self.img_npy[i].stat().st_size
501
+ else:
502
+ self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # im, hw_orig, hw_resized = load_image(self, i)
503
+ gb += self.imgs[i].nbytes
504
+ pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB {cache_images})'
505
+ pbar.close()
506
+
507
+ def cache_labels(self, path=Path('./labels.cache'), prefix=''):
508
+ # Cache dataset labels, check images and read shapes
509
+ x = {} # dict
510
+ nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
511
+ desc = f"{prefix}Scanning '{path.parent / path.stem}' images and labels..."
512
+ with Pool(NUM_THREADS) as pool:
513
+ pbar = tqdm(pool.imap_unordered(verify_image_label, zip(self.img_files, self.label_files, repeat(prefix), repeat(self.num_coords))),
514
+ desc=desc, total=len(self.img_files))
515
+ for im_file, l, shape, segments, nm_f, nf_f, ne_f, nc_f, msg in pbar:
516
+ nm += nm_f
517
+ nf += nf_f
518
+ ne += ne_f
519
+ nc += nc_f
520
+ if im_file:
521
+ x[im_file] = [l, shape, segments]
522
+ if msg:
523
+ msgs.append(msg)
524
+ pbar.desc = f"{desc}{nf} found, {nm} missing, {ne} empty, {nc} corrupted"
525
+
526
+ pbar.close()
527
+ if msgs:
528
+ logging.info('\n'.join(msgs))
529
+ if nf == 0:
530
+ logging.info(f'{prefix}WARNING: No labels found in {path}. See {HELP_URL}')
531
+ x['hash'] = get_hash(self.label_files + self.img_files)
532
+ x['results'] = nf, nm, ne, nc, len(self.img_files)
533
+ x['msgs'] = msgs # warnings
534
+ x['version'] = 0.4 # cache version
535
+ try:
536
+ np.save(path, x) # save cache for next time
537
+ path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
538
+ logging.info(f'{prefix}New cache created: {path}')
539
+ except Exception as e:
540
+ logging.info(f'{prefix}WARNING: Cache directory {path.parent} is not writeable: {e}') # path not writeable
541
+ return x
542
+
543
+ def __len__(self):
544
+ return len(self.img_files)
545
+
546
+ # def __iter__(self):
547
+ # self.count = -1
548
+ # print('ran dataset iter')
549
+ # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)
550
+ # return self
551
+
552
+ def __getitem__(self, index):
553
+ index = self.indices[index] # linear, shuffled, or image_weights
554
+
555
+ hyp = self.hyp
556
+ mosaic = self.mosaic and random.random() < hyp['mosaic']
557
+ if mosaic:
558
+ # Load mosaic
559
+ img, labels = load_mosaic(self, index, kp_bbox=self.kp_bbox)
560
+ shapes = None
561
+
562
+ # MixUp augmentation
563
+ if random.random() < hyp['mixup']:
564
+ img, labels = mixup(img, labels, *load_mosaic(self, random.randint(0, self.n - 1)))
565
+
566
+ else:
567
+ # Load image
568
+ img, (h0, w0), (h, w) = load_image(self, index)
569
+
570
+ # Letterbox
571
+ shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape
572
+ img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)
573
+ shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling
574
+
575
+ labels = self.labels[index].copy()
576
+ if labels.size: # normalized xywh to pixel xyxy format
577
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])
578
+
579
+ if self.augment:
580
+ img, labels = random_perspective(img, labels,
581
+ degrees=hyp['degrees'],
582
+ translate=hyp['translate'],
583
+ scale=hyp['scale'],
584
+ shear=hyp['shear'],
585
+ perspective=hyp['perspective'],
586
+ kp_bbox=self.kp_bbox)
587
+
588
+ nl = len(labels) # number of labels
589
+ if nl:
590
+ labels[:, 1:] = xyxy2xywhn(labels[:, 1:], w=img.shape[1], h=img.shape[0], clip=True, eps=1E-3)
591
+
592
+ if self.augment:
593
+ # Albumentations
594
+ img, labels = self.albumentations(img, labels)
595
+ nl = len(labels) # update after albumentations
596
+
597
+ # HSV color-space
598
+ augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])
599
+
600
+ # Flip up-down
601
+ if random.random() < hyp['flipud']:
602
+ img = np.flipud(img)
603
+ if nl:
604
+ labels[:, 2] = 1 - labels[:, 2]
605
+
606
+ # Flip left-right
607
+ if random.random() < hyp['fliplr']:
608
+ img = np.fliplr(img)
609
+ if nl:
610
+ labels[:, 1] = 1 - labels[:, 1]
611
+
612
+ if self.kp_flip and labels.shape[1] > 5:
613
+ labels[:, 5::3] = 1 - labels[:, 5::3] # flip keypoints in person object
614
+ keypoints = labels[:, 5:].reshape(nl, -1, 3)
615
+ keypoints = keypoints[:, self.kp_flip] # reorder left / right keypoints
616
+ labels[:, 5:] = keypoints.reshape(nl, -1)
617
+
618
+ if self.obj_flip:
619
+ for i, cls in enumerate(labels[:, 0]):
620
+ labels[i, 0] = self.obj_flip[labels[i, 0]]
621
+
622
+ # Cutouts
623
+ # labels = cutout(img, labels, p=0.5)
624
+
625
+ # img_h, img_w = img.shape[:2]
626
+ # img = img.copy()
627
+ # person_obj = labels[labels[:, 0] == 0]
628
+ # for lbl in person_obj:
629
+ # xc, yc, w, h = lbl[1:5].copy()
630
+ # pt1 = (int((xc - w / 2) * img_w), int((yc - h / 2) * img_h))
631
+ # pt2 = (int((xc + w / 2) * img_w), int((yc + h / 2) * img_h))
632
+ # cv2.rectangle(img, pt1, pt2, (255, 0, 255), thickness=2)
633
+ #
634
+ # kp = lbl[5:]
635
+ # kp = np.array(kp).reshape(-1, 3)
636
+ # kp[:, 0] = kp[:, 0] * img_w
637
+ # kp[:, 1] = kp[:, 1] * img_h
638
+ # for i, (x, y, v) in enumerate(kp):
639
+ # if v:
640
+ # if i in COCO_KP_LEFT:
641
+ # color = (0, 255, 255)
642
+ # else:
643
+ # color = (255, 255, 0)
644
+ # cv2.circle(img, (int(round(x)), int(round(y))), 2, color, thickness=2)
645
+ # # cv2.putText(img, COCO_KP_NAMES_SHORT[i], (int(round(x + 10)), int(round(y + 10))),
646
+ # # cv2.FONT_HERSHEY_PLAIN, 1, (255, 255, 0), thickness=1)
647
+ # cv2.imshow('', img)
648
+ # cv2.waitKey(0)
649
+ # cv2.destroyAllWindows()
650
+
651
+ labels_out = torch.zeros((nl, labels.shape[-1] + 1))
652
+ if nl:
653
+ labels_out[:, 1:] = torch.from_numpy(labels)
654
+ # Convert
655
+ img = img.transpose((2, 0, 1))[::-1] # HWC to CHW, BGR to RGB
656
+ img = np.ascontiguousarray(img)
657
+
658
+ return torch.from_numpy(img), labels_out, self.img_files[index], shapes
659
+
660
+ @staticmethod
661
+ def collate_fn(batch):
662
+ img, label, path, shapes = zip(*batch) # transposed
663
+ for i, l in enumerate(label):
664
+ l[:, 0] = i # add target image index for build_targets()
665
+ return torch.stack(img, 0), torch.cat(label, 0), path, shapes
666
+
667
+ @staticmethod
668
+ def collate_fn4(batch):
669
+ img, label, path, shapes = zip(*batch) # transposed
670
+ n = len(shapes) // 4
671
+ img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]
672
+
673
+ ho = torch.tensor([[0., 0, 0, 1, 0, 0]])
674
+ wo = torch.tensor([[0., 0, 1, 0, 0, 0]])
675
+ s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale
676
+ for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW
677
+ i *= 4
678
+ if random.random() < 0.5:
679
+ im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[
680
+ 0].type(img[i].type())
681
+ l = label[i]
682
+ else:
683
+ im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)
684
+ l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s
685
+ img4.append(im)
686
+ label4.append(l)
687
+
688
+ for i, l in enumerate(label4):
689
+ l[:, 0] = i # add target image index for build_targets()
690
+
691
+ return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4
692
+
693
+
694
+ # Ancillary functions --------------------------------------------------------------------------------------------------
695
+ def load_image(self, i):
696
+ # loads 1 image from dataset index 'i', returns im, original hw, resized hw
697
+ im = self.imgs[i]
698
+ if im is None: # not cached in ram
699
+ npy = self.img_npy[i]
700
+ if npy and npy.exists(): # load npy
701
+ im = np.load(npy)
702
+ else: # read image
703
+ path = self.img_files[i]
704
+ im = cv2.imread(path) # BGR
705
+ assert im is not None, 'Image Not Found ' + path
706
+ h0, w0 = im.shape[:2] # orig hw
707
+ r = self.img_size / max(h0, w0) # ratio
708
+ if r != 1: # if sizes are not equal
709
+ im = cv2.resize(im, (int(w0 * r), int(h0 * r)),
710
+ interpolation=cv2.INTER_AREA if r < 1 and not self.augment else cv2.INTER_LINEAR)
711
+ return im, (h0, w0), im.shape[:2] # im, hw_original, hw_resized
712
+ else:
713
+ return self.imgs[i], self.img_hw0[i], self.img_hw[i] # im, hw_original, hw_resized
714
+
715
+
716
+ def load_mosaic(self, index, kp_bbox=None):
717
+ # loads images in a 4-mosaic
718
+
719
+ labels4, segments4 = [], []
720
+ s = self.img_size
721
+ yc, xc = [int(random.uniform(-x, 2 * s + x)) for x in self.mosaic_border] # mosaic center x, y
722
+ indices = [index] + random.choices(self.indices, k=3) # 3 additional image indices
723
+ for i, index in enumerate(indices):
724
+ # Load image
725
+ img, _, (h, w) = load_image(self, index)
726
+
727
+ # place img in img4
728
+ if i == 0: # top left
729
+ img4 = np.full((s * 2, s * 2, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
730
+ x1a, y1a, x2a, y2a = max(xc - w, 0), max(yc - h, 0), xc, yc # xmin, ymin, xmax, ymax (large image)
731
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), h - (y2a - y1a), w, h # xmin, ymin, xmax, ymax (small image)
732
+ elif i == 1: # top right
733
+ x1a, y1a, x2a, y2a = xc, max(yc - h, 0), min(xc + w, s * 2), yc
734
+ x1b, y1b, x2b, y2b = 0, h - (y2a - y1a), min(w, x2a - x1a), h
735
+ elif i == 2: # bottom left
736
+ x1a, y1a, x2a, y2a = max(xc - w, 0), yc, xc, min(s * 2, yc + h)
737
+ x1b, y1b, x2b, y2b = w - (x2a - x1a), 0, w, min(y2a - y1a, h)
738
+ elif i == 3: # bottom right
739
+ x1a, y1a, x2a, y2a = xc, yc, min(xc + w, s * 2), min(s * 2, yc + h)
740
+ x1b, y1b, x2b, y2b = 0, 0, min(w, x2a - x1a), min(y2a - y1a, h)
741
+
742
+ img4[y1a:y2a, x1a:x2a] = img[y1b:y2b, x1b:x2b] # img4[ymin:ymax, xmin:xmax]
743
+ padw = x1a - x1b
744
+ padh = y1a - y1b
745
+
746
+ # Labels
747
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
748
+ if labels.size:
749
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padw, padh) # normalized xywh to pixel xyxy format
750
+ segments = [xyn2xy(x, w, h, padw, padh) for x in segments]
751
+ labels4.append(labels)
752
+ segments4.extend(segments)
753
+
754
+ # Concat/clip labels
755
+ labels4 = np.concatenate(labels4, 0)
756
+ for x in (labels4[:, 1:], *segments4):
757
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
758
+ # img4, labels4 = replicate(img4, labels4) # replicate
759
+
760
+ # Augment
761
+ img4, labels4, segments4 = copy_paste(img4, labels4, segments4, p=self.hyp['copy_paste'])
762
+ img4, labels4 = random_perspective(img4, labels4, segments4,
763
+ degrees=self.hyp['degrees'],
764
+ translate=self.hyp['translate'],
765
+ scale=self.hyp['scale'],
766
+ shear=self.hyp['shear'],
767
+ perspective=self.hyp['perspective'],
768
+ border=self.mosaic_border,
769
+ kp_bbox=kp_bbox) # border to remove
770
+
771
+ return img4, labels4
772
+
773
+
774
+ def load_mosaic9(self, index):
775
+ # loads images in a 9-mosaic
776
+
777
+ labels9, segments9 = [], []
778
+ s = self.img_size
779
+ indices = [index] + random.choices(self.indices, k=8) # 8 additional image indices
780
+ for i, index in enumerate(indices):
781
+ # Load image
782
+ img, _, (h, w) = load_image(self, index)
783
+
784
+ # place img in img9
785
+ if i == 0: # center
786
+ img9 = np.full((s * 3, s * 3, img.shape[2]), 114, dtype=np.uint8) # base image with 4 tiles
787
+ h0, w0 = h, w
788
+ c = s, s, s + w, s + h # xmin, ymin, xmax, ymax (base) coordinates
789
+ elif i == 1: # top
790
+ c = s, s - h, s + w, s
791
+ elif i == 2: # top right
792
+ c = s + wp, s - h, s + wp + w, s
793
+ elif i == 3: # right
794
+ c = s + w0, s, s + w0 + w, s + h
795
+ elif i == 4: # bottom right
796
+ c = s + w0, s + hp, s + w0 + w, s + hp + h
797
+ elif i == 5: # bottom
798
+ c = s + w0 - w, s + h0, s + w0, s + h0 + h
799
+ elif i == 6: # bottom left
800
+ c = s + w0 - wp - w, s + h0, s + w0 - wp, s + h0 + h
801
+ elif i == 7: # left
802
+ c = s - w, s + h0 - h, s, s + h0
803
+ elif i == 8: # top left
804
+ c = s - w, s + h0 - hp - h, s, s + h0 - hp
805
+
806
+ padx, pady = c[:2]
807
+ x1, y1, x2, y2 = [max(x, 0) for x in c] # allocate coords
808
+
809
+ # Labels
810
+ labels, segments = self.labels[index].copy(), self.segments[index].copy()
811
+ if labels.size:
812
+ labels[:, 1:] = xywhn2xyxy(labels[:, 1:], w, h, padx, pady) # normalized xywh to pixel xyxy format
813
+ segments = [xyn2xy(x, w, h, padx, pady) for x in segments]
814
+ labels9.append(labels)
815
+ segments9.extend(segments)
816
+
817
+ # Image
818
+ img9[y1:y2, x1:x2] = img[y1 - pady:, x1 - padx:] # img9[ymin:ymax, xmin:xmax]
819
+ hp, wp = h, w # height, width previous
820
+
821
+ # Offset
822
+ yc, xc = [int(random.uniform(0, s)) for _ in self.mosaic_border] # mosaic center x, y
823
+ img9 = img9[yc:yc + 2 * s, xc:xc + 2 * s]
824
+
825
+ # Concat/clip labels
826
+ labels9 = np.concatenate(labels9, 0)
827
+ labels9[:, [1, 3]] -= xc
828
+ labels9[:, [2, 4]] -= yc
829
+ c = np.array([xc, yc]) # centers
830
+ segments9 = [x - c for x in segments9]
831
+
832
+ for x in (labels9[:, 1:], *segments9):
833
+ np.clip(x, 0, 2 * s, out=x) # clip when using random_perspective()
834
+ # img9, labels9 = replicate(img9, labels9) # replicate
835
+
836
+ # Augment
837
+ img9, labels9 = random_perspective(img9, labels9, segments9,
838
+ degrees=self.hyp['degrees'],
839
+ translate=self.hyp['translate'],
840
+ scale=self.hyp['scale'],
841
+ shear=self.hyp['shear'],
842
+ perspective=self.hyp['perspective'],
843
+ border=self.mosaic_border) # border to remove
844
+
845
+ return img9, labels9
846
+
847
+
848
+ def create_folder(path='./new'):
849
+ # Create folder
850
+ if os.path.exists(path):
851
+ shutil.rmtree(path) # delete output folder
852
+ os.makedirs(path) # make new output folder
853
+
854
+
855
+ def flatten_recursive(path='../datasets/coco128'):
856
+ # Flatten a recursive directory by bringing all files to top level
857
+ new_path = Path(path + '_flat')
858
+ create_folder(new_path)
859
+ for file in tqdm(glob.glob(str(Path(path)) + '/**/*.*', recursive=True)):
860
+ shutil.copyfile(file, new_path / Path(file).name)
861
+
862
+
863
+ def extract_boxes(path='../datasets/coco128', labels_dir='labels'): # from utils.datasets import *; extract_boxes()
864
+ # Convert detection dataset into classification dataset, with one directory per class
865
+ path = Path(path) # images dir
866
+ shutil.rmtree(path / 'classifier') if (path / 'classifier').is_dir() else None # remove existing
867
+ files = list(path.rglob('*.*'))
868
+ n = len(files) # number of files
869
+ for im_file in tqdm(files, total=n):
870
+ if im_file.suffix[1:] in IMG_FORMATS:
871
+ # image
872
+ im = cv2.imread(str(im_file))[..., ::-1] # BGR to RGB
873
+ h, w = im.shape[:2]
874
+
875
+ # labels
876
+ lb_file = Path(img2label_paths([str(im_file)], labels_dir=labels_dir)[0])
877
+ if Path(lb_file).exists():
878
+ with open(lb_file, 'r') as f:
879
+ lb = np.array([x.split() for x in f.read().strip().splitlines()], dtype=np.float32) # labels
880
+
881
+ for j, x in enumerate(lb):
882
+ c = int(x[0]) # class
883
+ f = (path / 'classifier') / f'{c}' / f'{path.stem}_{im_file.stem}_{j}.jpg' # new filename
884
+ if not f.parent.is_dir():
885
+ f.parent.mkdir(parents=True)
886
+
887
+ b = x[1:] * [w, h, w, h] # box
888
+ # b[2:] = b[2:].max() # rectangle to square
889
+ b[2:] = b[2:] * 1.2 + 3 # pad
890
+ b = xywh2xyxy(b.reshape(-1, 4)).ravel().astype(np.int)
891
+
892
+ b[[0, 2]] = np.clip(b[[0, 2]], 0, w) # clip boxes outside of image
893
+ b[[1, 3]] = np.clip(b[[1, 3]], 0, h)
894
+ assert cv2.imwrite(str(f), im[b[1]:b[3], b[0]:b[2]]), f'box failure in {f}'
895
+
896
+
897
+ def autosplit(path='../datasets/coco128/images', weights=(0.9, 0.1, 0.0), annotated_only=False, labels_dir='labels_dir'):
898
+ """ Autosplit a dataset into train/val/test splits and save path/autosplit_*.txt files
899
+ Usage: from utils.datasets import *; autosplit()
900
+ Arguments
901
+ path: Path to images directory
902
+ weights: Train, val, test weights (list, tuple)
903
+ annotated_only: Only use images with an annotated txt file
904
+ """
905
+ path = Path(path) # images dir
906
+ files = sum([list(path.rglob(f"*.{img_ext}")) for img_ext in IMG_FORMATS], []) # image files only
907
+ n = len(files) # number of files
908
+ random.seed(0) # for reproducibility
909
+ indices = random.choices([0, 1, 2], weights=weights, k=n) # assign each image to a split
910
+
911
+ txt = ['autosplit_train.txt', 'autosplit_val.txt', 'autosplit_test.txt'] # 3 txt files
912
+ [(path.parent / x).unlink(missing_ok=True) for x in txt] # remove existing
913
+
914
+ print(f'Autosplitting images from {path}' + ', using *.txt labeled images only' * annotated_only)
915
+ for i, img in tqdm(zip(indices, files), total=n):
916
+ if not annotated_only or Path(img2label_paths([str(img)], labels_dir='labels_dir')[0]).exists(): # check label
917
+ with open(path.parent / txt[i], 'a') as f:
918
+ f.write('./' + img.relative_to(path.parent).as_posix() + '\n') # add image to txt file
919
+
920
+
921
+ def verify_image_label(args):
922
+ # Verify one image-label pair
923
+ im_file, lb_file, prefix, num_coords = args
924
+ nm, nf, ne, nc, msg, segments = 0, 0, 0, 0, '', [] # number (missing, found, empty, corrupt), message, segments
925
+ try:
926
+ # verify images
927
+ im = Image.open(im_file)
928
+ im.verify() # PIL verify
929
+ shape = exif_size(im) # image size
930
+ assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'
931
+ assert im.format.lower() in IMG_FORMATS, f'invalid image format {im.format}'
932
+ if im.format.lower() in ('jpg', 'jpeg'):
933
+ with open(im_file, 'rb') as f:
934
+ f.seek(-2, 2)
935
+ if f.read() != b'\xff\xd9': # corrupt JPEG
936
+ Image.open(im_file).save(im_file, format='JPEG', subsampling=0, quality=100) # re-save image
937
+ msg = f'{prefix}WARNING: corrupt JPEG restored and saved {im_file}'
938
+
939
+ # verify labels
940
+ if os.path.isfile(lb_file):
941
+ nf = 1 # label found
942
+ with open(lb_file, 'r') as f:
943
+ l = [x.split() for x in f.read().strip().splitlines() if len(x)]
944
+ # if any([len(x) > 8 for x in l]): # is segment
945
+ # classes = np.array([x[0] for x in l], dtype=np.float32)
946
+ # segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)
947
+ # l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)
948
+ l = np.array(l, dtype=np.float32)
949
+ if len(l):
950
+ # assert l.shape[1] == 5, 'labels require 5 columns each'
951
+ assert (l >= 0).all(), 'negative labels'
952
+ # assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'
953
+ # assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'
954
+ else:
955
+ ne = 1 # label empty
956
+ l = np.zeros((0, 5 + num_coords * 3 // 2), dtype=np.float32)
957
+ else:
958
+ nm = 1 # label missing
959
+ l = np.zeros((0, 5 + num_coords * 3 // 2), dtype=np.float32)
960
+ return im_file, l, shape, segments, nm, nf, ne, nc, msg
961
+ except Exception as e:
962
+ nc = 1
963
+ msg = f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}'
964
+ return [None, None, None, None, nm, nf, ne, nc, msg]
965
+
966
+
967
+ def dataset_stats(path='coco128.yaml', autodownload=False, verbose=False, profile=False, hub=False, labels_dir='labels'):
968
+ """ Return dataset statistics dictionary with images and instances counts per split per class
969
+ To run in parent directory: export PYTHONPATH="$PWD/yolov5"
970
+ Usage1: from utils.datasets import *; dataset_stats('coco128.yaml', autodownload=True)
971
+ Usage2: from utils.datasets import *; dataset_stats('../datasets/coco128_with_yaml.zip')
972
+ Arguments
973
+ path: Path to data.yaml or data.zip (with data.yaml inside data.zip)
974
+ autodownload: Attempt to download dataset if not found locally
975
+ verbose: Print stats dictionary
976
+ """
977
+
978
+ def round_labels(labels):
979
+ # Update labels to integer class and 6 decimal place floats
980
+ return [[int(c), *[round(x, 4) for x in points]] for c, *points in labels]
981
+
982
+ def unzip(path):
983
+ # Unzip data.zip TODO: CONSTRAINT: path/to/abc.zip MUST unzip to 'path/to/abc/'
984
+ if str(path).endswith('.zip'): # path is data.zip
985
+ assert Path(path).is_file(), f'Error unzipping {path}, file not found'
986
+ assert os.system(f'unzip -q {path} -d {path.parent}') == 0, f'Error unzipping {path}'
987
+ dir = path.with_suffix('') # dataset directory
988
+ return True, str(dir), next(dir.rglob('*.yaml')) # zipped, data_dir, yaml_path
989
+ else: # path is data.yaml
990
+ return False, None, path
991
+
992
+ def hub_ops(f, max_dim=1920):
993
+ # HUB ops for 1 image 'f'
994
+ im = Image.open(f)
995
+ r = max_dim / max(im.height, im.width) # ratio
996
+ if r < 1.0: # image too large
997
+ im = im.resize((int(im.width * r), int(im.height * r)))
998
+ im.save(im_dir / Path(f).name, quality=75) # save
999
+
1000
+ zipped, data_dir, yaml_path = unzip(Path(path))
1001
+ with open(check_file(yaml_path), errors='ignore') as f:
1002
+ data = yaml.safe_load(f) # data dict
1003
+ if zipped:
1004
+ data['path'] = data_dir # TODO: should this be dir.resolve()?
1005
+ check_dataset(data, autodownload) # download dataset if missing
1006
+ hub_dir = Path(data['path'] + ('-hub' if hub else ''))
1007
+ stats = {'nc': data['nc'], 'names': data['names']} # statistics dictionary
1008
+ for split in 'train', 'val', 'test':
1009
+ if data.get(split) is None:
1010
+ stats[split] = None # i.e. no test set
1011
+ continue
1012
+ x = []
1013
+ dataset = LoadImagesAndLabels(data[split], labels_dir=labels_dir) # load dataset
1014
+ for label in tqdm(dataset.labels, total=dataset.n, desc='Statistics'):
1015
+ x.append(np.bincount(label[:, 0].astype(int), minlength=data['nc']))
1016
+ x = np.array(x) # shape(128x80)
1017
+ stats[split] = {'instance_stats': {'total': int(x.sum()), 'per_class': x.sum(0).tolist()},
1018
+ 'image_stats': {'total': dataset.n, 'unlabelled': int(np.all(x == 0, 1).sum()),
1019
+ 'per_class': (x > 0).sum(0).tolist()},
1020
+ 'labels': [{str(Path(k).name): round_labels(v.tolist())} for k, v in
1021
+ zip(dataset.img_files, dataset.labels)]}
1022
+
1023
+ if hub:
1024
+ im_dir = hub_dir / 'images'
1025
+ im_dir.mkdir(parents=True, exist_ok=True)
1026
+ for _ in tqdm(ThreadPool(NUM_THREADS).imap(hub_ops, dataset.img_files), total=dataset.n, desc='HUB Ops'):
1027
+ pass
1028
+
1029
+ # Profile
1030
+ stats_path = hub_dir / 'stats.json'
1031
+ if profile:
1032
+ for _ in range(1):
1033
+ file = stats_path.with_suffix('.npy')
1034
+ t1 = time.time()
1035
+ np.save(file, stats)
1036
+ t2 = time.time()
1037
+ x = np.load(file, allow_pickle=True)
1038
+ print(f'stats.npy times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1039
+
1040
+ file = stats_path.with_suffix('.json')
1041
+ t1 = time.time()
1042
+ with open(file, 'w') as f:
1043
+ json.dump(stats, f) # save stats *.json
1044
+ t2 = time.time()
1045
+ with open(file, 'r') as f:
1046
+ x = json.load(f) # load hyps dict
1047
+ print(f'stats.json times: {time.time() - t2:.3f}s read, {t2 - t1:.3f}s write')
1048
+
1049
+ # Save, print and return
1050
+ if hub:
1051
+ print(f'Saving {stats_path.resolve()}...')
1052
+ with open(stats_path, 'w') as f:
1053
+ json.dump(stats, f) # save stats.json
1054
+ if verbose:
1055
+ print(json.dumps(stats, indent=2, sort_keys=False))
1056
+ return stats
utils/downloads.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Download utils
4
+ """
5
+
6
+ import os
7
+ import platform
8
+ import subprocess
9
+ import time
10
+ import urllib
11
+ from pathlib import Path
12
+
13
+ import requests
14
+ import torch
15
+
16
+
17
+ def gsutil_getsize(url=''):
18
+ # gs://bucket/file size https://cloud.google.com/storage/docs/gsutil/commands/du
19
+ s = subprocess.check_output(f'gsutil du {url}', shell=True).decode('utf-8')
20
+ return eval(s.split(' ')[0]) if len(s) else 0 # bytes
21
+
22
+
23
+ def safe_download(file, url, url2=None, min_bytes=1E0, error_msg=''):
24
+ # Attempts to download file from url or url2, checks and removes incomplete downloads < min_bytes
25
+ file = Path(file)
26
+ assert_msg = f"Downloaded file '{file}' does not exist or size is < min_bytes={min_bytes}"
27
+ try: # url1
28
+ print(f'Downloading {url} to {file}...')
29
+ torch.hub.download_url_to_file(url, str(file))
30
+ assert file.exists() and file.stat().st_size > min_bytes, assert_msg # check
31
+ except Exception as e: # url2
32
+ file.unlink(missing_ok=True) # remove partial downloads
33
+ print(f'ERROR: {e}\nRe-attempting {url2 or url} to {file}...')
34
+ os.system(f"curl -L '{url2 or url}' -o '{file}' --retry 3 -C -") # curl download, retry and resume on fail
35
+ finally:
36
+ if not file.exists() or file.stat().st_size < min_bytes: # check
37
+ file.unlink(missing_ok=True) # remove partial downloads
38
+ print(f"ERROR: {assert_msg}\n{error_msg}")
39
+ print('')
40
+
41
+
42
+ def attempt_download(file, repo='ultralytics/yolov5'): # from utils.downloads import *; attempt_download()
43
+ # Attempt file download if does not exist
44
+ file = Path(str(file).strip().replace("'", ''))
45
+
46
+ if not file.exists():
47
+ # URL specified
48
+ name = Path(urllib.parse.unquote(str(file))).name # decode '%2F' to '/' etc.
49
+ if str(file).startswith(('http:/', 'https:/')): # download
50
+ url = str(file).replace(':/', '://') # Pathlib turns :// -> :/
51
+ name = name.split('?')[0] # parse authentication https://url.com/file.txt?auth...
52
+ safe_download(file=name, url=url, min_bytes=1E5)
53
+ return name
54
+
55
+ # GitHub assets
56
+ file.parent.mkdir(parents=True, exist_ok=True) # make parent dir (if required)
57
+ try:
58
+ response = requests.get(f'https://api.github.com/repos/{repo}/releases/latest').json() # github api
59
+ assets = [x['name'] for x in response['assets']] # release assets, i.e. ['yolov5s.pt', 'yolov5m.pt', ...]
60
+ tag = response['tag_name'] # i.e. 'v1.0'
61
+ except: # fallback plan
62
+ assets = ['yolov5s.pt', 'yolov5m.pt', 'yolov5l.pt', 'yolov5x.pt',
63
+ 'yolov5s6.pt', 'yolov5m6.pt', 'yolov5l6.pt', 'yolov5x6.pt']
64
+ try:
65
+ tag = subprocess.check_output('git tag', shell=True, stderr=subprocess.STDOUT).decode().split()[-1]
66
+ except:
67
+ tag = 'v5.0' # current release
68
+ tag = 'v5.0' # download v5.0 models
69
+ if name in assets:
70
+ safe_download(file,
71
+ url=f'https://github.com/{repo}/releases/download/{tag}/{name}',
72
+ # url2=f'https://storage.googleapis.com/{repo}/ckpt/{name}', # backup url (optional)
73
+ min_bytes=1E5,
74
+ error_msg=f'{file} missing, try downloading from https://github.com/{repo}/releases/')
75
+
76
+ return str(file)
77
+
78
+
79
+ def gdrive_download(id='16TiPfZj7htmTyhntwcZyEEAejOUxuT6m', file='tmp.zip'):
80
+ # Downloads a file from Google Drive. from yolov5.utils.downloads import *; gdrive_download()
81
+ t = time.time()
82
+ file = Path(file)
83
+ cookie = Path('cookie') # gdrive cookie
84
+ print(f'Downloading https://drive.google.com/uc?export=download&id={id} as {file}... ', end='')
85
+ file.unlink(missing_ok=True) # remove existing file
86
+ cookie.unlink(missing_ok=True) # remove existing cookie
87
+
88
+ # Attempt file download
89
+ out = "NUL" if platform.system() == "Windows" else "/dev/null"
90
+ os.system(f'curl -c ./cookie -s -L "drive.google.com/uc?export=download&id={id}" > {out}')
91
+ if os.path.exists('cookie'): # large file
92
+ s = f'curl -Lb ./cookie "drive.google.com/uc?export=download&confirm={get_token()}&id={id}" -o {file}'
93
+ else: # small file
94
+ s = f'curl -s -L -o {file} "drive.google.com/uc?export=download&id={id}"'
95
+ r = os.system(s) # execute, capture return
96
+ cookie.unlink(missing_ok=True) # remove existing cookie
97
+
98
+ # Error check
99
+ if r != 0:
100
+ file.unlink(missing_ok=True) # remove partial
101
+ print('Download error ') # raise Exception('Download error')
102
+ return r
103
+
104
+ # Unzip if archive
105
+ if file.suffix == '.zip':
106
+ print('unzipping... ', end='')
107
+ os.system(f'unzip -q {file}') # unzip
108
+ file.unlink() # remove zip to free space
109
+
110
+ print(f'Done ({time.time() - t:.1f}s)')
111
+ return r
112
+
113
+
114
+ def get_token(cookie="./cookie"):
115
+ with open(cookie) as f:
116
+ for line in f:
117
+ if "download" in line:
118
+ return line.split()[-1]
119
+ return ""
120
+
121
+ # Google utils: https://cloud.google.com/storage/docs/reference/libraries ----------------------------------------------
122
+ #
123
+ #
124
+ # def upload_blob(bucket_name, source_file_name, destination_blob_name):
125
+ # # Uploads a file to a bucket
126
+ # # https://cloud.google.com/storage/docs/uploading-objects#storage-upload-object-python
127
+ #
128
+ # storage_client = storage.Client()
129
+ # bucket = storage_client.get_bucket(bucket_name)
130
+ # blob = bucket.blob(destination_blob_name)
131
+ #
132
+ # blob.upload_from_filename(source_file_name)
133
+ #
134
+ # print('File {} uploaded to {}.'.format(
135
+ # source_file_name,
136
+ # destination_blob_name))
137
+ #
138
+ #
139
+ # def download_blob(bucket_name, source_blob_name, destination_file_name):
140
+ # # Uploads a blob from a bucket
141
+ # storage_client = storage.Client()
142
+ # bucket = storage_client.get_bucket(bucket_name)
143
+ # blob = bucket.blob(source_blob_name)
144
+ #
145
+ # blob.download_to_filename(destination_file_name)
146
+ #
147
+ # print('Blob {} downloaded to {}.'.format(
148
+ # source_blob_name,
149
+ # destination_file_name))
utils/general.py ADDED
@@ -0,0 +1,853 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ General utils
4
+ """
5
+
6
+ import contextlib
7
+ import glob
8
+ import logging
9
+ import math
10
+ import os
11
+ import platform
12
+ import random
13
+ import re
14
+ import signal
15
+ import time
16
+ import urllib
17
+ from itertools import repeat
18
+ from multiprocessing.pool import ThreadPool
19
+ from pathlib import Path
20
+ from subprocess import check_output
21
+
22
+ import cv2
23
+ import numpy as np
24
+ import pandas as pd
25
+ import pkg_resources as pkg
26
+ import torch
27
+ import torchvision
28
+ import yaml
29
+
30
+ from utils.downloads import gsutil_getsize
31
+ from utils.metrics import box_iou, fitness
32
+ from utils.torch_utils import init_torch_seeds
33
+ from utils.labels import write_kp_labels
34
+
35
+ # Settings
36
+ torch.set_printoptions(linewidth=320, precision=5, profile='long')
37
+ np.set_printoptions(linewidth=320, formatter={'float_kind': '{:11.5g}'.format}) # format short g, %precision=5
38
+ pd.options.display.max_columns = 10
39
+ cv2.setNumThreads(0) # prevent OpenCV from multithreading (incompatible with PyTorch DataLoader)
40
+ os.environ['NUMEXPR_MAX_THREADS'] = str(min(os.cpu_count(), 8)) # NumExpr max threads
41
+
42
+
43
+ class Profile(contextlib.ContextDecorator):
44
+ # Usage: @Profile() decorator or 'with Profile():' context manager
45
+ def __enter__(self):
46
+ self.start = time.time()
47
+
48
+ def __exit__(self, type, value, traceback):
49
+ print(f'Profile results: {time.time() - self.start:.5f}s')
50
+
51
+
52
+ class Timeout(contextlib.ContextDecorator):
53
+ # Usage: @Timeout(seconds) decorator or 'with Timeout(seconds):' context manager
54
+ def __init__(self, seconds, *, timeout_msg='', suppress_timeout_errors=True):
55
+ self.seconds = int(seconds)
56
+ self.timeout_message = timeout_msg
57
+ self.suppress = bool(suppress_timeout_errors)
58
+
59
+ def _timeout_handler(self, signum, frame):
60
+ raise TimeoutError(self.timeout_message)
61
+
62
+ def __enter__(self):
63
+ signal.signal(signal.SIGALRM, self._timeout_handler) # Set handler for SIGALRM
64
+ signal.alarm(self.seconds) # start countdown for SIGALRM to be raised
65
+
66
+ def __exit__(self, exc_type, exc_val, exc_tb):
67
+ signal.alarm(0) # Cancel SIGALRM if it's scheduled
68
+ if self.suppress and exc_type is TimeoutError: # Suppress TimeoutError
69
+ return True
70
+
71
+
72
+ def try_except(func):
73
+ # try-except function. Usage: @try_except decorator
74
+ def handler(*args, **kwargs):
75
+ try:
76
+ func(*args, **kwargs)
77
+ except Exception as e:
78
+ print(e)
79
+
80
+ return handler
81
+
82
+
83
+ def methods(instance):
84
+ # Get class/instance methods
85
+ return [f for f in dir(instance) if callable(getattr(instance, f)) and not f.startswith("__")]
86
+
87
+
88
+ def set_logging(rank=-1, verbose=True):
89
+ logging.basicConfig(
90
+ format="%(message)s",
91
+ level=logging.INFO if (verbose and rank in [-1, 0]) else logging.WARN)
92
+
93
+
94
+ def init_seeds(seed=0):
95
+ # Initialize random number generator (RNG) seeds
96
+ random.seed(seed)
97
+ np.random.seed(seed)
98
+ init_torch_seeds(seed)
99
+
100
+
101
+ def get_latest_run(search_dir='.'):
102
+ # Return path to most recent 'last.pt' in /runs (i.e. to --resume from)
103
+ last_list = glob.glob(f'{search_dir}/**/last*.pt', recursive=True)
104
+ return max(last_list, key=os.path.getctime) if last_list else ''
105
+
106
+
107
+ def is_docker():
108
+ # Is environment a Docker container?
109
+ return Path('/workspace').exists() # or Path('/.dockerenv').exists()
110
+
111
+
112
+ def is_colab():
113
+ # Is environment a Google Colab instance?
114
+ try:
115
+ import google.colab
116
+ return True
117
+ except Exception as e:
118
+ return False
119
+
120
+
121
+ def is_pip():
122
+ # Is file in a pip package?
123
+ return 'site-packages' in Path(__file__).absolute().parts
124
+
125
+
126
+ def is_ascii(s=''):
127
+ # Is string composed of all ASCII (no UTF) characters?
128
+ s = str(s) # convert list, tuple, None, etc. to str
129
+ return len(s.encode().decode('ascii', 'ignore')) == len(s)
130
+
131
+
132
+ def emojis(str=''):
133
+ # Return platform-dependent emoji-safe version of string
134
+ return str.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else str
135
+
136
+
137
+ def file_size(file):
138
+ # Return file size in MB
139
+ return Path(file).stat().st_size / 1e6
140
+
141
+
142
+ def check_online():
143
+ # Check internet connectivity
144
+ import socket
145
+ try:
146
+ socket.create_connection(("1.1.1.1", 443), 5) # check host accessibility
147
+ return True
148
+ except OSError:
149
+ return False
150
+
151
+
152
+ @try_except
153
+ def check_git_status():
154
+ # Recommend 'git pull' if code is out of date
155
+ msg = ', for updates see https://github.com/ultralytics/yolov5'
156
+ print(colorstr('github: '), end='')
157
+ assert Path('.git').exists(), 'skipping check (not a git repository)' + msg
158
+ assert not is_docker(), 'skipping check (Docker image)' + msg
159
+ assert check_online(), 'skipping check (offline)' + msg
160
+
161
+ cmd = 'git fetch && git config --get remote.origin.url'
162
+ url = check_output(cmd, shell=True, timeout=5).decode().strip().rstrip('.git') # git fetch
163
+ branch = check_output('git rev-parse --abbrev-ref HEAD', shell=True).decode().strip() # checked out
164
+ n = int(check_output(f'git rev-list {branch}..origin/master --count', shell=True)) # commits behind
165
+ if n > 0:
166
+ s = f"⚠️ YOLOv5 is out of date by {n} commit{'s' * (n > 1)}. Use `git pull` or `git clone {url}` to update."
167
+ else:
168
+ s = f'up to date with {url} ✅'
169
+ print(emojis(s)) # emoji-safe
170
+
171
+
172
+ def check_python(minimum='3.6.2'):
173
+ # Check current python version vs. required python version
174
+ check_version(platform.python_version(), minimum, name='Python ')
175
+
176
+
177
+ def check_version(current='0.0.0', minimum='0.0.0', name='version ', pinned=False):
178
+ # Check version vs. required version
179
+ current, minimum = (pkg.parse_version(x) for x in (current, minimum))
180
+ result = (current == minimum) if pinned else (current >= minimum)
181
+ assert result, f'{name}{minimum} required by YOLOv5, but {name}{current} is currently installed'
182
+
183
+
184
+ @try_except
185
+ def check_requirements(requirements='requirements.txt', exclude=(), install=True):
186
+ # Check installed dependencies meet requirements (pass *.txt file or list of packages)
187
+ prefix = colorstr('red', 'bold', 'requirements:')
188
+ check_python() # check python version
189
+ if isinstance(requirements, (str, Path)): # requirements.txt file
190
+ file = Path(requirements)
191
+ assert file.exists(), f"{prefix} {file.resolve()} not found, check failed."
192
+ requirements = [f'{x.name}{x.specifier}' for x in pkg.parse_requirements(file.open()) if x.name not in exclude]
193
+ else: # list or tuple of packages
194
+ requirements = [x for x in requirements if x not in exclude]
195
+
196
+ n = 0 # number of packages updates
197
+ for r in requirements:
198
+ try:
199
+ pkg.require(r)
200
+ except Exception as e: # DistributionNotFound or VersionConflict if requirements not met
201
+ s = f"{prefix} {r} not found and is required by YOLOv5"
202
+ if install:
203
+ print(f"{s}, attempting auto-update...")
204
+ try:
205
+ assert check_online(), f"'pip install {r}' skipped (offline)"
206
+ print(check_output(f"pip install '{r}'", shell=True).decode())
207
+ n += 1
208
+ except Exception as e:
209
+ print(f'{prefix} {e}')
210
+ else:
211
+ print(f'{s}. Please install and rerun your command.')
212
+
213
+ if n: # if packages updated
214
+ source = file.resolve() if 'file' in locals() else requirements
215
+ s = f"{prefix} {n} package{'s' * (n > 1)} updated per {source}\n" \
216
+ f"{prefix} ⚠️ {colorstr('bold', 'Restart runtime or rerun command for updates to take effect')}\n"
217
+ print(emojis(s))
218
+
219
+
220
+ def check_img_size(imgsz, s=32, floor=0):
221
+ # Verify image size is a multiple of stride s in each dimension
222
+ if isinstance(imgsz, int): # integer i.e. img_size=640
223
+ new_size = max(make_divisible(imgsz, int(s)), floor)
224
+ else: # list i.e. img_size=[640, 480]
225
+ new_size = [max(make_divisible(x, int(s)), floor) for x in imgsz]
226
+ if new_size != imgsz:
227
+ print(f'WARNING: --img-size {imgsz} must be multiple of max stride {s}, updating to {new_size}')
228
+ return new_size
229
+
230
+
231
+ def check_imshow():
232
+ # Check if environment supports image displays
233
+ try:
234
+ assert not is_docker(), 'cv2.imshow() is disabled in Docker environments'
235
+ assert not is_colab(), 'cv2.imshow() is disabled in Google Colab environments'
236
+ cv2.imshow('test', np.zeros((1, 1, 3)))
237
+ cv2.waitKey(1)
238
+ cv2.destroyAllWindows()
239
+ cv2.waitKey(1)
240
+ return True
241
+ except Exception as e:
242
+ print(f'WARNING: Environment does not support cv2.imshow() or PIL Image.show() image displays\n{e}')
243
+ return False
244
+
245
+
246
+ def check_file(file):
247
+ # Search/download file (if necessary) and return path
248
+ file = str(file) # convert to str()
249
+ if Path(file).is_file() or file == '': # exists
250
+ return file
251
+ elif file.startswith(('http:/', 'https:/')): # download
252
+ url = str(Path(file)).replace(':/', '://') # Pathlib turns :// -> :/
253
+ file = Path(urllib.parse.unquote(file)).name.split('?')[0] # '%2F' to '/', split https://url.com/file.txt?auth
254
+ print(f'Downloading {url} to {file}...')
255
+ torch.hub.download_url_to_file(url, file)
256
+ assert Path(file).exists() and Path(file).stat().st_size > 0, f'File download failed: {url}' # check
257
+ return file
258
+ else: # search
259
+ files = glob.glob('./**/' + file, recursive=True) # find file
260
+ assert len(files), f'File not found: {file}' # assert file was found
261
+ assert len(files) == 1, f"Multiple files match '{file}', specify exact path: {files}" # assert unique
262
+ return files[0] # return file
263
+
264
+
265
+ def check_dataset(data, autodownload=True):
266
+ # Download and/or unzip dataset if not found locally
267
+ # Usage: https://github.com/ultralytics/yolov5/releases/download/v1.0/coco128_with_yaml.zip
268
+
269
+ # Download (optional)
270
+ extract_dir = ''
271
+ if isinstance(data, (str, Path)) and str(data).endswith('.zip'): # i.e. gs://bucket/dir/coco128.zip
272
+ download(data, dir='../datasets', unzip=True, delete=False, curl=False, threads=1)
273
+ data = next((Path('../datasets') / Path(data).stem).rglob('*.yaml'))
274
+ extract_dir, autodownload = data.parent, False
275
+
276
+ # Read yaml (optional)
277
+ if isinstance(data, (str, Path)):
278
+ with open(data, errors='ignore') as f:
279
+ data = yaml.safe_load(f) # dictionary
280
+
281
+ # Parse yaml
282
+ path = extract_dir or Path(data.get('path') or '') # optional 'path' default to '.'
283
+ for k in 'train', 'val', 'test':
284
+ if data.get(k): # prepend path
285
+ data[k] = str(path / data[k]) if isinstance(data[k], str) else [str(path / x) for x in data[k]]
286
+
287
+ assert 'nc' in data, "Dataset 'nc' key missing."
288
+ if 'names' not in data:
289
+ data['names'] = [f'class{i}' for i in range(data['nc'])] # assign class names if missing
290
+ train, val, test, s = [data.get(x) for x in ('train', 'val', 'test', 'download')]
291
+ if val:
292
+ val = [Path(x).resolve() for x in (val if isinstance(val, list) else [val])] # val path
293
+ if not all(x.exists() for x in val):
294
+ if 'kp_bbox' in data.keys():
295
+ print('Writing dataset labels to {}...'.format(os.path.join(data['path'], data['labels'])))
296
+ write_kp_labels(data)
297
+ else:
298
+ print('\nWARNING: Dataset not found, nonexistent paths: %s' % [str(x) for x in val if not x.exists()])
299
+ if s and autodownload: # download script
300
+ if s.startswith('http') and s.endswith('.zip'): # URL
301
+ f = Path(s).name # filename
302
+ print(f'Downloading {s} ...')
303
+ torch.hub.download_url_to_file(s, f)
304
+ root = path.parent if 'path' in data else '..' # unzip directory i.e. '../'
305
+ Path(root).mkdir(parents=True, exist_ok=True) # create root
306
+ r = os.system(f'unzip -q {f} -d {root} && rm {f}') # unzip
307
+ elif s.startswith('bash '): # bash script
308
+ print(f'Running {s} ...')
309
+ r = os.system(s)
310
+ else: # python script
311
+ r = exec(s, {'yaml': data}) # return None
312
+ print('Dataset autodownload %s\n' % ('success' if r in (0, None) else 'failure')) # print result
313
+ else:
314
+ raise Exception('Dataset not found.')
315
+
316
+ return data # dictionary
317
+
318
+
319
+ def download(url, dir='.', unzip=True, delete=True, curl=False, threads=1):
320
+ # Multi-threaded file download and unzip function, used in data.yaml for autodownload
321
+ def download_one(url, dir):
322
+ # Download 1 file
323
+ f = dir / Path(url).name # filename
324
+ if Path(url).is_file(): # exists in current path
325
+ Path(url).rename(f) # move to dir
326
+ elif not f.exists():
327
+ print(f'Downloading {url} to {f}...')
328
+ if curl:
329
+ os.system(f"curl -L '{url}' -o '{f}' --retry 9 -C -") # curl download, retry and resume on fail
330
+ else:
331
+ torch.hub.download_url_to_file(url, f, progress=True) # torch download
332
+ if unzip and f.suffix in ('.zip', '.gz'):
333
+ print(f'Unzipping {f}...')
334
+ if f.suffix == '.zip':
335
+ s = f'unzip -qo {f} -d {dir}' # unzip -quiet -overwrite
336
+ elif f.suffix == '.gz':
337
+ s = f'tar xfz {f} --directory {f.parent}' # unzip
338
+ if delete: # delete zip file after unzip
339
+ s += f' && rm {f}'
340
+ os.system(s)
341
+
342
+ dir = Path(dir)
343
+ dir.mkdir(parents=True, exist_ok=True) # make directory
344
+ if threads > 1:
345
+ pool = ThreadPool(threads)
346
+ pool.imap(lambda x: download_one(*x), zip(url, repeat(dir))) # multi-threaded
347
+ pool.close()
348
+ pool.join()
349
+ else:
350
+ for u in [url] if isinstance(url, (str, Path)) else url:
351
+ download_one(u, dir)
352
+
353
+
354
+ def make_divisible(x, divisor):
355
+ # Returns x evenly divisible by divisor
356
+ return math.ceil(x / divisor) * divisor
357
+
358
+
359
+ def clean_str(s):
360
+ # Cleans a string by replacing special characters with underscore _
361
+ return re.sub(pattern="[|@#!¡·$€%&()=?¿^*;:,¨´><+]", repl="_", string=s)
362
+
363
+
364
+ def one_cycle(y1=0.0, y2=1.0, steps=100):
365
+ # lambda function for sinusoidal ramp from y1 to y2 https://arxiv.org/pdf/1812.01187.pdf
366
+ return lambda x: ((1 - math.cos(x * math.pi / steps)) / 2) * (y2 - y1) + y1
367
+
368
+
369
+ def colorstr(*input):
370
+ # Colors a string https://en.wikipedia.org/wiki/ANSI_escape_code, i.e. colorstr('blue', 'hello world')
371
+ *args, string = input if len(input) > 1 else ('blue', 'bold', input[0]) # color arguments, string
372
+ colors = {'black': '\033[30m', # basic colors
373
+ 'red': '\033[31m',
374
+ 'green': '\033[32m',
375
+ 'yellow': '\033[33m',
376
+ 'blue': '\033[34m',
377
+ 'magenta': '\033[35m',
378
+ 'cyan': '\033[36m',
379
+ 'white': '\033[37m',
380
+ 'bright_black': '\033[90m', # bright colors
381
+ 'bright_red': '\033[91m',
382
+ 'bright_green': '\033[92m',
383
+ 'bright_yellow': '\033[93m',
384
+ 'bright_blue': '\033[94m',
385
+ 'bright_magenta': '\033[95m',
386
+ 'bright_cyan': '\033[96m',
387
+ 'bright_white': '\033[97m',
388
+ 'end': '\033[0m', # misc
389
+ 'bold': '\033[1m',
390
+ 'underline': '\033[4m'}
391
+ return ''.join(colors[x] for x in args) + f'{string}' + colors['end']
392
+
393
+
394
+ def labels_to_class_weights(labels, nc=80):
395
+ # Get class weights (inverse frequency) from training labels
396
+ if labels[0] is None: # no labels loaded
397
+ return torch.Tensor()
398
+
399
+ labels = np.concatenate(labels, 0) # labels.shape = (866643, 5) for COCO
400
+ classes = labels[:, 0].astype(np.int) # labels = [class xywh]
401
+ weights = np.bincount(classes, minlength=nc) # occurrences per class
402
+
403
+ # Prepend gridpoint count (for uCE training)
404
+ # gpi = ((320 / 32 * np.array([1, 2, 4])) ** 2 * 3).sum() # gridpoints per image
405
+ # weights = np.hstack([gpi * len(labels) - weights.sum() * 9, weights * 9]) ** 0.5 # prepend gridpoints to start
406
+
407
+ weights[weights == 0] = 1 # replace empty bins with 1
408
+ weights = 1 / weights # number of targets per class
409
+ weights /= weights.sum() # normalize
410
+ return torch.from_numpy(weights)
411
+
412
+
413
+ def labels_to_image_weights(labels, nc=80, class_weights=np.ones(80)):
414
+ # Produces image weights based on class_weights and image contents
415
+ class_counts = np.array([np.bincount(x[:, 0].astype(np.int), minlength=nc) for x in labels])
416
+ image_weights = (class_weights.reshape(1, nc) * class_counts).sum(1)
417
+ # index = random.choices(range(n), weights=image_weights, k=1) # weight image sample
418
+ return image_weights
419
+
420
+
421
+ def coco80_to_coco91_class(): # converts 80-index (val2014) to 91-index (paper)
422
+ # https://tech.amikelive.com/node-718/what-object-categories-labels-are-in-coco-dataset/
423
+ # a = np.loadtxt('data/coco.names', dtype='str', delimiter='\n')
424
+ # b = np.loadtxt('data/coco_paper.names', dtype='str', delimiter='\n')
425
+ # x1 = [list(a[i] == b).index(True) + 1 for i in range(80)] # darknet to coco
426
+ # x2 = [list(b[i] == a).index(True) if any(b[i] == a) else None for i in range(91)] # coco to darknet
427
+ x = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 27, 28, 31, 32, 33, 34,
428
+ 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63,
429
+ 64, 65, 67, 70, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 84, 85, 86, 87, 88, 89, 90]
430
+ return x
431
+
432
+
433
+ def xyxy2xywh(x):
434
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] where xy1=top-left, xy2=bottom-right
435
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
436
+ y[:, 0] = (x[:, 0] + x[:, 2]) / 2 # x center
437
+ y[:, 1] = (x[:, 1] + x[:, 3]) / 2 # y center
438
+ y[:, 2] = x[:, 2] - x[:, 0] # width
439
+ y[:, 3] = x[:, 3] - x[:, 1] # height
440
+ return y
441
+
442
+
443
+ def xywh2xyxy(x):
444
+ # Convert nx4 boxes from [x, y, w, h] to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
445
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
446
+ y[:, 0] = x[:, 0] - x[:, 2] / 2 # top left x
447
+ y[:, 1] = x[:, 1] - x[:, 3] / 2 # top left y
448
+ y[:, 2] = x[:, 0] + x[:, 2] / 2 # bottom right x
449
+ y[:, 3] = x[:, 1] + x[:, 3] / 2 # bottom right y
450
+ return y
451
+
452
+
453
+ def xywhn2xyxy(x, w=640, h=640, padw=0, padh=0):
454
+ # Convert nx4 boxes from [x, y, w, h] normalized to [x1, y1, x2, y2] where xy1=top-left, xy2=bottom-right
455
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
456
+ y[:, 0] = w * (x[:, 0] - x[:, 2] / 2) + padw # top left x
457
+ y[:, 1] = h * (x[:, 1] - x[:, 3] / 2) + padh # top left y
458
+ y[:, 2] = w * (x[:, 0] + x[:, 2] / 2) + padw # bottom right x
459
+ y[:, 3] = h * (x[:, 1] + x[:, 3] / 2) + padh # bottom right y
460
+
461
+ # Convert keypoints from [x, y, v] normalized to [x, y]
462
+ if y.shape[-1] > 4:
463
+ nl = y.shape[0]
464
+ kp = y[:, 4:].reshape(nl, -1, 3)
465
+ kp[..., 0] *= w
466
+ kp[..., 0] += padw
467
+ kp[..., 1] *= h
468
+ kp[..., 1] += padh
469
+ y[:, 4:] = kp.reshape(nl, -1)
470
+
471
+ return y
472
+
473
+
474
+ def xyxy2xywhn(x, w=640, h=640, clip=False, eps=0.0):
475
+ # Convert nx4 boxes from [x1, y1, x2, y2] to [x, y, w, h] normalized where xy1=top-left, xy2=bottom-right
476
+ if clip:
477
+ clip_coords(x, (h - eps, w - eps)) # warning: inplace clip
478
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
479
+ y[:, 0] = ((x[:, 0] + x[:, 2]) / 2) / w # x center
480
+ y[:, 1] = ((x[:, 1] + x[:, 3]) / 2) / h # y center
481
+ y[:, 2] = (x[:, 2] - x[:, 0]) / w # width
482
+ y[:, 3] = (x[:, 3] - x[:, 1]) / h # height
483
+
484
+ # convert keypoints from [x, y, v] to [x, y, v] normalized
485
+ if y.shape[-1] > 4:
486
+ nl = y.shape[0]
487
+ kp = y[:, 4:].reshape(nl, -1, 3)
488
+ kp[..., 0] /= w
489
+ kp[..., 1] /= h
490
+ y[:, 4:] = kp.reshape(nl, -1)
491
+
492
+ return y
493
+
494
+
495
+ def xyn2xy(x, w=640, h=640, padw=0, padh=0):
496
+ # Convert normalized segments into pixel segments, shape (n,2)
497
+ y = x.clone() if isinstance(x, torch.Tensor) else np.copy(x)
498
+ y[:, 0] = w * x[:, 0] + padw # top left x
499
+ y[:, 1] = h * x[:, 1] + padh # top left y
500
+ return y
501
+
502
+
503
+ def segment2box(segment, width=640, height=640):
504
+ # Convert 1 segment label to 1 box label, applying inside-image constraint, i.e. (xy1, xy2, ...) to (xyxy)
505
+ x, y = segment.T # segment xy
506
+ inside = (x >= 0) & (y >= 0) & (x <= width) & (y <= height)
507
+ x, y, = x[inside], y[inside]
508
+ return np.array([x.min(), y.min(), x.max(), y.max()]) if any(x) else np.zeros((1, 4)) # xyxy
509
+
510
+
511
+ def segments2boxes(segments):
512
+ # Convert segment labels to box labels, i.e. (cls, xy1, xy2, ...) to (cls, xywh)
513
+ boxes = []
514
+ for s in segments:
515
+ x, y = s.T # segment xy
516
+ boxes.append([x.min(), y.min(), x.max(), y.max()]) # cls, xyxy
517
+ return xyxy2xywh(np.array(boxes)) # cls, xywh
518
+
519
+
520
+ def resample_segments(segments, n=1000):
521
+ # Up-sample an (n,2) segment
522
+ for i, s in enumerate(segments):
523
+ x = np.linspace(0, len(s) - 1, n)
524
+ xp = np.arange(len(s))
525
+ segments[i] = np.concatenate([np.interp(x, xp, s[:, i]) for i in range(2)]).reshape(2, -1).T # segment xy
526
+ return segments
527
+
528
+
529
+ def scale_coords(img1_shape, coords, img0_shape, ratio_pad=None):
530
+ # Rescale coords (xyxy) from img1_shape to img0_shape
531
+ if ratio_pad is None: # calculate from img0_shape
532
+ gain = min(img1_shape[0] / img0_shape[0], img1_shape[1] / img0_shape[1]) # gain = old / new
533
+ pad = (img1_shape[1] - img0_shape[1] * gain) / 2, (img1_shape[0] - img0_shape[0] * gain) / 2 # wh padding
534
+ else:
535
+ gain = ratio_pad[0][0]
536
+ pad = ratio_pad[1]
537
+
538
+ nl = coords.shape[0]
539
+ coords = coords.reshape((nl, -1, 2))
540
+ coords[..., 0] -= pad[0]
541
+ coords[..., 1] -= pad[1]
542
+ coords /= gain
543
+ coords = coords.reshape(nl, -1)
544
+ clip_coords(coords, img0_shape)
545
+ return coords
546
+
547
+
548
+ def clip_coords(boxes, shape):
549
+ # Clip bounding xyxy bounding boxes to image shape (height, width)
550
+ if isinstance(boxes, torch.Tensor): # faster individually
551
+ boxes[:, 0].clamp_(0, shape[1]) # x1
552
+ boxes[:, 1].clamp_(0, shape[0]) # y1
553
+ boxes[:, 2].clamp_(0, shape[1]) # x2
554
+ boxes[:, 3].clamp_(0, shape[0]) # y2
555
+ else: # np.array (faster grouped)
556
+ boxes[:, [0, 2]] = boxes[:, [0, 2]].clip(0, shape[1]) # x1, x2
557
+ boxes[:, [1, 3]] = boxes[:, [1, 3]].clip(0, shape[0]) # y1, y2
558
+
559
+
560
+ def non_max_suppression(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, agnostic=False, multi_label=False,
561
+ labels=(), max_det=300):
562
+ """Runs Non-Maximum Suppression (NMS) on inference results
563
+
564
+ Returns:
565
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls]
566
+ """
567
+
568
+ nc = prediction.shape[2] - 5 # number of classes
569
+ xc = prediction[..., 4] > conf_thres # candidates
570
+
571
+ # Checks
572
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
573
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
574
+
575
+ # Settings
576
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
577
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
578
+ time_limit = 10.0 # seconds to quit after
579
+ redundant = True # require redundant detections
580
+ multi_label &= nc > 1 # multiple labels per box (adds 0.5ms/img)
581
+ merge = False # use merge-NMS
582
+
583
+ t = time.time()
584
+ output = [torch.zeros((0, 6), device=prediction.device)] * prediction.shape[0]
585
+ for xi, x in enumerate(prediction): # image index, image inference
586
+ # Apply constraints
587
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
588
+ x = x[xc[xi]] # confidence
589
+
590
+ # Cat apriori labels if autolabelling
591
+ if labels and len(labels[xi]):
592
+ l = labels[xi]
593
+ v = torch.zeros((len(l), nc + 5), device=x.device)
594
+ v[:, :4] = l[:, 1:5] # box
595
+ v[:, 4] = 1.0 # conf
596
+ v[range(len(l)), l[:, 0].long() + 5] = 1.0 # cls
597
+ x = torch.cat((x, v), 0)
598
+
599
+ # If none remain process next image
600
+ if not x.shape[0]:
601
+ continue
602
+
603
+ # Compute conf
604
+ x[:, 5:] *= x[:, 4:5] # conf = obj_conf * cls_conf
605
+
606
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
607
+ box = xywh2xyxy(x[:, :4])
608
+
609
+ # Detections matrix nx6 (xyxy, conf, cls)
610
+ if multi_label:
611
+ i, j = (x[:, 5:] > conf_thres).nonzero(as_tuple=False).T
612
+ x = torch.cat((box[i], x[i, j + 5, None], j[:, None].float()), 1)
613
+ else: # best class only
614
+ conf, j = x[:, 5:].max(1, keepdim=True)
615
+ x = torch.cat((box, conf, j.float()), 1)[conf.view(-1) > conf_thres]
616
+
617
+ # Filter by class
618
+ if classes is not None:
619
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
620
+
621
+ # Apply finite constraint
622
+ # if not torch.isfinite(x).all():
623
+ # x = x[torch.isfinite(x).all(1)]
624
+
625
+ # Check shape
626
+ n = x.shape[0] # number of boxes
627
+ if not n: # no boxes
628
+ continue
629
+ elif n > max_nms: # excess boxes
630
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
631
+
632
+ # Batched NMS
633
+ c = x[:, 5:6] * (0 if agnostic else max_wh) # classes
634
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
635
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
636
+ if i.shape[0] > max_det: # limit detections
637
+ i = i[:max_det]
638
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
639
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
640
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
641
+ weights = iou * scores[None] # box weights
642
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
643
+ if redundant:
644
+ i = i[iou.sum(1) > 1] # require redundancy
645
+
646
+ output[xi] = x[i]
647
+ if (time.time() - t) > time_limit:
648
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
649
+ break # time limit exceeded
650
+
651
+ return output
652
+
653
+
654
+ def non_max_suppression_kp(prediction, conf_thres=0.25, iou_thres=0.45, classes=None, max_det=300, num_coords=34):
655
+ """Runs Non-Maximum Suppression (NMS) on inference results
656
+
657
+ Returns:
658
+ list of detections, on (n,6) tensor per image [xyxy, conf, cls, keypoints]
659
+ """
660
+
661
+ nc = prediction.shape[2] - 5 - num_coords # number of classes
662
+ xc = prediction[..., 4] > conf_thres # candidates
663
+
664
+ # Checks
665
+ assert 0 <= conf_thres <= 1, f'Invalid Confidence threshold {conf_thres}, valid values are between 0.0 and 1.0'
666
+ assert 0 <= iou_thres <= 1, f'Invalid IoU {iou_thres}, valid values are between 0.0 and 1.0'
667
+
668
+ # Settings
669
+ min_wh, max_wh = 2, 4096 # (pixels) minimum and maximum box width and height
670
+ max_nms = 30000 # maximum number of boxes into torchvision.ops.nms()
671
+ time_limit = 10.0 # seconds to quit after
672
+ redundant = True # require redundant detections
673
+ merge = False # use merge-NMS
674
+
675
+ t = time.time()
676
+ output = [torch.zeros((0, 6 + num_coords), device=prediction.device)] * prediction.shape[0]
677
+ for xi, x in enumerate(prediction): # image index, image inference
678
+ # Apply constraints
679
+ # x[((x[..., 2:4] < min_wh) | (x[..., 2:4] > max_wh)).any(1), 4] = 0 # width-height
680
+ x = x[xc[xi]] # confidence
681
+
682
+ # If none remain process next image
683
+ if not x.shape[0]:
684
+ continue
685
+
686
+ # Compute conf
687
+ x[:, 5:-num_coords] *= x[:, 4:5] # conf = obj_conf * cls_conf
688
+
689
+ # Box (center x, center y, width, height) to (x1, y1, x2, y2)
690
+ box = xywh2xyxy(x[:, :4])
691
+
692
+ # Detections matrix nx6 (xyxy, conf, cls)
693
+ conf, j = x[:, 5:-num_coords].max(1, keepdim=True)
694
+ kp = x[:, -num_coords:]
695
+ x = torch.cat((box, conf, j.float(), kp), 1)[conf.view(-1) > conf_thres]
696
+
697
+ # Filter by class
698
+ if classes is not None:
699
+ x = x[(x[:, 5:6] == torch.tensor(classes, device=x.device)).any(1)]
700
+
701
+ # Apply finite constraint
702
+ # if not torch.isfinite(x).all():
703
+ # x = x[torch.isfinite(x).all(1)]
704
+
705
+ # Check shape
706
+ n = x.shape[0] # number of boxes
707
+ if not n: # no boxes
708
+ continue
709
+ elif n > max_nms: # excess boxes
710
+ x = x[x[:, 4].argsort(descending=True)[:max_nms]] # sort by confidence
711
+
712
+ # Batched NMS
713
+ c = x[:, 5:6] * max_wh # classes
714
+ boxes, scores = x[:, :4] + c, x[:, 4] # boxes (offset by class), scores
715
+ i = torchvision.ops.nms(boxes, scores, iou_thres) # NMS
716
+ if i.shape[0] > max_det: # limit detections
717
+ i = i[:max_det]
718
+ if merge and (1 < n < 3E3): # Merge NMS (boxes merged using weighted mean)
719
+ # update boxes as boxes(i,4) = weights(i,n) * boxes(n,4)
720
+ iou = box_iou(boxes[i], boxes) > iou_thres # iou matrix
721
+ weights = iou * scores[None] # box weights
722
+ x[i, :4] = torch.mm(weights, x[:, :4]).float() / weights.sum(1, keepdim=True) # merged boxes
723
+ if redundant:
724
+ i = i[iou.sum(1) > 1] # require redundancy
725
+
726
+ output[xi] = x[i]
727
+ if (time.time() - t) > time_limit:
728
+ print(f'WARNING: NMS time limit {time_limit}s exceeded')
729
+ break # time limit exceeded
730
+
731
+ return output
732
+
733
+
734
+ def strip_optimizer(f='best.pt', s=''): # from utils.general import *; strip_optimizer()
735
+ # Strip optimizer from 'f' to finalize training, optionally save as 's'
736
+ x = torch.load(f, map_location=torch.device('cpu'))
737
+ if x.get('ema'):
738
+ x['model'] = x['ema'] # replace model with ema
739
+ for k in 'optimizer', 'training_results', 'wandb_id', 'ema', 'updates': # keys
740
+ x[k] = None
741
+ x['epoch'] = -1
742
+ x['model'].half() # to FP16
743
+ for p in x['model'].parameters():
744
+ p.requires_grad = False
745
+ torch.save(x, s or f)
746
+ mb = os.path.getsize(s or f) / 1E6 # filesize
747
+ print(f"Optimizer stripped from {f},{(' saved as %s,' % s) if s else ''} {mb:.1f}MB")
748
+
749
+
750
+ def print_mutation(results, hyp, save_dir, bucket):
751
+ evolve_csv, results_csv, evolve_yaml = save_dir / 'evolve.csv', save_dir / 'results.csv', save_dir / 'hyp_evolve.yaml'
752
+ keys = ('metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95',
753
+ 'val/box_loss', 'val/obj_loss', 'val/cls_loss') + tuple(hyp.keys()) # [results + hyps]
754
+ keys = tuple(x.strip() for x in keys)
755
+ vals = results + tuple(hyp.values())
756
+ n = len(keys)
757
+
758
+ # Download (optional)
759
+ if bucket:
760
+ url = f'gs://{bucket}/evolve.csv'
761
+ if gsutil_getsize(url) > (os.path.getsize(evolve_csv) if os.path.exists(evolve_csv) else 0):
762
+ os.system(f'gsutil cp {url} {save_dir}') # download evolve.csv if larger than local
763
+
764
+ # Log to evolve.csv
765
+ s = '' if evolve_csv.exists() else (('%20s,' * n % keys).rstrip(',') + '\n') # add header
766
+ with open(evolve_csv, 'a') as f:
767
+ f.write(s + ('%20.5g,' * n % vals).rstrip(',') + '\n')
768
+
769
+ # Print to screen
770
+ print(colorstr('evolve: ') + ', '.join(f'{x.strip():>20s}' for x in keys))
771
+ print(colorstr('evolve: ') + ', '.join(f'{x:20.5g}' for x in vals), end='\n\n\n')
772
+
773
+ # Save yaml
774
+ with open(evolve_yaml, 'w') as f:
775
+ data = pd.read_csv(evolve_csv)
776
+ data = data.rename(columns=lambda x: x.strip()) # strip keys
777
+ i = np.argmax(fitness(data.values[:, :7])) #
778
+ f.write(f'# YOLOv5 Hyperparameter Evolution Results\n' +
779
+ f'# Best generation: {i}\n' +
780
+ f'# Last generation: {len(data)}\n' +
781
+ f'# ' + ', '.join(f'{x.strip():>20s}' for x in keys[:7]) + '\n' +
782
+ f'# ' + ', '.join(f'{x:>20.5g}' for x in data.values[i, :7]) + '\n\n')
783
+ yaml.safe_dump(hyp, f, sort_keys=False)
784
+
785
+ if bucket:
786
+ os.system(f'gsutil cp {evolve_csv} {evolve_yaml} gs://{bucket}') # upload
787
+
788
+
789
+ def apply_classifier(x, model, img, im0):
790
+ # Apply a second stage classifier to yolo outputs
791
+ im0 = [im0] if isinstance(im0, np.ndarray) else im0
792
+ for i, d in enumerate(x): # per image
793
+ if d is not None and len(d):
794
+ d = d.clone()
795
+
796
+ # Reshape and pad cutouts
797
+ b = xyxy2xywh(d[:, :4]) # boxes
798
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # rectangle to square
799
+ b[:, 2:] = b[:, 2:] * 1.3 + 30 # pad
800
+ d[:, :4] = xywh2xyxy(b).long()
801
+
802
+ # Rescale boxes from img_size to im0 size
803
+ scale_coords(img.shape[2:], d[:, :4], im0[i].shape)
804
+
805
+ # Classes
806
+ pred_cls1 = d[:, 5].long()
807
+ ims = []
808
+ for j, a in enumerate(d): # per item
809
+ cutout = im0[i][int(a[1]):int(a[3]), int(a[0]):int(a[2])]
810
+ im = cv2.resize(cutout, (224, 224)) # BGR
811
+ # cv2.imwrite('example%i.jpg' % j, cutout)
812
+
813
+ im = im[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416
814
+ im = np.ascontiguousarray(im, dtype=np.float32) # uint8 to float32
815
+ im /= 255.0 # 0 - 255 to 0.0 - 1.0
816
+ ims.append(im)
817
+
818
+ pred_cls2 = model(torch.Tensor(ims).to(d.device)).argmax(1) # classifier prediction
819
+ x[i] = x[i][pred_cls1 == pred_cls2] # retain matching class detections
820
+
821
+ return x
822
+
823
+
824
+ def save_one_box(xyxy, im, file='image.jpg', gain=1.02, pad=10, square=False, BGR=False, save=True):
825
+ # Save image crop as {file} with crop size multiple {gain} and {pad} pixels. Save and/or return crop
826
+ xyxy = torch.tensor(xyxy).view(-1, 4)
827
+ b = xyxy2xywh(xyxy) # boxes
828
+ if square:
829
+ b[:, 2:] = b[:, 2:].max(1)[0].unsqueeze(1) # attempt rectangle to square
830
+ b[:, 2:] = b[:, 2:] * gain + pad # box wh * gain + pad
831
+ xyxy = xywh2xyxy(b).long()
832
+ clip_coords(xyxy, im.shape)
833
+ crop = im[int(xyxy[0, 1]):int(xyxy[0, 3]), int(xyxy[0, 0]):int(xyxy[0, 2]), ::(1 if BGR else -1)]
834
+ if save:
835
+ cv2.imwrite(str(increment_path(file, mkdir=True).with_suffix('.jpg')), crop)
836
+ return crop
837
+
838
+
839
+ def increment_path(path, exist_ok=False, sep='', mkdir=False):
840
+ # Increment file or directory path, i.e. runs/exp --> runs/exp{sep}2, runs/exp{sep}3, ... etc.
841
+ path = Path(path) # os-agnostic
842
+ if path.exists() and not exist_ok:
843
+ suffix = path.suffix
844
+ path = path.with_suffix('')
845
+ dirs = glob.glob(f"{path}{sep}*") # similar paths
846
+ matches = [re.search(rf"%s{sep}(\d+)" % path.stem, d) for d in dirs]
847
+ i = [int(m.groups()[0]) for m in matches if m] # indices
848
+ n = max(i) + 1 if i else 2 # increment number
849
+ path = Path(f"{path}{sep}{n}{suffix}") # update path
850
+ dir = path if path.suffix == '' else path.parent # directory
851
+ if not dir.exists() and mkdir:
852
+ dir.mkdir(parents=True, exist_ok=True) # make directory
853
+ return path
utils/labels.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os, os.path as osp
2
+ import argparse
3
+ import numpy as np
4
+ import yaml
5
+ from tqdm import tqdm
6
+
7
+
8
+ def write_kp_labels(data):
9
+ assert not osp.isdir(osp.join(data['path'], data['labels'])), \
10
+ 'Labels already generated. Remove or choose new name for labels.'
11
+
12
+ is_coco = 'coco' in data['path']
13
+ if is_coco:
14
+ from pycocotools.coco import COCO
15
+ else:
16
+ from crowdposetools.coco import COCO
17
+
18
+ splits = [osp.splitext(osp.split(data[s])[-1])[0] for s in ['train', 'val', 'test'] if s in data]
19
+ annotations = [osp.join(data['path'], data['{}_annotations'.format(s)]) for s in ['train', 'val', 'test'] if s in data]
20
+ test_split = [0 if s in ['train', 'val'] else 1 for s in ['train', 'val', 'test'] if s in data]
21
+ img_txt_dir = osp.join(data['path'], data['labels'], 'img_txt')
22
+ os.makedirs(img_txt_dir, exist_ok=True)
23
+
24
+ for split, annot, is_test in zip(splits, annotations, test_split):
25
+ img_txt_path = osp.join(img_txt_dir, '{}.txt'.format(split))
26
+ labels_path = osp.join(data['path'], '{}/{}'.format(data['labels'], split if is_coco else ''))
27
+ if not is_test:
28
+ os.makedirs(labels_path, exist_ok=True)
29
+ coco = COCO(annot)
30
+ if not is_test:
31
+ pbar = tqdm(coco.anns.keys(), total=len(coco.anns.keys()))
32
+ pbar.desc = 'Writing {} labels to {}'.format(split, labels_path)
33
+ for id in pbar:
34
+ a = coco.anns[id]
35
+
36
+ if a['image_id'] not in coco.imgs:
37
+ continue
38
+
39
+ if 'train' in split:
40
+ if is_coco and a['iscrowd']:
41
+ continue
42
+
43
+ img_info = coco.imgs[a['image_id']]
44
+ img_h, img_w = img_info['height'], img_info['width']
45
+ x, y, w, h = a['bbox']
46
+ xc, yc = x + w / 2, y + h / 2
47
+ xc /= img_w
48
+ yc /= img_h
49
+ w /= img_w
50
+ h /= img_h
51
+
52
+ keypoints = np.array(a['keypoints']).reshape([-1, 3])
53
+
54
+ # some of crowdpose keypoints are just outside image so clip to image extents
55
+ if not is_coco:
56
+ keypoints[:, 0] = np.clip(keypoints[:, 0], 0, img_w)
57
+ keypoints[:, 1] = np.clip(keypoints[:, 1], 0, img_h)
58
+
59
+ with open(osp.join(labels_path, '{}.txt'.format(osp.splitext(img_info['file_name'])[0])), 'a') as f:
60
+ # write person object
61
+ s = '{} {:.6f} {:.6f} {:.6f} {:.6f}'.format(0, xc, yc, w, h)
62
+ if data['pose_obj']:
63
+ for i, (x, y, v) in enumerate(keypoints):
64
+ s += ' {:.6f} {:.6f} {:.6f}'.format(x / img_w, y / img_h, v)
65
+ s += '\n'
66
+ f.write(s)
67
+
68
+ # write keypoint objects
69
+ for i, (x, y, v) in enumerate(keypoints):
70
+ if v:
71
+ if isinstance(data['kp_bbox'], list):
72
+ kp_bbox = data['kp_bbox'][i]
73
+ else:
74
+ kp_bbox = data['kp_bbox']
75
+
76
+ s = '{} {:.6f} {:.6f} {:.6f} {:.6f}'.format(
77
+ i + 1, x / img_w, y / img_h,
78
+ kp_bbox * max(img_h, img_w) / img_w,
79
+ kp_bbox * max(img_h, img_w) / img_h)
80
+
81
+ if data['pose_obj']:
82
+ for _ in range(keypoints.shape[0]):
83
+ s += ' {:.6f} {:.6f} {:.6f}'.format(0, 0, 0)
84
+ s += '\n'
85
+ f.write(s)
86
+ pbar.close()
87
+
88
+ with open(img_txt_path, 'w') as f:
89
+ for img_info in coco.imgs.values():
90
+ f.write(osp.join(data['path'], 'images',
91
+ '{}'.format(split if is_coco else ''),
92
+ img_info['file_name']) + '\n')
93
+
94
+
95
+ if __name__ == '__main__':
96
+ parser = argparse.ArgumentParser()
97
+ parser.add_argument('--data', default='data/coco-kp.yaml')
98
+ args = parser.parse_args()
99
+
100
+ assert osp.isfile(args.data), 'Data config file not found at {}'.format(args.data)
101
+
102
+ with open(args.data, 'rb') as f:
103
+ data = yaml.safe_load(f)
104
+ write_kp_labels(data)
utils/loggers/__init__.py ADDED
@@ -0,0 +1,149 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Logging utils
4
+ """
5
+
6
+ import warnings
7
+ from threading import Thread
8
+
9
+ import torch
10
+ from torch.utils.tensorboard import SummaryWriter
11
+
12
+ from utils.general import colorstr, emojis
13
+ from utils.loggers.wandb.wandb_utils import WandbLogger
14
+ from utils.plots import plot_images, plot_results
15
+ from utils.torch_utils import de_parallel
16
+
17
+ LOGGERS = ('csv', 'tb', 'wandb') # text-file, TensorBoard, Weights & Biases
18
+
19
+ try:
20
+ import wandb
21
+
22
+ assert hasattr(wandb, '__version__') # verify package import not local dir
23
+ except (ImportError, AssertionError):
24
+ wandb = None
25
+
26
+
27
+ class Loggers():
28
+ # YOLOv5 Loggers class
29
+ def __init__(self, save_dir=None, weights=None, opt=None, hyp=None, logger=None, include=LOGGERS):
30
+ self.save_dir = save_dir
31
+ self.weights = weights
32
+ self.opt = opt
33
+ self.hyp = hyp
34
+ self.logger = logger # for printing results to console
35
+ self.include = include
36
+ self.keys = ['train/box_loss', 'train/obj_loss', 'train/cls_loss', 'train/kp_loss', # train loss
37
+ 'metrics/precision', 'metrics/recall', 'metrics/mAP_0.5', 'metrics/mAP_0.5:0.95', # metrics
38
+ 'val/box_loss', 'val/obj_loss', 'val/cls_loss', 'val/kp_loss', # val loss
39
+ 'x/lr0', 'x/lr1', 'x/lr2'] # params
40
+ for k in LOGGERS:
41
+ setattr(self, k, None) # init empty logger dictionary
42
+ self.csv = True # always log to csv
43
+
44
+ # Message
45
+ if not wandb:
46
+ prefix = colorstr('Weights & Biases: ')
47
+ s = f"{prefix}run 'pip install wandb' to automatically track and visualize YOLOv5 🚀 runs (RECOMMENDED)"
48
+ print(emojis(s))
49
+
50
+ # TensorBoard
51
+ s = self.save_dir
52
+ if 'tb' in self.include and not self.opt.evolve:
53
+ prefix = colorstr('TensorBoard: ')
54
+ self.logger.info(f"{prefix}Start with 'tensorboard --logdir {s.parent}', view at http://localhost:6006/")
55
+ self.tb = SummaryWriter(str(s))
56
+
57
+ # W&B
58
+ if wandb and 'wandb' in self.include:
59
+ wandb_artifact_resume = isinstance(self.opt.resume, str) and self.opt.resume.startswith('wandb-artifact://')
60
+ run_id = torch.load(self.weights).get('wandb_id') if self.opt.resume and not wandb_artifact_resume else None
61
+ self.opt.hyp = self.hyp # add hyperparameters
62
+ self.wandb = WandbLogger(self.opt, run_id)
63
+ else:
64
+ self.wandb = None
65
+
66
+ def on_pretrain_routine_end(self):
67
+ # Callback runs on pre-train routine end
68
+ paths = self.save_dir.glob('*labels*.jpg') # training labels
69
+ if self.wandb:
70
+ self.wandb.log({"Labels": [wandb.Image(str(x), caption=x.name) for x in paths]})
71
+
72
+ def on_train_batch_end(self, ni, model, imgs, targets, paths, plots, sync_bn):
73
+ # Callback runs on train batch end
74
+ if plots:
75
+ if ni == 0:
76
+ if not sync_bn: # tb.add_graph() --sync known issue https://github.com/ultralytics/yolov5/issues/3754
77
+ with warnings.catch_warnings():
78
+ warnings.simplefilter('ignore') # suppress jit trace warning
79
+ self.tb.add_graph(torch.jit.trace(de_parallel(model), imgs[0:1], strict=False), [])
80
+ if ni < 3:
81
+ f = self.save_dir / f'train_batch{ni}.jpg' # filename
82
+ Thread(target=plot_images, args=(imgs, targets, paths, f), daemon=True).start()
83
+ if self.wandb and ni == 10:
84
+ files = sorted(self.save_dir.glob('train*.jpg'))
85
+ self.wandb.log({'Mosaics': [wandb.Image(str(f), caption=f.name) for f in files if f.exists()]})
86
+
87
+ def on_train_epoch_end(self, epoch):
88
+ # Callback runs on train epoch end
89
+ if self.wandb:
90
+ self.wandb.current_epoch = epoch + 1
91
+
92
+ def on_val_image_end(self, pred, predn, path, names, im):
93
+ # Callback runs on val image end
94
+ if self.wandb:
95
+ self.wandb.val_one_image(pred, predn, path, names, im)
96
+
97
+ def on_val_end(self):
98
+ # Callback runs on val end
99
+ if self.wandb:
100
+ files = sorted(self.save_dir.glob('val*.jpg'))
101
+ self.wandb.log({"Validation": [wandb.Image(str(f), caption=f.name) for f in files]})
102
+
103
+ def on_fit_epoch_end(self, vals, epoch, best_fitness, fi):
104
+ # Callback runs at the end of each fit (train+val) epoch
105
+ x = {k: v for k, v in zip(self.keys, vals)} # dict
106
+ if self.csv:
107
+ file = self.save_dir / 'results.csv'
108
+ n = len(x) + 1 # number of cols
109
+ s = '' if file.exists() else (('%20s,' * n % tuple(['epoch'] + self.keys)).rstrip(',') + '\n') # add header
110
+ with open(file, 'a') as f:
111
+ f.write(s + ('%20.5g,' * n % tuple([epoch] + vals)).rstrip(',') + '\n')
112
+
113
+ if self.tb:
114
+ for k, v in x.items():
115
+ self.tb.add_scalar(k, v, epoch)
116
+
117
+ if self.wandb:
118
+ self.wandb.log(x)
119
+ self.wandb.end_epoch(best_result=best_fitness == fi)
120
+
121
+ def on_model_save(self, last, epoch, final_epoch, best_fitness, fi):
122
+ # Callback runs on model save event
123
+ if self.wandb:
124
+ if ((epoch + 1) % self.opt.save_period == 0 and not final_epoch) and self.opt.save_period != -1:
125
+ self.wandb.log_model(last.parent, self.opt, epoch, fi, best_model=best_fitness == fi)
126
+
127
+ def on_train_end(self, last, best, plots, epoch):
128
+ # Callback runs on training end
129
+ if plots:
130
+ plot_results(file=self.save_dir / 'results.csv') # save results.png
131
+ files = ['results.png', 'confusion_matrix.png', *[f'{x}_curve.png' for x in ('F1', 'PR', 'P', 'R')]]
132
+ files = [(self.save_dir / f) for f in files if (self.save_dir / f).exists()] # filter
133
+
134
+ if self.tb:
135
+ import cv2
136
+ for f in files:
137
+ self.tb.add_image(f.stem, cv2.imread(str(f))[..., ::-1], epoch, dataformats='HWC')
138
+
139
+ if self.wandb:
140
+ self.wandb.log({"Results": [wandb.Image(str(f), caption=f.name) for f in files]})
141
+ # Calling wandb.log. TODO: Refactor this into WandbLogger.log_model
142
+ if not self.opt.evolve:
143
+ wandb.log_artifact(str(best if best.exists() else last), type='model',
144
+ name='run_' + self.wandb.wandb_run.id + '_model',
145
+ aliases=['latest', 'best', 'stripped'])
146
+ self.wandb.finish_run()
147
+ else:
148
+ self.wandb.finish_run()
149
+ self.wandb = WandbLogger(self.opt)
utils/loggers/wandb/README.md ADDED
@@ -0,0 +1,140 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ 📚 This guide explains how to use **Weights & Biases** (W&B) with YOLOv5 🚀.
2
+ * [About Weights & Biases](#about-weights-&-biases)
3
+ * [First-Time Setup](#first-time-setup)
4
+ * [Viewing runs](#viewing-runs)
5
+ * [Advanced Usage: Dataset Versioning and Evaluation](#advanced-usage)
6
+ * [Reports: Share your work with the world!](#reports)
7
+
8
+ ## About Weights & Biases
9
+ Think of [W&B](https://wandb.ai/site?utm_campaign=repo_yolo_wandbtutorial) like GitHub for machine learning models. With a few lines of code, save everything you need to debug, compare and reproduce your models — architecture, hyperparameters, git commits, model weights, GPU usage, and even datasets and predictions.
10
+
11
+ Used by top researchers including teams at OpenAI, Lyft, Github, and MILA, W&B is part of the new standard of best practices for machine learning. How W&B can help you optimize your machine learning workflows:
12
+
13
+ * [Debug](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Free-2) model performance in real time
14
+ * [GPU usage](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#System-4), visualized automatically
15
+ * [Custom charts](https://wandb.ai/wandb/customizable-charts/reports/Powerful-Custom-Charts-To-Debug-Model-Peformance--VmlldzoyNzY4ODI) for powerful, extensible visualization
16
+ * [Share insights](https://wandb.ai/wandb/getting-started/reports/Visualize-Debug-Machine-Learning-Models--VmlldzoyNzY5MDk#Share-8) interactively with collaborators
17
+ * [Optimize hyperparameters](https://docs.wandb.com/sweeps) efficiently
18
+ * [Track](https://docs.wandb.com/artifacts) datasets, pipelines, and production models
19
+
20
+ ## First-Time Setup
21
+ <details open>
22
+ <summary> Toggle Details </summary>
23
+ When you first train, W&B will prompt you to create a new account and will generate an **API key** for you. If you are an existing user you can retrieve your key from https://wandb.ai/authorize. This key is used to tell W&B where to log your data. You only need to supply your key once, and then it is remembered on the same device.
24
+
25
+ W&B will create a cloud **project** (default is 'YOLOv5') for your training runs, and each new training run will be provided a unique run **name** within that project as project/name. You can also manually set your project and run name as:
26
+
27
+ ```shell
28
+ $ python train.py --project ... --name ...
29
+ ```
30
+
31
+ <img alt="" width="800" src="https://user-images.githubusercontent.com/26833433/98183367-4acbc600-1f08-11eb-9a23-7266a4192355.jpg">
32
+ </details>
33
+
34
+ ## Viewing Runs
35
+ <details open>
36
+ <summary> Toggle Details </summary>
37
+ Run information streams from your environment to the W&B cloud console as you train. This allows you to monitor and even cancel runs in <b>realtime</b> . All important information is logged:
38
+
39
+ * Training & Validation losses
40
+ * Metrics: Precision, Recall, mAP@0.5, mAP@0.5:0.95
41
+ * Learning Rate over time
42
+ * A bounding box debugging panel, showing the training progress over time
43
+ * GPU: Type, **GPU Utilization**, power, temperature, **CUDA memory usage**
44
+ * System: Disk I/0, CPU utilization, RAM memory usage
45
+ * Your trained model as W&B Artifact
46
+ * Environment: OS and Python types, Git repository and state, **training command**
47
+
48
+ <img alt="" width="800" src="https://user-images.githubusercontent.com/26833433/98184457-bd3da580-1f0a-11eb-8461-95d908a71893.jpg">
49
+ </details>
50
+
51
+ ## Advanced Usage
52
+ You can leverage W&B artifacts and Tables integration to easily visualize and manage your datasets, models and training evaluations. Here are some quick examples to get you started.
53
+ <details open>
54
+ <h3>1. Visualize and Version Datasets</h3>
55
+ Log, visualize, dynamically query, and understand your data with <a href='https://docs.wandb.ai/guides/data-vis/tables'>W&B Tables</a>. You can use the following command to log your dataset as a W&B Table. This will generate a <code>{dataset}_wandb.yaml</code> file which can be used to train from dataset artifact.
56
+ <details>
57
+ <summary> <b>Usage</b> </summary>
58
+ <b>Code</b> <code> $ python utils/logger/wandb/log_dataset.py --project ... --name ... --data .. </code>
59
+
60
+ ![Screenshot (64)](https://user-images.githubusercontent.com/15766192/128486078-d8433890-98a3-4d12-8986-b6c0e3fc64b9.png)
61
+ </details>
62
+
63
+ <h3> 2: Train and Log Evaluation simultaneousy </h3>
64
+ This is an extension of the previous section, but it'll also training after uploading the dataset. <b> This also evaluation Table</b>
65
+ Evaluation table compares your predictions and ground truths across the validation set for each epoch. It uses the references to the already uploaded datasets,
66
+ so no images will be uploaded from your system more than once.
67
+ <details>
68
+ <summary> <b>Usage</b> </summary>
69
+ <b>Code</b> <code> $ python utils/logger/wandb/log_dataset.py --data .. --upload_data </code>
70
+
71
+ ![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png)
72
+ </details>
73
+
74
+ <h3> 3: Train using dataset artifact </h3>
75
+ When you upload a dataset as described in the first section, you get a new config file with an added `_wandb` to its name. This file contains the information that
76
+ can be used to train a model directly from the dataset artifact. <b> This also logs evaluation </b>
77
+ <details>
78
+ <summary> <b>Usage</b> </summary>
79
+ <b>Code</b> <code> $ python utils/logger/wandb/log_dataset.py --data {data}_wandb.yaml </code>
80
+
81
+ ![Screenshot (72)](https://user-images.githubusercontent.com/15766192/128979739-4cf63aeb-a76f-483f-8861-1c0100b938a5.png)
82
+ </details>
83
+
84
+ <h3> 4: Save model checkpoints as artifacts </h3>
85
+ To enable saving and versioning checkpoints of your experiment, pass `--save_period n` with the base cammand, where `n` represents checkpoint interval.
86
+ You can also log both the dataset and model checkpoints simultaneously. If not passed, only the final model will be logged
87
+
88
+ <details>
89
+ <summary> <b>Usage</b> </summary>
90
+ <b>Code</b> <code> $ python train.py --save_period 1 </code>
91
+
92
+ ![Screenshot (68)](https://user-images.githubusercontent.com/15766192/128726138-ec6c1f60-639d-437d-b4ee-3acd9de47ef3.png)
93
+ </details>
94
+
95
+ </details>
96
+
97
+ <h3> 5: Resume runs from checkpoint artifacts. </h3>
98
+ Any run can be resumed using artifacts if the <code>--resume</code> argument starts with <code>wandb-artifact://</code> prefix followed by the run path, i.e, <code>wandb-artifact://username/project/runid </code>. This doesn't require the model checkpoint to be present on the local system.
99
+
100
+ <details>
101
+ <summary> <b>Usage</b> </summary>
102
+ <b>Code</b> <code> $ python train.py --resume wandb-artifact://{run_path} </code>
103
+
104
+ ![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png)
105
+ </details>
106
+
107
+ <h3> 6: Resume runs from dataset artifact & checkpoint artifacts. </h3>
108
+ <b> Local dataset or model checkpoints are not required. This can be used to resume runs directly on a different device </b>
109
+ The syntax is same as the previous section, but you'll need to lof both the dataset and model checkpoints as artifacts, i.e, set bot <code>--upload_dataset</code> or
110
+ train from <code>_wandb.yaml</code> file and set <code>--save_period</code>
111
+
112
+ <details>
113
+ <summary> <b>Usage</b> </summary>
114
+ <b>Code</b> <code> $ python train.py --resume wandb-artifact://{run_path} </code>
115
+
116
+ ![Screenshot (70)](https://user-images.githubusercontent.com/15766192/128728988-4e84b355-6c87-41ae-a591-14aecf45343e.png)
117
+ </details>
118
+
119
+ </details>
120
+
121
+
122
+
123
+ <h3> Reports </h3>
124
+ W&B Reports can be created from your saved runs for sharing online. Once a report is created you will receive a link you can use to publically share your results. Here is an example report created from the COCO128 tutorial trainings of all four YOLOv5 models ([link](https://wandb.ai/glenn-jocher/yolov5_tutorial/reports/YOLOv5-COCO128-Tutorial-Results--VmlldzozMDI5OTY)).
125
+
126
+ <img alt="" width="800" src="https://user-images.githubusercontent.com/26833433/98185222-794ba000-1f0c-11eb-850f-3e9c45ad6949.jpg">
127
+
128
+ ## Environments
129
+ 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):
130
+
131
+ * **Google Colab and Kaggle** notebooks with free GPU: [![Open In Colab](https://camo.githubusercontent.com/84f0493939e0c4de4e6dbe113251b4bfb5353e57134ffd9fcab6b8714514d4d1/68747470733a2f2f636f6c61622e72657365617263682e676f6f676c652e636f6d2f6173736574732f636f6c61622d62616467652e737667)](https://colab.research.google.com/github/ultralytics/yolov5/blob/master/tutorial.ipynb) [![Open In Kaggle](https://camo.githubusercontent.com/a08ca511178e691ace596a95d334f73cf4ce06e83a5c4a5169b8bb68cac27bef/68747470733a2f2f6b6167676c652e636f6d2f7374617469632f696d616765732f6f70656e2d696e2d6b6167676c652e737667)](https://www.kaggle.com/ultralytics/yolov5)
132
+ * **Google Cloud** Deep Learning VM. See [GCP Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/GCP-Quickstart)
133
+ * **Amazon** Deep Learning AMI. See [AWS Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/AWS-Quickstart)
134
+ * **Docker Image**. See [Docker Quickstart Guide](https://github.com/ultralytics/yolov5/wiki/Docker-Quickstart) [![Docker Pulls](https://camo.githubusercontent.com/280faedaf431e4c0c24fdb30ec00a66d627404e5c4c498210d3f014dd58c2c7e/68747470733a2f2f696d672e736869656c64732e696f2f646f636b65722f70756c6c732f756c7472616c79746963732f796f6c6f76353f6c6f676f3d646f636b6572)](https://hub.docker.com/r/ultralytics/yolov5)
135
+
136
+ ## Status
137
+ ![CI CPU testing](https://github.com/ultralytics/yolov5/workflows/CI%20CPU%20testing/badge.svg)
138
+
139
+ 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.
140
+
utils/loggers/wandb/__init__.py ADDED
File without changes
utils/loggers/wandb/log_dataset.py ADDED
@@ -0,0 +1,23 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+
3
+ from wandb_utils import WandbLogger
4
+
5
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
6
+
7
+
8
+ def create_dataset_artifact(opt):
9
+ logger = WandbLogger(opt, None, job_type='Dataset Creation') # TODO: return value unused
10
+
11
+
12
+ if __name__ == '__main__':
13
+ parser = argparse.ArgumentParser()
14
+ parser.add_argument('--data', type=str, default='data/coco128.yaml', help='data.yaml path')
15
+ parser.add_argument('--single-cls', action='store_true', help='train as single-class dataset')
16
+ parser.add_argument('--project', type=str, default='YOLOv5', help='name of W&B Project')
17
+ parser.add_argument('--entity', default=None, help='W&B entity')
18
+ parser.add_argument('--name', type=str, default='log dataset', help='name of W&B run')
19
+
20
+ opt = parser.parse_args()
21
+ opt.resume = False # Explicitly disallow resume check for dataset upload job
22
+
23
+ create_dataset_artifact(opt)
utils/loggers/wandb/sweep.py ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import sys
2
+ from pathlib import Path
3
+
4
+ import wandb
5
+
6
+ FILE = Path(__file__).absolute()
7
+ sys.path.append(FILE.parents[3].as_posix()) # add utils/ to path
8
+
9
+ from train import train, parse_opt
10
+ from utils.general import increment_path
11
+ from utils.torch_utils import select_device
12
+
13
+
14
+ def sweep():
15
+ wandb.init()
16
+ # Get hyp dict from sweep agent
17
+ hyp_dict = vars(wandb.config).get("_items")
18
+
19
+ # Workaround: get necessary opt args
20
+ opt = parse_opt(known=True)
21
+ opt.batch_size = hyp_dict.get("batch_size")
22
+ opt.save_dir = str(increment_path(Path(opt.project) / opt.name, exist_ok=opt.exist_ok or opt.evolve))
23
+ opt.epochs = hyp_dict.get("epochs")
24
+ opt.nosave = True
25
+ opt.data = hyp_dict.get("data")
26
+ device = select_device(opt.device, batch_size=opt.batch_size)
27
+
28
+ # train
29
+ train(hyp_dict, opt, device)
30
+
31
+
32
+ if __name__ == "__main__":
33
+ sweep()
utils/loggers/wandb/sweep.yaml ADDED
@@ -0,0 +1,143 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hyperparameters for training
2
+ # To set range-
3
+ # Provide min and max values as:
4
+ # parameter:
5
+ #
6
+ # min: scalar
7
+ # max: scalar
8
+ # OR
9
+ #
10
+ # Set a specific list of search space-
11
+ # parameter:
12
+ # values: [scalar1, scalar2, scalar3...]
13
+ #
14
+ # You can use grid, bayesian and hyperopt search strategy
15
+ # For more info on configuring sweeps visit - https://docs.wandb.ai/guides/sweeps/configuration
16
+
17
+ program: utils/loggers/wandb/sweep.py
18
+ method: random
19
+ metric:
20
+ name: metrics/mAP_0.5
21
+ goal: maximize
22
+
23
+ parameters:
24
+ # hyperparameters: set either min, max range or values list
25
+ data:
26
+ value: "data/coco128.yaml"
27
+ batch_size:
28
+ values: [64]
29
+ epochs:
30
+ values: [10]
31
+
32
+ lr0:
33
+ distribution: uniform
34
+ min: 1e-5
35
+ max: 1e-1
36
+ lrf:
37
+ distribution: uniform
38
+ min: 0.01
39
+ max: 1.0
40
+ momentum:
41
+ distribution: uniform
42
+ min: 0.6
43
+ max: 0.98
44
+ weight_decay:
45
+ distribution: uniform
46
+ min: 0.0
47
+ max: 0.001
48
+ warmup_epochs:
49
+ distribution: uniform
50
+ min: 0.0
51
+ max: 5.0
52
+ warmup_momentum:
53
+ distribution: uniform
54
+ min: 0.0
55
+ max: 0.95
56
+ warmup_bias_lr:
57
+ distribution: uniform
58
+ min: 0.0
59
+ max: 0.2
60
+ box:
61
+ distribution: uniform
62
+ min: 0.02
63
+ max: 0.2
64
+ cls:
65
+ distribution: uniform
66
+ min: 0.2
67
+ max: 4.0
68
+ cls_pw:
69
+ distribution: uniform
70
+ min: 0.5
71
+ max: 2.0
72
+ obj:
73
+ distribution: uniform
74
+ min: 0.2
75
+ max: 4.0
76
+ obj_pw:
77
+ distribution: uniform
78
+ min: 0.5
79
+ max: 2.0
80
+ iou_t:
81
+ distribution: uniform
82
+ min: 0.1
83
+ max: 0.7
84
+ anchor_t:
85
+ distribution: uniform
86
+ min: 2.0
87
+ max: 8.0
88
+ fl_gamma:
89
+ distribution: uniform
90
+ min: 0.0
91
+ max: 0.1
92
+ hsv_h:
93
+ distribution: uniform
94
+ min: 0.0
95
+ max: 0.1
96
+ hsv_s:
97
+ distribution: uniform
98
+ min: 0.0
99
+ max: 0.9
100
+ hsv_v:
101
+ distribution: uniform
102
+ min: 0.0
103
+ max: 0.9
104
+ degrees:
105
+ distribution: uniform
106
+ min: 0.0
107
+ max: 45.0
108
+ translate:
109
+ distribution: uniform
110
+ min: 0.0
111
+ max: 0.9
112
+ scale:
113
+ distribution: uniform
114
+ min: 0.0
115
+ max: 0.9
116
+ shear:
117
+ distribution: uniform
118
+ min: 0.0
119
+ max: 10.0
120
+ perspective:
121
+ distribution: uniform
122
+ min: 0.0
123
+ max: 0.001
124
+ flipud:
125
+ distribution: uniform
126
+ min: 0.0
127
+ max: 1.0
128
+ fliplr:
129
+ distribution: uniform
130
+ min: 0.0
131
+ max: 1.0
132
+ mosaic:
133
+ distribution: uniform
134
+ min: 0.0
135
+ max: 1.0
136
+ mixup:
137
+ distribution: uniform
138
+ min: 0.0
139
+ max: 1.0
140
+ copy_paste:
141
+ distribution: uniform
142
+ min: 0.0
143
+ max: 1.0
utils/loggers/wandb/wandb_utils.py ADDED
@@ -0,0 +1,519 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Utilities and tools for tracking runs with Weights & Biases."""
2
+
3
+ import logging
4
+ import os
5
+ import sys
6
+ from contextlib import contextmanager
7
+ from pathlib import Path
8
+
9
+ import yaml
10
+ from tqdm import tqdm
11
+
12
+ FILE = Path(__file__).absolute()
13
+ sys.path.append(FILE.parents[3].as_posix()) # add yolov5/ to path
14
+
15
+ from utils.datasets import LoadImagesAndLabels
16
+ from utils.datasets import img2label_paths
17
+ from utils.general import check_dataset, check_file
18
+
19
+ try:
20
+ import wandb
21
+
22
+ assert hasattr(wandb, '__version__') # verify package import not local dir
23
+ except (ImportError, AssertionError):
24
+ wandb = None
25
+
26
+ RANK = int(os.getenv('RANK', -1))
27
+ WANDB_ARTIFACT_PREFIX = 'wandb-artifact://'
28
+
29
+
30
+ def remove_prefix(from_string, prefix=WANDB_ARTIFACT_PREFIX):
31
+ return from_string[len(prefix):]
32
+
33
+
34
+ def check_wandb_config_file(data_config_file):
35
+ wandb_config = '_wandb.'.join(data_config_file.rsplit('.', 1)) # updated data.yaml path
36
+ if Path(wandb_config).is_file():
37
+ return wandb_config
38
+ return data_config_file
39
+
40
+
41
+ def check_wandb_dataset(data_file):
42
+ is_wandb_artifact = False
43
+ if check_file(data_file) and data_file.endswith('.yaml'):
44
+ with open(data_file, errors='ignore') as f:
45
+ data_dict = yaml.safe_load(f)
46
+ is_wandb_artifact = (data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX) or
47
+ data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX))
48
+ if is_wandb_artifact:
49
+ return data_dict
50
+ else:
51
+ return check_dataset(data_file)
52
+
53
+
54
+ def get_run_info(run_path):
55
+ run_path = Path(remove_prefix(run_path, WANDB_ARTIFACT_PREFIX))
56
+ run_id = run_path.stem
57
+ project = run_path.parent.stem
58
+ entity = run_path.parent.parent.stem
59
+ model_artifact_name = 'run_' + run_id + '_model'
60
+ return entity, project, run_id, model_artifact_name
61
+
62
+
63
+ def check_wandb_resume(opt):
64
+ process_wandb_config_ddp_mode(opt) if RANK not in [-1, 0] else None
65
+ if isinstance(opt.resume, str):
66
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
67
+ if RANK not in [-1, 0]: # For resuming DDP runs
68
+ entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
69
+ api = wandb.Api()
70
+ artifact = api.artifact(entity + '/' + project + '/' + model_artifact_name + ':latest')
71
+ modeldir = artifact.download()
72
+ opt.weights = str(Path(modeldir) / "last.pt")
73
+ return True
74
+ return None
75
+
76
+
77
+ def process_wandb_config_ddp_mode(opt):
78
+ with open(check_file(opt.data), errors='ignore') as f:
79
+ data_dict = yaml.safe_load(f) # data dict
80
+ train_dir, val_dir = None, None
81
+ if isinstance(data_dict['train'], str) and data_dict['train'].startswith(WANDB_ARTIFACT_PREFIX):
82
+ api = wandb.Api()
83
+ train_artifact = api.artifact(remove_prefix(data_dict['train']) + ':' + opt.artifact_alias)
84
+ train_dir = train_artifact.download()
85
+ train_path = Path(train_dir) / 'data/images/'
86
+ data_dict['train'] = str(train_path)
87
+
88
+ if isinstance(data_dict['val'], str) and data_dict['val'].startswith(WANDB_ARTIFACT_PREFIX):
89
+ api = wandb.Api()
90
+ val_artifact = api.artifact(remove_prefix(data_dict['val']) + ':' + opt.artifact_alias)
91
+ val_dir = val_artifact.download()
92
+ val_path = Path(val_dir) / 'data/images/'
93
+ data_dict['val'] = str(val_path)
94
+ if train_dir or val_dir:
95
+ ddp_data_path = str(Path(val_dir) / 'wandb_local_data.yaml')
96
+ with open(ddp_data_path, 'w') as f:
97
+ yaml.safe_dump(data_dict, f)
98
+ opt.data = ddp_data_path
99
+
100
+
101
+ class WandbLogger():
102
+ """Log training runs, datasets, models, and predictions to Weights & Biases.
103
+
104
+ This logger sends information to W&B at wandb.ai. By default, this information
105
+ includes hyperparameters, system configuration and metrics, model metrics,
106
+ and basic data metrics and analyses.
107
+
108
+ By providing additional command line arguments to train.py, datasets,
109
+ models and predictions can also be logged.
110
+
111
+ For more on how this logger is used, see the Weights & Biases documentation:
112
+ https://docs.wandb.com/guides/integrations/yolov5
113
+ """
114
+
115
+ def __init__(self, opt, run_id=None, job_type='Training'):
116
+ """
117
+ - Initialize WandbLogger instance
118
+ - Upload dataset if opt.upload_dataset is True
119
+ - Setup trainig processes if job_type is 'Training'
120
+
121
+ arguments:
122
+ opt (namespace) -- Commandline arguments for this run
123
+ run_id (str) -- Run ID of W&B run to be resumed
124
+ job_type (str) -- To set the job_type for this run
125
+
126
+ """
127
+ # Pre-training routine --
128
+ self.job_type = job_type
129
+ self.wandb, self.wandb_run = wandb, None if not wandb else wandb.run
130
+ self.val_artifact, self.train_artifact = None, None
131
+ self.train_artifact_path, self.val_artifact_path = None, None
132
+ self.result_artifact = None
133
+ self.val_table, self.result_table = None, None
134
+ self.bbox_media_panel_images = []
135
+ self.val_table_path_map = None
136
+ self.max_imgs_to_log = 16
137
+ self.wandb_artifact_data_dict = None
138
+ self.data_dict = None
139
+ # It's more elegant to stick to 1 wandb.init call, but useful config data is overwritten in the WandbLogger's wandb.init call
140
+ if isinstance(opt.resume, str): # checks resume from artifact
141
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
142
+ entity, project, run_id, model_artifact_name = get_run_info(opt.resume)
143
+ model_artifact_name = WANDB_ARTIFACT_PREFIX + model_artifact_name
144
+ assert wandb, 'install wandb to resume wandb runs'
145
+ # Resume wandb-artifact:// runs here| workaround for not overwriting wandb.config
146
+ self.wandb_run = wandb.init(id=run_id,
147
+ project=project,
148
+ entity=entity,
149
+ resume='allow',
150
+ allow_val_change=True)
151
+ opt.resume = model_artifact_name
152
+ elif self.wandb:
153
+ self.wandb_run = wandb.init(config=opt,
154
+ resume="allow",
155
+ project='YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem,
156
+ entity=opt.entity,
157
+ name=opt.name if opt.name != 'exp' else None,
158
+ job_type=job_type,
159
+ id=run_id,
160
+ allow_val_change=True) if not wandb.run else wandb.run
161
+ if self.wandb_run:
162
+ if self.job_type == 'Training':
163
+ if opt.upload_dataset:
164
+ if not opt.resume:
165
+ self.wandb_artifact_data_dict = self.check_and_upload_dataset(opt)
166
+
167
+ if opt.resume:
168
+ # resume from artifact
169
+ if isinstance(opt.resume, str) and opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
170
+ self.data_dict = dict(self.wandb_run.config.data_dict)
171
+ else: # local resume
172
+ self.data_dict = check_wandb_dataset(opt.data)
173
+ else:
174
+ self.data_dict = check_wandb_dataset(opt.data)
175
+ self.wandb_artifact_data_dict = self.wandb_artifact_data_dict or self.data_dict
176
+
177
+ # write data_dict to config. useful for resuming from artifacts. Do this only when not resuming.
178
+ self.wandb_run.config.update({'data_dict': self.wandb_artifact_data_dict},
179
+ allow_val_change=True)
180
+ self.setup_training(opt)
181
+
182
+ if self.job_type == 'Dataset Creation':
183
+ self.data_dict = self.check_and_upload_dataset(opt)
184
+
185
+ def check_and_upload_dataset(self, opt):
186
+ """
187
+ Check if the dataset format is compatible and upload it as W&B artifact
188
+
189
+ arguments:
190
+ opt (namespace)-- Commandline arguments for current run
191
+
192
+ returns:
193
+ Updated dataset info dictionary where local dataset paths are replaced by WAND_ARFACT_PREFIX links.
194
+ """
195
+ assert wandb, 'Install wandb to upload dataset'
196
+ config_path = self.log_dataset_artifact(opt.data,
197
+ opt.single_cls,
198
+ 'YOLOv5' if opt.project == 'runs/train' else Path(opt.project).stem)
199
+ print("Created dataset config file ", config_path)
200
+ with open(config_path, errors='ignore') as f:
201
+ wandb_data_dict = yaml.safe_load(f)
202
+ return wandb_data_dict
203
+
204
+ def setup_training(self, opt):
205
+ """
206
+ Setup the necessary processes for training YOLO models:
207
+ - Attempt to download model checkpoint and dataset artifacts if opt.resume stats with WANDB_ARTIFACT_PREFIX
208
+ - Update data_dict, to contain info of previous run if resumed and the paths of dataset artifact if downloaded
209
+ - Setup log_dict, initialize bbox_interval
210
+
211
+ arguments:
212
+ opt (namespace) -- commandline arguments for this run
213
+
214
+ """
215
+ self.log_dict, self.current_epoch = {}, 0
216
+ self.bbox_interval = opt.bbox_interval
217
+ if isinstance(opt.resume, str):
218
+ modeldir, _ = self.download_model_artifact(opt)
219
+ if modeldir:
220
+ self.weights = Path(modeldir) / "last.pt"
221
+ config = self.wandb_run.config
222
+ opt.weights, opt.save_period, opt.batch_size, opt.bbox_interval, opt.epochs, opt.hyp = str(
223
+ self.weights), config.save_period, config.batch_size, config.bbox_interval, config.epochs, \
224
+ config.hyp
225
+ data_dict = self.data_dict
226
+ if self.val_artifact is None: # If --upload_dataset is set, use the existing artifact, don't download
227
+ self.train_artifact_path, self.train_artifact = self.download_dataset_artifact(data_dict.get('train'),
228
+ opt.artifact_alias)
229
+ self.val_artifact_path, self.val_artifact = self.download_dataset_artifact(data_dict.get('val'),
230
+ opt.artifact_alias)
231
+
232
+ if self.train_artifact_path is not None:
233
+ train_path = Path(self.train_artifact_path) / 'data/images/'
234
+ data_dict['train'] = str(train_path)
235
+ if self.val_artifact_path is not None:
236
+ val_path = Path(self.val_artifact_path) / 'data/images/'
237
+ data_dict['val'] = str(val_path)
238
+
239
+ if self.val_artifact is not None:
240
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
241
+ self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"])
242
+ self.val_table = self.val_artifact.get("val")
243
+ if self.val_table_path_map is None:
244
+ self.map_val_table_path()
245
+ if opt.bbox_interval == -1:
246
+ self.bbox_interval = opt.bbox_interval = (opt.epochs // 10) if opt.epochs > 10 else 1
247
+ train_from_artifact = self.train_artifact_path is not None and self.val_artifact_path is not None
248
+ # Update the the data_dict to point to local artifacts dir
249
+ if train_from_artifact:
250
+ self.data_dict = data_dict
251
+
252
+ def download_dataset_artifact(self, path, alias):
253
+ """
254
+ download the model checkpoint artifact if the path starts with WANDB_ARTIFACT_PREFIX
255
+
256
+ arguments:
257
+ path -- path of the dataset to be used for training
258
+ alias (str)-- alias of the artifact to be download/used for training
259
+
260
+ returns:
261
+ (str, wandb.Artifact) -- path of the downladed dataset and it's corresponding artifact object if dataset
262
+ is found otherwise returns (None, None)
263
+ """
264
+ if isinstance(path, str) and path.startswith(WANDB_ARTIFACT_PREFIX):
265
+ artifact_path = Path(remove_prefix(path, WANDB_ARTIFACT_PREFIX) + ":" + alias)
266
+ dataset_artifact = wandb.use_artifact(artifact_path.as_posix().replace("\\", "/"))
267
+ assert dataset_artifact is not None, "'Error: W&B dataset artifact doesn\'t exist'"
268
+ datadir = dataset_artifact.download()
269
+ return datadir, dataset_artifact
270
+ return None, None
271
+
272
+ def download_model_artifact(self, opt):
273
+ """
274
+ download the model checkpoint artifact if the resume path starts with WANDB_ARTIFACT_PREFIX
275
+
276
+ arguments:
277
+ opt (namespace) -- Commandline arguments for this run
278
+ """
279
+ if opt.resume.startswith(WANDB_ARTIFACT_PREFIX):
280
+ model_artifact = wandb.use_artifact(remove_prefix(opt.resume, WANDB_ARTIFACT_PREFIX) + ":latest")
281
+ assert model_artifact is not None, 'Error: W&B model artifact doesn\'t exist'
282
+ modeldir = model_artifact.download()
283
+ epochs_trained = model_artifact.metadata.get('epochs_trained')
284
+ total_epochs = model_artifact.metadata.get('total_epochs')
285
+ is_finished = total_epochs is None
286
+ assert not is_finished, 'training is finished, can only resume incomplete runs.'
287
+ return modeldir, model_artifact
288
+ return None, None
289
+
290
+ def log_model(self, path, opt, epoch, fitness_score, best_model=False):
291
+ """
292
+ Log the model checkpoint as W&B artifact
293
+
294
+ arguments:
295
+ path (Path) -- Path of directory containing the checkpoints
296
+ opt (namespace) -- Command line arguments for this run
297
+ epoch (int) -- Current epoch number
298
+ fitness_score (float) -- fitness score for current epoch
299
+ best_model (boolean) -- Boolean representing if the current checkpoint is the best yet.
300
+ """
301
+ model_artifact = wandb.Artifact('run_' + wandb.run.id + '_model', type='model', metadata={
302
+ 'original_url': str(path),
303
+ 'epochs_trained': epoch + 1,
304
+ 'save period': opt.save_period,
305
+ 'project': opt.project,
306
+ 'total_epochs': opt.epochs,
307
+ 'fitness_score': fitness_score
308
+ })
309
+ model_artifact.add_file(str(path / 'last.pt'), name='last.pt')
310
+ wandb.log_artifact(model_artifact,
311
+ aliases=['latest', 'last', 'epoch ' + str(self.current_epoch), 'best' if best_model else ''])
312
+ print("Saving model artifact on epoch ", epoch + 1)
313
+
314
+ def log_dataset_artifact(self, data_file, single_cls, project, overwrite_config=False):
315
+ """
316
+ Log the dataset as W&B artifact and return the new data file with W&B links
317
+
318
+ arguments:
319
+ data_file (str) -- the .yaml file with information about the dataset like - path, classes etc.
320
+ single_class (boolean) -- train multi-class data as single-class
321
+ project (str) -- project name. Used to construct the artifact path
322
+ overwrite_config (boolean) -- overwrites the data.yaml file if set to true otherwise creates a new
323
+ file with _wandb postfix. Eg -> data_wandb.yaml
324
+
325
+ returns:
326
+ the new .yaml file with artifact links. it can be used to start training directly from artifacts
327
+ """
328
+ self.data_dict = check_dataset(data_file) # parse and check
329
+ data = dict(self.data_dict)
330
+ nc, names = (1, ['item']) if single_cls else (int(data['nc']), data['names'])
331
+ names = {k: v for k, v in enumerate(names)} # to index dictionary
332
+ self.train_artifact = self.create_dataset_table(LoadImagesAndLabels(
333
+ data['train'], rect=True, batch_size=1), names, name='train') if data.get('train') else None
334
+ self.val_artifact = self.create_dataset_table(LoadImagesAndLabels(
335
+ data['val'], rect=True, batch_size=1), names, name='val') if data.get('val') else None
336
+ if data.get('train'):
337
+ data['train'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'train')
338
+ if data.get('val'):
339
+ data['val'] = WANDB_ARTIFACT_PREFIX + str(Path(project) / 'val')
340
+ path = Path(data_file).stem
341
+ path = (path if overwrite_config else path + '_wandb') + '.yaml' # updated data.yaml path
342
+ data.pop('download', None)
343
+ data.pop('path', None)
344
+ with open(path, 'w') as f:
345
+ yaml.safe_dump(data, f)
346
+
347
+ if self.job_type == 'Training': # builds correct artifact pipeline graph
348
+ self.wandb_run.use_artifact(self.val_artifact)
349
+ self.wandb_run.use_artifact(self.train_artifact)
350
+ self.val_artifact.wait()
351
+ self.val_table = self.val_artifact.get('val')
352
+ self.map_val_table_path()
353
+ else:
354
+ self.wandb_run.log_artifact(self.train_artifact)
355
+ self.wandb_run.log_artifact(self.val_artifact)
356
+ return path
357
+
358
+ def map_val_table_path(self):
359
+ """
360
+ Map the validation dataset Table like name of file -> it's id in the W&B Table.
361
+ Useful for - referencing artifacts for evaluation.
362
+ """
363
+ self.val_table_path_map = {}
364
+ print("Mapping dataset")
365
+ for i, data in enumerate(tqdm(self.val_table.data)):
366
+ self.val_table_path_map[data[3]] = data[0]
367
+
368
+ def create_dataset_table(self, dataset, class_to_id, name='dataset'):
369
+ """
370
+ Create and return W&B artifact containing W&B Table of the dataset.
371
+
372
+ arguments:
373
+ dataset (LoadImagesAndLabels) -- instance of LoadImagesAndLabels class used to iterate over the data to build Table
374
+ class_to_id (dict(int, str)) -- hash map that maps class ids to labels
375
+ name (str) -- name of the artifact
376
+
377
+ returns:
378
+ dataset artifact to be logged or used
379
+ """
380
+ # TODO: Explore multiprocessing to slpit this loop parallely| This is essential for speeding up the the logging
381
+ artifact = wandb.Artifact(name=name, type="dataset")
382
+ img_files = tqdm([dataset.path]) if isinstance(dataset.path, str) and Path(dataset.path).is_dir() else None
383
+ img_files = tqdm(dataset.img_files) if not img_files else img_files
384
+ for img_file in img_files:
385
+ if Path(img_file).is_dir():
386
+ artifact.add_dir(img_file, name='data/images')
387
+ labels_path = 'labels'.join(dataset.path.rsplit('images', 1))
388
+ artifact.add_dir(labels_path, name='data/labels')
389
+ else:
390
+ artifact.add_file(img_file, name='data/images/' + Path(img_file).name)
391
+ label_file = Path(img2label_paths([img_file])[0])
392
+ artifact.add_file(str(label_file),
393
+ name='data/labels/' + label_file.name) if label_file.exists() else None
394
+ table = wandb.Table(columns=["id", "train_image", "Classes", "name"])
395
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in class_to_id.items()])
396
+ for si, (img, labels, paths, shapes) in enumerate(tqdm(dataset)):
397
+ box_data, img_classes = [], {}
398
+ for cls, *xywh in labels[:, 1:].tolist():
399
+ cls = int(cls)
400
+ box_data.append({"position": {"middle": [xywh[0], xywh[1]], "width": xywh[2], "height": xywh[3]},
401
+ "class_id": cls,
402
+ "box_caption": "%s" % (class_to_id[cls])})
403
+ img_classes[cls] = class_to_id[cls]
404
+ boxes = {"ground_truth": {"box_data": box_data, "class_labels": class_to_id}} # inference-space
405
+ table.add_data(si, wandb.Image(paths, classes=class_set, boxes=boxes), list(img_classes.values()),
406
+ Path(paths).name)
407
+ artifact.add(table, name)
408
+ return artifact
409
+
410
+ def log_training_progress(self, predn, path, names):
411
+ """
412
+ Build evaluation Table. Uses reference from validation dataset table.
413
+
414
+ arguments:
415
+ predn (list): list of predictions in the native space in the format - [xmin, ymin, xmax, ymax, confidence, class]
416
+ path (str): local path of the current evaluation image
417
+ names (dict(int, str)): hash map that maps class ids to labels
418
+ """
419
+ class_set = wandb.Classes([{'id': id, 'name': name} for id, name in names.items()])
420
+ box_data = []
421
+ total_conf = 0
422
+ for *xyxy, conf, cls in predn.tolist():
423
+ if conf >= 0.25:
424
+ box_data.append(
425
+ {"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
426
+ "class_id": int(cls),
427
+ "box_caption": "%s %.3f" % (names[cls], conf),
428
+ "scores": {"class_score": conf},
429
+ "domain": "pixel"})
430
+ total_conf = total_conf + conf
431
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
432
+ id = self.val_table_path_map[Path(path).name]
433
+ self.result_table.add_data(self.current_epoch,
434
+ id,
435
+ self.val_table.data[id][1],
436
+ wandb.Image(self.val_table.data[id][1], boxes=boxes, classes=class_set),
437
+ total_conf / max(1, len(box_data))
438
+ )
439
+
440
+ def val_one_image(self, pred, predn, path, names, im):
441
+ """
442
+ Log validation data for one image. updates the result Table if validation dataset is uploaded and log bbox media panel
443
+
444
+ arguments:
445
+ pred (list): list of scaled predictions in the format - [xmin, ymin, xmax, ymax, confidence, class]
446
+ predn (list): list of predictions in the native space - [xmin, ymin, xmax, ymax, confidence, class]
447
+ path (str): local path of the current evaluation image
448
+ """
449
+ if self.val_table and self.result_table: # Log Table if Val dataset is uploaded as artifact
450
+ self.log_training_progress(predn, path, names)
451
+
452
+ if len(self.bbox_media_panel_images) < self.max_imgs_to_log and self.current_epoch > 0:
453
+ if self.current_epoch % self.bbox_interval == 0:
454
+ box_data = [{"position": {"minX": xyxy[0], "minY": xyxy[1], "maxX": xyxy[2], "maxY": xyxy[3]},
455
+ "class_id": int(cls),
456
+ "box_caption": "%s %.3f" % (names[cls], conf),
457
+ "scores": {"class_score": conf},
458
+ "domain": "pixel"} for *xyxy, conf, cls in pred.tolist()]
459
+ boxes = {"predictions": {"box_data": box_data, "class_labels": names}} # inference-space
460
+ self.bbox_media_panel_images.append(wandb.Image(im, boxes=boxes, caption=path.name))
461
+
462
+ def log(self, log_dict):
463
+ """
464
+ save the metrics to the logging dictionary
465
+
466
+ arguments:
467
+ log_dict (Dict) -- metrics/media to be logged in current step
468
+ """
469
+ if self.wandb_run:
470
+ for key, value in log_dict.items():
471
+ self.log_dict[key] = value
472
+
473
+ def end_epoch(self, best_result=False):
474
+ """
475
+ commit the log_dict, model artifacts and Tables to W&B and flush the log_dict.
476
+
477
+ arguments:
478
+ best_result (boolean): Boolean representing if the result of this evaluation is best or not
479
+ """
480
+ if self.wandb_run:
481
+ with all_logging_disabled():
482
+ if self.bbox_media_panel_images:
483
+ self.log_dict["Bounding Box Debugger/Images"] = self.bbox_media_panel_images
484
+ wandb.log(self.log_dict)
485
+ self.log_dict = {}
486
+ self.bbox_media_panel_images = []
487
+ if self.result_artifact:
488
+ self.result_artifact.add(self.result_table, 'result')
489
+ wandb.log_artifact(self.result_artifact, aliases=['latest', 'last', 'epoch ' + str(self.current_epoch),
490
+ ('best' if best_result else '')])
491
+
492
+ wandb.log({"evaluation": self.result_table})
493
+ self.result_table = wandb.Table(["epoch", "id", "ground truth", "prediction", "avg_confidence"])
494
+ self.result_artifact = wandb.Artifact("run_" + wandb.run.id + "_progress", "evaluation")
495
+
496
+ def finish_run(self):
497
+ """
498
+ Log metrics if any and finish the current W&B run
499
+ """
500
+ if self.wandb_run:
501
+ if self.log_dict:
502
+ with all_logging_disabled():
503
+ wandb.log(self.log_dict)
504
+ wandb.run.finish()
505
+
506
+
507
+ @contextmanager
508
+ def all_logging_disabled(highest_level=logging.CRITICAL):
509
+ """ source - https://gist.github.com/simon-weber/7853144
510
+ A context manager that will prevent any logging messages triggered during the body from being processed.
511
+ :param highest_level: the maximum logging level in use.
512
+ This would only need to be changed if a custom level greater than CRITICAL is defined.
513
+ """
514
+ previous_level = logging.root.manager.disable
515
+ logging.disable(highest_level)
516
+ try:
517
+ yield
518
+ finally:
519
+ logging.disable(previous_level)
utils/loss.py ADDED
@@ -0,0 +1,262 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Loss functions
4
+ """
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+
9
+ from utils.metrics import bbox_iou
10
+ from utils.torch_utils import is_parallel
11
+
12
+
13
+ def smooth_BCE(eps=0.1): # https://github.com/ultralytics/yolov3/issues/238#issuecomment-598028441
14
+ # return positive, negative label smoothing BCE targets
15
+ return 1.0 - 0.5 * eps, 0.5 * eps
16
+
17
+
18
+ class BCEBlurWithLogitsLoss(nn.Module):
19
+ # BCEwithLogitLoss() with reduced missing label effects.
20
+ def __init__(self, alpha=0.05):
21
+ super(BCEBlurWithLogitsLoss, self).__init__()
22
+ self.loss_fcn = nn.BCEWithLogitsLoss(reduction='none') # must be nn.BCEWithLogitsLoss()
23
+ self.alpha = alpha
24
+
25
+ def forward(self, pred, true):
26
+ loss = self.loss_fcn(pred, true)
27
+ pred = torch.sigmoid(pred) # prob from logits
28
+ dx = pred - true # reduce only missing label effects
29
+ # dx = (pred - true).abs() # reduce missing label and false label effects
30
+ alpha_factor = 1 - torch.exp((dx - 1) / (self.alpha + 1e-4))
31
+ loss *= alpha_factor
32
+ return loss.mean()
33
+
34
+
35
+ class FocalLoss(nn.Module):
36
+ # Wraps focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
37
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
38
+ super(FocalLoss, self).__init__()
39
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
40
+ self.gamma = gamma
41
+ self.alpha = alpha
42
+ self.reduction = loss_fcn.reduction
43
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
44
+
45
+ def forward(self, pred, true):
46
+ loss = self.loss_fcn(pred, true)
47
+ # p_t = torch.exp(-loss)
48
+ # loss *= self.alpha * (1.000001 - p_t) ** self.gamma # non-zero power for gradient stability
49
+
50
+ # TF implementation https://github.com/tensorflow/addons/blob/v0.7.1/tensorflow_addons/losses/focal_loss.py
51
+ pred_prob = torch.sigmoid(pred) # prob from logits
52
+ p_t = true * pred_prob + (1 - true) * (1 - pred_prob)
53
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
54
+ modulating_factor = (1.0 - p_t) ** self.gamma
55
+ loss *= alpha_factor * modulating_factor
56
+
57
+ if self.reduction == 'mean':
58
+ return loss.mean()
59
+ elif self.reduction == 'sum':
60
+ return loss.sum()
61
+ else: # 'none'
62
+ return loss
63
+
64
+
65
+ class QFocalLoss(nn.Module):
66
+ # Wraps Quality focal loss around existing loss_fcn(), i.e. criteria = FocalLoss(nn.BCEWithLogitsLoss(), gamma=1.5)
67
+ def __init__(self, loss_fcn, gamma=1.5, alpha=0.25):
68
+ super(QFocalLoss, self).__init__()
69
+ self.loss_fcn = loss_fcn # must be nn.BCEWithLogitsLoss()
70
+ self.gamma = gamma
71
+ self.alpha = alpha
72
+ self.reduction = loss_fcn.reduction
73
+ self.loss_fcn.reduction = 'none' # required to apply FL to each element
74
+
75
+ def forward(self, pred, true):
76
+ loss = self.loss_fcn(pred, true)
77
+
78
+ pred_prob = torch.sigmoid(pred) # prob from logits
79
+ alpha_factor = true * self.alpha + (1 - true) * (1 - self.alpha)
80
+ modulating_factor = torch.abs(true - pred_prob) ** self.gamma
81
+ loss *= alpha_factor * modulating_factor
82
+
83
+ if self.reduction == 'mean':
84
+ return loss.mean()
85
+ elif self.reduction == 'sum':
86
+ return loss.sum()
87
+ else: # 'none'
88
+ return loss
89
+
90
+
91
+ class ComputeLoss:
92
+ # Compute losses
93
+ def __init__(self, model, autobalance=False, num_coords=0):
94
+ super(ComputeLoss, self).__init__()
95
+ self.sort_obj_iou = False
96
+ device = next(model.parameters()).device # get model device
97
+ h = model.hyp # hyperparameters
98
+
99
+ # Define criteria
100
+ BCEcls = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['cls_pw']], device=device))
101
+ BCEobj = nn.BCEWithLogitsLoss(pos_weight=torch.tensor([h['obj_pw']], device=device))
102
+
103
+ # Class label smoothing https://arxiv.org/pdf/1902.04103.pdf eqn 3
104
+ self.cp, self.cn = smooth_BCE(eps=h.get('label_smoothing', 0.0)) # positive, negative BCE targets
105
+
106
+ # Focal loss
107
+ g = h['fl_gamma'] # focal loss gamma
108
+ if g > 0:
109
+ BCEcls, BCEobj = FocalLoss(BCEcls, g), FocalLoss(BCEobj, g)
110
+
111
+ det = model.module.model[-1] if is_parallel(model) else model.model[-1] # Detect() module
112
+ self.balance = {3: [4.0, 1.0, 0.4]}.get(det.nl, [4.0, 1.0, 0.25, 0.06, .02]) # P3-P7
113
+ self.ssi = list(det.stride).index(16) if autobalance else 0 # stride 16 index
114
+ self.BCEcls, self.BCEobj, self.gr, self.hyp, self.autobalance = BCEcls, BCEobj, 1.0, h, autobalance
115
+
116
+ if self.autobalance:
117
+ self.loss_coeffs = model.module.loss_coeffs if is_parallel(model) else model.loss_coeffs[-1]
118
+
119
+ # for k in 'na', 'nc', 'nl', 'anchors':
120
+ # setattr(self, k, getattr(det, k))
121
+ self.num_coords = num_coords
122
+ self.na = det.na
123
+ self.nc = det.nc
124
+ self.nl = det.nl
125
+ self.anchors = det.anchors
126
+
127
+ def __call__(self, p, targets): # predictions, targets, model
128
+ device = targets.device
129
+ lcls = torch.zeros(1, device=device)
130
+ lbox = torch.zeros(1, device=device)
131
+ lobj = torch.zeros(1, device=device)
132
+ lkps = torch.zeros(1, device=device) # keypoint loss
133
+ tcls, tbox, tkps, indices, anchors = self.build_targets(p, targets) # targets
134
+
135
+ # Losses
136
+ for i, pi in enumerate(p): # layer index, layer predictions
137
+ b, a, gj, gi = indices[i] # image, anchor, gridy, gridx
138
+ tobj = torch.zeros_like(pi[..., 0], device=device) # target obj
139
+
140
+ n = b.shape[0] # number of targets
141
+ if n:
142
+ ps = pi[b, a, gj, gi] # prediction subset corresponding to targets
143
+
144
+ # Regression
145
+ pxy = ps[:, :2].sigmoid() * 2. - 0.5
146
+ pwh = (ps[:, 2:4].sigmoid() * 2) ** 2 * anchors[i] # range [0, 4] * anchor
147
+ pbox = torch.cat((pxy, pwh), 1) # predicted box
148
+ iou = bbox_iou(pbox.T, tbox[i], x1y1x2y2=False, CIoU=True) # iou(prediction, target)
149
+ lbox += (1.0 - iou).mean() # iou loss
150
+
151
+ # Keypoints
152
+ if self.num_coords:
153
+ tkp = tkps[i]
154
+ vis = tkp[..., 2] > 0
155
+ tkp_vis = tkp[vis]
156
+ if len(tkp_vis):
157
+ pkp = ps[:, 5 + self.nc:].reshape((-1, self.num_coords // 2, 2))
158
+ pkp = (pkp.sigmoid() * 4. - 2.) * anchors[i][:, None, :] # range [-2, 2] * anchor
159
+ pkp_vis = pkp[vis]
160
+ l2 = torch.linalg.norm(pkp_vis - tkp_vis[..., :2], dim=-1)
161
+ lkps += torch.mean(l2)
162
+
163
+ # Objectness
164
+ score_iou = iou.detach().clamp(0).type(tobj.dtype)
165
+ if self.sort_obj_iou:
166
+ sort_id = torch.argsort(score_iou)
167
+ b, a, gj, gi, score_iou = b[sort_id], a[sort_id], gj[sort_id], gi[sort_id], score_iou[sort_id]
168
+ tobj[b, a, gj, gi] = (1.0 - self.gr) + self.gr * score_iou # iou ratio
169
+
170
+ # Classification
171
+ if self.nc > 1: # cls loss (only if multiple classes)
172
+ t = torch.full_like(ps[:, 5:5 + self.nc], self.cn, device=device) # targets
173
+ t[range(n), tcls[i]] = self.cp
174
+ lcls += self.BCEcls(ps[:, 5:5 + self.nc], t) # BCE
175
+
176
+ # Append targets to text file
177
+ # with open('targets.txt', 'a') as file:
178
+ # [file.write('%11.5g ' * 4 % tuple(x) + '\n') for x in torch.cat((txy[i], twh[i]), 1)]
179
+
180
+ obji = self.BCEobj(pi[..., 4], tobj)
181
+ lobj += obji * self.balance[i] # obj loss
182
+
183
+ lbox *= self.hyp['box']
184
+ lobj *= self.hyp['obj']
185
+ lcls *= self.hyp['cls']
186
+ lkps *= self.hyp['kp']
187
+
188
+ if self.autobalance:
189
+ loss = (lbox + lobj + lcls) / (torch.exp(2 * self.loss_coeffs[0])) + self.loss_coeffs[0]
190
+ loss += lkps / (torch.exp(2 * self.loss_coeffs[1])) + self.loss_coeffs[1]
191
+ else:
192
+ loss = lbox + lobj + lcls + lkps
193
+
194
+ bs = tobj.shape[0] # batch size
195
+
196
+ return loss * bs, torch.cat((lbox, lobj, lcls, lkps)).detach()
197
+
198
+ def build_targets(self, p, targets):
199
+ # Build targets for compute_loss(), input targets(image,class,x,y,w,h, x1,y1,v1, ..., x17,y17,v17)
200
+ na, nt = self.na, targets.shape[0] # number of anchors, targets
201
+ tcls, tbox, tkps, indices, anch = [], [], [], [], []
202
+ gain = torch.ones(7 + self.num_coords * 3 // 2, device=targets.device) # normalized to gridspace gain
203
+ ai = torch.arange(na, device=targets.device).float().view(na, 1).repeat(1, nt) # same as .repeat_interleave(nt)
204
+ targets = torch.cat((targets.repeat(na, 1, 1), ai[:, :, None]), 2) # append anchor indices
205
+
206
+ g = 0.5 # bias
207
+ off = torch.tensor([[0, 0],
208
+ [1, 0], [0, 1], [-1, 0], [0, -1], # j,k,l,m
209
+ # [1, 1], [1, -1], [-1, 1], [-1, -1], # jk,jm,lk,lm
210
+ ], device=targets.device).float() * g # offsets
211
+
212
+ for i in range(self.nl):
213
+ anchors = self.anchors[i]
214
+ xy_gain = torch.tensor(p[i].shape)[[3, 2]]
215
+ gain[2:4] = xy_gain
216
+ gain[4:6] = xy_gain
217
+ for j in range(self.num_coords // 2):
218
+ kp_idx = 6 + j * 3
219
+ gain[kp_idx:kp_idx + 2] = xy_gain
220
+
221
+ # Match targets to anchors
222
+ t = targets * gain
223
+ if nt:
224
+ # Matches
225
+ r = t[:, :, 4:6] / anchors[:, None] # wh ratio
226
+ j = torch.max(r, 1. / r).max(2)[0] < self.hyp['anchor_t'] # compare
227
+ # j = wh_iou(anchors, t[:, 4:6]) > model.hyp['iou_t'] # iou(3,n)=wh_iou(anchors(3,2), gwh(n,2))
228
+ t = t[j] # filter
229
+
230
+ # Offsets
231
+ gxy = t[:, 2:4] # grid xy
232
+ gxi = gain[[2, 3]] - gxy # inverse
233
+ j, k = ((gxy % 1. < g) & (gxy > 1.)).T
234
+ l, m = ((gxi % 1. < g) & (gxi > 1.)).T
235
+ j = torch.stack((torch.ones_like(j), j, k, l, m))
236
+ t = t.repeat((5, 1, 1))[j]
237
+ offsets = (torch.zeros_like(gxy)[None] + off[:, None])[j]
238
+ else:
239
+ t = targets[0]
240
+ offsets = 0
241
+
242
+ # Define
243
+ b = t[:, 0].long() # image
244
+ c = t[:, 1].long() # class
245
+ gxy = t[:, 2:4] # grid xy
246
+ gwh = t[:, 4:6] # grid wh
247
+ gij = (gxy - offsets).long()
248
+ gi, gj = gij.T # grid xy indices
249
+
250
+ if self.num_coords:
251
+ kp = t[:, 6:-1].reshape(-1, self.num_coords // 2, 3)
252
+ kp[..., :2] -= gij[:, None, :] # grid kp relative to grid box anchor
253
+ tkps.append(kp)
254
+
255
+ # Append
256
+ a = t[:, -1].long() # anchor indices
257
+ indices.append((b, a, gj.clamp_(0, gain[3] - 1), gi.clamp_(0, gain[2] - 1))) # image, anchor, grid indices
258
+ tbox.append(torch.cat((gxy - gij, gwh), 1)) # box
259
+ anch.append(anchors[a]) # anchors
260
+ tcls.append(c) # class
261
+
262
+ return tcls, tbox, tkps, indices, anch
utils/metrics.py ADDED
@@ -0,0 +1,333 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Model validation metrics
4
+ """
5
+
6
+ import math
7
+ import warnings
8
+ from pathlib import Path
9
+
10
+ import matplotlib.pyplot as plt
11
+ import numpy as np
12
+ import torch
13
+
14
+
15
+ def fitness(x):
16
+ # Model fitness as a weighted combination of metrics
17
+ w = [0.0, 0.0, 0.1, 0.9] # weights for [P, R, mAP@0.5, mAP@0.5:0.95]
18
+ return (x[:, :4] * w).sum(1)
19
+
20
+
21
+ def ap_per_class(tp, conf, pred_cls, target_cls, plot=False, save_dir='.', names=()):
22
+ """ Compute the average precision, given the recall and precision curves.
23
+ Source: https://github.com/rafaelpadilla/Object-Detection-Metrics.
24
+ # Arguments
25
+ tp: True positives (nparray, nx1 or nx10).
26
+ conf: Objectness value from 0-1 (nparray).
27
+ pred_cls: Predicted object classes (nparray).
28
+ target_cls: True object classes (nparray).
29
+ plot: Plot precision-recall curve at mAP@0.5
30
+ save_dir: Plot save directory
31
+ # Returns
32
+ The average precision as computed in py-faster-rcnn.
33
+ """
34
+
35
+ # Sort by objectness
36
+ i = np.argsort(-conf)
37
+ tp, conf, pred_cls = tp[i], conf[i], pred_cls[i]
38
+
39
+ # Find unique classes
40
+ unique_classes = np.unique(target_cls)
41
+ nc = unique_classes.shape[0] # number of classes, number of detections
42
+
43
+ # Create Precision-Recall curve and compute AP for each class
44
+ px, py = np.linspace(0, 1, 1000), [] # for plotting
45
+ ap, p, r = np.zeros((nc, tp.shape[1])), np.zeros((nc, 1000)), np.zeros((nc, 1000))
46
+ for ci, c in enumerate(unique_classes):
47
+ i = pred_cls == c
48
+ n_l = (target_cls == c).sum() # number of labels
49
+ n_p = i.sum() # number of predictions
50
+
51
+ if n_p == 0 or n_l == 0:
52
+ continue
53
+ else:
54
+ # Accumulate FPs and TPs
55
+ fpc = (1 - tp[i]).cumsum(0)
56
+ tpc = tp[i].cumsum(0)
57
+
58
+ # Recall
59
+ recall = tpc / (n_l + 1e-16) # recall curve
60
+ r[ci] = np.interp(-px, -conf[i], recall[:, 0], left=0) # negative x, xp because xp decreases
61
+
62
+ # Precision
63
+ precision = tpc / (tpc + fpc) # precision curve
64
+ p[ci] = np.interp(-px, -conf[i], precision[:, 0], left=1) # p at pr_score
65
+
66
+ # AP from recall-precision curve
67
+ for j in range(tp.shape[1]):
68
+ ap[ci, j], mpre, mrec = compute_ap(recall[:, j], precision[:, j])
69
+ if plot and j == 0:
70
+ py.append(np.interp(px, mrec, mpre)) # precision at mAP@0.5
71
+
72
+ # Compute F1 (harmonic mean of precision and recall)
73
+ f1 = 2 * p * r / (p + r + 1e-16)
74
+ if plot:
75
+ plot_pr_curve(px, py, ap, Path(save_dir) / 'PR_curve.png', names)
76
+ plot_mc_curve(px, f1, Path(save_dir) / 'F1_curve.png', names, ylabel='F1')
77
+ plot_mc_curve(px, p, Path(save_dir) / 'P_curve.png', names, ylabel='Precision')
78
+ plot_mc_curve(px, r, Path(save_dir) / 'R_curve.png', names, ylabel='Recall')
79
+
80
+ i = f1.mean(0).argmax() # max F1 index
81
+ return p[:, i], r[:, i], ap, f1[:, i], unique_classes.astype('int32')
82
+
83
+
84
+ def compute_ap(recall, precision):
85
+ """ Compute the average precision, given the recall and precision curves
86
+ # Arguments
87
+ recall: The recall curve (list)
88
+ precision: The precision curve (list)
89
+ # Returns
90
+ Average precision, precision curve, recall curve
91
+ """
92
+
93
+ # Append sentinel values to beginning and end
94
+ mrec = np.concatenate(([0.0], recall, [1.0]))
95
+ mpre = np.concatenate(([1.0], precision, [0.0]))
96
+
97
+ # Compute the precision envelope
98
+ mpre = np.flip(np.maximum.accumulate(np.flip(mpre)))
99
+
100
+ # Integrate area under curve
101
+ method = 'interp' # methods: 'continuous', 'interp'
102
+ if method == 'interp':
103
+ x = np.linspace(0, 1, 101) # 101-point interp (COCO)
104
+ ap = np.trapz(np.interp(x, mrec, mpre), x) # integrate
105
+ else: # 'continuous'
106
+ i = np.where(mrec[1:] != mrec[:-1])[0] # points where x axis (recall) changes
107
+ ap = np.sum((mrec[i + 1] - mrec[i]) * mpre[i + 1]) # area under curve
108
+
109
+ return ap, mpre, mrec
110
+
111
+
112
+ class ConfusionMatrix:
113
+ # Updated version of https://github.com/kaanakan/object_detection_confusion_matrix
114
+ def __init__(self, nc, conf=0.25, iou_thres=0.45):
115
+ self.matrix = np.zeros((nc + 1, nc + 1))
116
+ self.nc = nc # number of classes
117
+ self.conf = conf
118
+ self.iou_thres = iou_thres
119
+
120
+ def process_batch(self, detections, labels):
121
+ """
122
+ Return intersection-over-union (Jaccard index) of boxes.
123
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
124
+ Arguments:
125
+ detections (Array[N, 6]), x1, y1, x2, y2, conf, class
126
+ labels (Array[M, 5]), class, x1, y1, x2, y2
127
+ Returns:
128
+ None, updates confusion matrix accordingly
129
+ """
130
+ detections = detections[detections[:, 4] > self.conf]
131
+ gt_classes = labels[:, 0].int()
132
+ detection_classes = detections[:, 5].int()
133
+ iou = box_iou(labels[:, 1:], detections[:, :4])
134
+
135
+ x = torch.where(iou > self.iou_thres)
136
+ if x[0].shape[0]:
137
+ matches = torch.cat((torch.stack(x, 1), iou[x[0], x[1]][:, None]), 1).cpu().numpy()
138
+ if x[0].shape[0] > 1:
139
+ matches = matches[matches[:, 2].argsort()[::-1]]
140
+ matches = matches[np.unique(matches[:, 1], return_index=True)[1]]
141
+ matches = matches[matches[:, 2].argsort()[::-1]]
142
+ matches = matches[np.unique(matches[:, 0], return_index=True)[1]]
143
+ else:
144
+ matches = np.zeros((0, 3))
145
+
146
+ n = matches.shape[0] > 0
147
+ m0, m1, _ = matches.transpose().astype(np.int16)
148
+ for i, gc in enumerate(gt_classes):
149
+ j = m0 == i
150
+ if n and sum(j) == 1:
151
+ self.matrix[detection_classes[m1[j]], gc] += 1 # correct
152
+ else:
153
+ self.matrix[self.nc, gc] += 1 # background FP
154
+
155
+ if n:
156
+ for i, dc in enumerate(detection_classes):
157
+ if not any(m1 == i):
158
+ self.matrix[dc, self.nc] += 1 # background FN
159
+
160
+ def matrix(self):
161
+ return self.matrix
162
+
163
+ def plot(self, normalize=True, save_dir='', names=()):
164
+ try:
165
+ import seaborn as sn
166
+
167
+ array = self.matrix / ((self.matrix.sum(0).reshape(1, -1) + 1E-6) if normalize else 1) # normalize columns
168
+ array[array < 0.005] = np.nan # don't annotate (would appear as 0.00)
169
+
170
+ fig = plt.figure(figsize=(12, 9), tight_layout=True)
171
+ sn.set(font_scale=1.0 if self.nc < 50 else 0.8) # for label size
172
+ labels = (0 < len(names) < 99) and len(names) == self.nc # apply names to ticklabels
173
+ with warnings.catch_warnings():
174
+ warnings.simplefilter('ignore') # suppress empty matrix RuntimeWarning: All-NaN slice encountered
175
+ sn.heatmap(array, annot=self.nc < 30, annot_kws={"size": 8}, cmap='Blues', fmt='.2f', square=True,
176
+ xticklabels=names + ['background FP'] if labels else "auto",
177
+ yticklabels=names + ['background FN'] if labels else "auto").set_facecolor((1, 1, 1))
178
+ fig.axes[0].set_xlabel('True')
179
+ fig.axes[0].set_ylabel('Predicted')
180
+ fig.savefig(Path(save_dir) / 'confusion_matrix.png', dpi=250)
181
+ plt.close()
182
+ except Exception as e:
183
+ print(f'WARNING: ConfusionMatrix plot failure: {e}')
184
+
185
+ def print(self):
186
+ for i in range(self.nc + 1):
187
+ print(' '.join(map(str, self.matrix[i])))
188
+
189
+
190
+ def bbox_iou(box1, box2, x1y1x2y2=True, GIoU=False, DIoU=False, CIoU=False, eps=1e-7):
191
+ # Returns the IoU of box1 to box2. box1 is 4, box2 is nx4
192
+ box2 = box2.T
193
+
194
+ # Get the coordinates of bounding boxes
195
+ if x1y1x2y2: # x1, y1, x2, y2 = box1
196
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
197
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
198
+ else: # transform from xywh to xyxy
199
+ b1_x1, b1_x2 = box1[0] - box1[2] / 2, box1[0] + box1[2] / 2
200
+ b1_y1, b1_y2 = box1[1] - box1[3] / 2, box1[1] + box1[3] / 2
201
+ b2_x1, b2_x2 = box2[0] - box2[2] / 2, box2[0] + box2[2] / 2
202
+ b2_y1, b2_y2 = box2[1] - box2[3] / 2, box2[1] + box2[3] / 2
203
+
204
+ # Intersection area
205
+ inter = (torch.min(b1_x2, b2_x2) - torch.max(b1_x1, b2_x1)).clamp(0) * \
206
+ (torch.min(b1_y2, b2_y2) - torch.max(b1_y1, b2_y1)).clamp(0)
207
+
208
+ # Union Area
209
+ w1, h1 = b1_x2 - b1_x1, b1_y2 - b1_y1 + eps
210
+ w2, h2 = b2_x2 - b2_x1, b2_y2 - b2_y1 + eps
211
+ union = w1 * h1 + w2 * h2 - inter + eps
212
+
213
+ iou = inter / union
214
+ if GIoU or DIoU or CIoU:
215
+ cw = torch.max(b1_x2, b2_x2) - torch.min(b1_x1, b2_x1) # convex (smallest enclosing box) width
216
+ ch = torch.max(b1_y2, b2_y2) - torch.min(b1_y1, b2_y1) # convex height
217
+ if CIoU or DIoU: # Distance or Complete IoU https://arxiv.org/abs/1911.08287v1
218
+ c2 = cw ** 2 + ch ** 2 + eps # convex diagonal squared
219
+ rho2 = ((b2_x1 + b2_x2 - b1_x1 - b1_x2) ** 2 +
220
+ (b2_y1 + b2_y2 - b1_y1 - b1_y2) ** 2) / 4 # center distance squared
221
+ if DIoU:
222
+ return iou - rho2 / c2 # DIoU
223
+ elif CIoU: # https://github.com/Zzh-tju/DIoU-SSD-pytorch/blob/master/utils/box/box_utils.py#L47
224
+ v = (4 / math.pi ** 2) * torch.pow(torch.atan(w2 / h2) - torch.atan(w1 / h1), 2)
225
+ with torch.no_grad():
226
+ alpha = v / (v - iou + (1 + eps))
227
+ return iou - (rho2 / c2 + v * alpha) # CIoU
228
+ else: # GIoU https://arxiv.org/pdf/1902.09630.pdf
229
+ c_area = cw * ch + eps # convex area
230
+ return iou - (c_area - union) / c_area # GIoU
231
+ else:
232
+ return iou # IoU
233
+
234
+
235
+ def box_iou(box1, box2):
236
+ # https://github.com/pytorch/vision/blob/master/torchvision/ops/boxes.py
237
+ """
238
+ Return intersection-over-union (Jaccard index) of boxes.
239
+ Both sets of boxes are expected to be in (x1, y1, x2, y2) format.
240
+ Arguments:
241
+ box1 (Tensor[N, 4])
242
+ box2 (Tensor[M, 4])
243
+ Returns:
244
+ iou (Tensor[N, M]): the NxM matrix containing the pairwise
245
+ IoU values for every element in boxes1 and boxes2
246
+ """
247
+
248
+ def box_area(box):
249
+ # box = 4xn
250
+ return (box[2] - box[0]) * (box[3] - box[1])
251
+
252
+ area1 = box_area(box1.T)
253
+ area2 = box_area(box2.T)
254
+
255
+ # inter(N,M) = (rb(N,M,2) - lt(N,M,2)).clamp(0).prod(2)
256
+ inter = (torch.min(box1[:, None, 2:], box2[:, 2:]) - torch.max(box1[:, None, :2], box2[:, :2])).clamp(0).prod(2)
257
+ return inter / (area1[:, None] + area2 - inter) # iou = inter / (area1 + area2 - inter)
258
+
259
+
260
+ def bbox_ioa(box1, box2, eps=1E-7):
261
+ """ Returns the intersection over box2 area given box1, box2. Boxes are x1y1x2y2
262
+ box1: np.array of shape(4)
263
+ box2: np.array of shape(nx4)
264
+ returns: np.array of shape(n)
265
+ """
266
+
267
+ box2 = box2.transpose()
268
+
269
+ # Get the coordinates of bounding boxes
270
+ b1_x1, b1_y1, b1_x2, b1_y2 = box1[0], box1[1], box1[2], box1[3]
271
+ b2_x1, b2_y1, b2_x2, b2_y2 = box2[0], box2[1], box2[2], box2[3]
272
+
273
+ # Intersection area
274
+ inter_area = (np.minimum(b1_x2, b2_x2) - np.maximum(b1_x1, b2_x1)).clip(0) * \
275
+ (np.minimum(b1_y2, b2_y2) - np.maximum(b1_y1, b2_y1)).clip(0)
276
+
277
+ # box2 area
278
+ box2_area = (b2_x2 - b2_x1) * (b2_y2 - b2_y1) + eps
279
+
280
+ # Intersection over box2 area
281
+ return inter_area / box2_area
282
+
283
+
284
+ def wh_iou(wh1, wh2):
285
+ # Returns the nxm IoU matrix. wh1 is nx2, wh2 is mx2
286
+ wh1 = wh1[:, None] # [N,1,2]
287
+ wh2 = wh2[None] # [1,M,2]
288
+ inter = torch.min(wh1, wh2).prod(2) # [N,M]
289
+ return inter / (wh1.prod(2) + wh2.prod(2) - inter) # iou = inter / (area1 + area2 - inter)
290
+
291
+
292
+ # Plots ----------------------------------------------------------------------------------------------------------------
293
+
294
+ def plot_pr_curve(px, py, ap, save_dir='pr_curve.png', names=()):
295
+ # Precision-recall curve
296
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
297
+ py = np.stack(py, axis=1)
298
+
299
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
300
+ for i, y in enumerate(py.T):
301
+ ax.plot(px, y, linewidth=1, label=f'{names[i]} {ap[i, 0]:.3f}') # plot(recall, precision)
302
+ else:
303
+ ax.plot(px, py, linewidth=1, color='grey') # plot(recall, precision)
304
+
305
+ ax.plot(px, py.mean(1), linewidth=3, color='blue', label='all classes %.3f mAP@0.5' % ap[:, 0].mean())
306
+ ax.set_xlabel('Recall')
307
+ ax.set_ylabel('Precision')
308
+ ax.set_xlim(0, 1)
309
+ ax.set_ylim(0, 1)
310
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
311
+ fig.savefig(Path(save_dir), dpi=250)
312
+ plt.close()
313
+
314
+
315
+ def plot_mc_curve(px, py, save_dir='mc_curve.png', names=(), xlabel='Confidence', ylabel='Metric'):
316
+ # Metric-confidence curve
317
+ fig, ax = plt.subplots(1, 1, figsize=(9, 6), tight_layout=True)
318
+
319
+ if 0 < len(names) < 21: # display per-class legend if < 21 classes
320
+ for i, y in enumerate(py):
321
+ ax.plot(px, y, linewidth=1, label=f'{names[i]}') # plot(confidence, metric)
322
+ else:
323
+ ax.plot(px, py.T, linewidth=1, color='grey') # plot(confidence, metric)
324
+
325
+ y = py.mean(0)
326
+ ax.plot(px, y, linewidth=3, color='blue', label=f'all classes {y.max():.2f} at {px[y.argmax()]:.3f}')
327
+ ax.set_xlabel(xlabel)
328
+ ax.set_ylabel(ylabel)
329
+ ax.set_xlim(0, 1)
330
+ ax.set_ylim(0, 1)
331
+ plt.legend(bbox_to_anchor=(1.04, 1), loc="upper left")
332
+ fig.savefig(Path(save_dir), dpi=250)
333
+ plt.close()
utils/plots.py ADDED
@@ -0,0 +1,437 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ Plotting utils
4
+ """
5
+
6
+ import math
7
+ from copy import copy
8
+ from pathlib import Path
9
+
10
+ import cv2
11
+ import matplotlib
12
+ import matplotlib.pyplot as plt
13
+ import numpy as np
14
+ import pandas as pd
15
+ import seaborn as sn
16
+ import torch
17
+ from PIL import Image, ImageDraw, ImageFont
18
+
19
+ from utils.general import is_ascii, xyxy2xywh, xywh2xyxy
20
+ from utils.metrics import fitness
21
+
22
+ # Settings
23
+ matplotlib.rc('font', **{'size': 11})
24
+ matplotlib.use('Agg') # for writing to files only
25
+
26
+ FILE = Path(__file__).absolute()
27
+ ROOT = FILE.parents[1] # yolov5/ dir
28
+
29
+
30
+ class Colors:
31
+ # Ultralytics color palette https://ultralytics.com/
32
+ def __init__(self):
33
+ # hex = matplotlib.colors.TABLEAU_COLORS.values()
34
+ hex = ('FF3838', 'FF9D97', 'FF701F', 'FFB21D', 'CFD231', '48F90A', '92CC17', '3DDB86', '1A9334', '00D4BB',
35
+ '2C99A8', '00C2FF', '344593', '6473FF', '0018EC', '8438FF', '520085', 'CB38FF', 'FF95C8', 'FF37C7')
36
+ self.palette = [self.hex2rgb('#' + c) for c in hex]
37
+ self.n = len(self.palette)
38
+
39
+ def __call__(self, i, bgr=False):
40
+ c = self.palette[int(i) % self.n]
41
+ return (c[2], c[1], c[0]) if bgr else c
42
+
43
+ @staticmethod
44
+ def hex2rgb(h): # rgb order (PIL)
45
+ return tuple(int(h[1 + i:1 + i + 2], 16) for i in (0, 2, 4))
46
+
47
+
48
+ colors = Colors() # create instance for 'from utils.plots import colors'
49
+
50
+
51
+ def check_font(font='Arial.ttf', size=10):
52
+ # Return a PIL TrueType Font, downloading to ROOT dir if necessary
53
+ font = Path(font)
54
+ font = font if font.exists() else (ROOT / font.name)
55
+ try:
56
+ return ImageFont.truetype(str(font) if font.exists() else font.name, size)
57
+ except Exception as e: # download if missing
58
+ url = "https://ultralytics.com/assets/" + font.name
59
+ print(f'Downloading {url} to {font}...')
60
+ torch.hub.download_url_to_file(url, str(font))
61
+ return ImageFont.truetype(str(font), size)
62
+
63
+
64
+ class Annotator:
65
+ check_font() # download TTF if necessary
66
+
67
+ # YOLOv5 Annotator for train/val mosaics and jpgs and detect/hub inference annotations
68
+ def __init__(self, im, line_width=None, font_size=None, font='Arial.ttf', pil=True):
69
+ assert im.data.contiguous, 'Image not contiguous. Apply np.ascontiguousarray(im) to Annotator() input images.'
70
+ self.pil = pil
71
+ if self.pil: # use PIL
72
+ self.im = im if isinstance(im, Image.Image) else Image.fromarray(im)
73
+ self.draw = ImageDraw.Draw(self.im)
74
+ self.font = check_font(font, size=font_size or max(round(sum(self.im.size) / 2 * 0.035), 12))
75
+ self.fh = self.font.getsize('a')[1] - 3 # font height
76
+ else: # use cv2
77
+ self.im = im
78
+ self.lw = line_width or max(round(sum(im.shape) / 2 * 0.003), 2) # line width
79
+
80
+ def box_label(self, box, label='', color=(128, 128, 128), txt_color=(255, 255, 255)):
81
+ # Add one xyxy box to image with label
82
+ if self.pil or not is_ascii(label):
83
+ self.draw.rectangle(box, width=self.lw, outline=color) # box
84
+ if label:
85
+ w = self.font.getsize(label)[0] # text width
86
+ self.draw.rectangle([box[0], box[1] - self.fh, box[0] + w + 1, box[1] + 1], fill=color)
87
+ self.draw.text((box[0], box[1]), label, fill=txt_color, font=self.font, anchor='ls')
88
+ else: # cv2
89
+ c1, c2 = (int(box[0]), int(box[1])), (int(box[2]), int(box[3]))
90
+ cv2.rectangle(self.im, c1, c2, color, thickness=self.lw, lineType=cv2.LINE_AA)
91
+ if label:
92
+ tf = max(self.lw - 1, 1) # font thickness
93
+ w, h = cv2.getTextSize(label, 0, fontScale=self.lw / 3, thickness=tf)[0]
94
+ c2 = c1[0] + w, c1[1] - h - 3
95
+ cv2.rectangle(self.im, c1, c2, color, -1, cv2.LINE_AA) # filled
96
+ cv2.putText(self.im, label, (c1[0], c1[1] - 2), 0, self.lw / 3, txt_color, thickness=tf,
97
+ lineType=cv2.LINE_AA)
98
+
99
+ def rectangle(self, xy, fill=None, outline=None, width=1):
100
+ # Add rectangle to image (PIL-only)
101
+ self.draw.rectangle(xy, fill, outline, width)
102
+
103
+ def text(self, xy, text, txt_color=(255, 255, 255)):
104
+ # Add text to image (PIL-only)
105
+ w, h = self.font.getsize(text) # text width, height
106
+ self.draw.text((xy[0], xy[1] - h + 1), text, fill=txt_color, font=self.font)
107
+
108
+ def result(self):
109
+ # Return annotated image as array
110
+ return np.asarray(self.im)
111
+
112
+
113
+ def hist2d(x, y, n=100):
114
+ # 2d histogram used in labels.png and evolve.png
115
+ xedges, yedges = np.linspace(x.min(), x.max(), n), np.linspace(y.min(), y.max(), n)
116
+ hist, xedges, yedges = np.histogram2d(x, y, (xedges, yedges))
117
+ xidx = np.clip(np.digitize(x, xedges) - 1, 0, hist.shape[0] - 1)
118
+ yidx = np.clip(np.digitize(y, yedges) - 1, 0, hist.shape[1] - 1)
119
+ return np.log(hist[xidx, yidx])
120
+
121
+
122
+ def butter_lowpass_filtfilt(data, cutoff=1500, fs=50000, order=5):
123
+ from scipy.signal import butter, filtfilt
124
+
125
+ # https://stackoverflow.com/questions/28536191/how-to-filter-smooth-with-scipy-numpy
126
+ def butter_lowpass(cutoff, fs, order):
127
+ nyq = 0.5 * fs
128
+ normal_cutoff = cutoff / nyq
129
+ return butter(order, normal_cutoff, btype='low', analog=False)
130
+
131
+ b, a = butter_lowpass(cutoff, fs, order=order)
132
+ return filtfilt(b, a, data) # forward-backward filter
133
+
134
+
135
+ def output_to_target(output):
136
+ # Convert model output to target format [batch_id, class_id, x, y, w, h, conf]
137
+ targets = []
138
+ for i, o in enumerate(output):
139
+ for *box, conf, cls in o.cpu().numpy():
140
+ targets.append([i, cls, *list(*xyxy2xywh(np.array(box)[None])), conf])
141
+ return np.array(targets)
142
+
143
+
144
+ def plot_images(images, targets, paths=None, fname='images.jpg', names=None, max_size=1920, max_subplots=16):
145
+ # Plot image grid with labels
146
+ if isinstance(images, torch.Tensor):
147
+ images = images.cpu().float().numpy()
148
+ if isinstance(targets, torch.Tensor):
149
+ targets = targets.cpu().numpy()
150
+ if np.max(images[0]) <= 1:
151
+ images *= 255.0 # de-normalise (optional)
152
+ bs, _, h, w = images.shape # batch size, _, height, width
153
+ bs = min(bs, max_subplots) # limit plot images
154
+ ns = np.ceil(bs ** 0.5) # number of subplots (square)
155
+
156
+ # Build Image
157
+ mosaic = np.full((int(ns * h), int(ns * w), 3), 255, dtype=np.uint8) # init
158
+ for i, im in enumerate(images):
159
+ if i == max_subplots: # if last batch has fewer images than we expect
160
+ break
161
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
162
+ im = im.transpose(1, 2, 0)
163
+ mosaic[y:y + h, x:x + w, :] = im
164
+
165
+ # Resize (optional)
166
+ scale = max_size / ns / max(h, w)
167
+ if scale < 1:
168
+ h = math.ceil(scale * h)
169
+ w = math.ceil(scale * w)
170
+ mosaic = cv2.resize(mosaic, tuple(int(x * ns) for x in (w, h)))
171
+
172
+ # Annotate
173
+ fs = int((h + w) * ns * 0.01) # font size
174
+ annotator = Annotator(mosaic, line_width=round(fs / 10), font_size=fs)
175
+ for i in range(i + 1):
176
+ x, y = int(w * (i // ns)), int(h * (i % ns)) # block origin
177
+ annotator.rectangle([x, y, x + w, y + h], None, (255, 255, 255), width=2) # borders
178
+ if paths:
179
+ annotator.text((x + 5, y + 5 + h), text=Path(paths[i]).name[:40], txt_color=(220, 220, 220)) # filenames
180
+ if len(targets) > 0:
181
+ ti = targets[targets[:, 0] == i] # image targets
182
+ boxes = xywh2xyxy(ti[:, 2:6]).T
183
+ classes = ti[:, 1].astype('int')
184
+ labels = ti.shape[1] == 6 or ti.shape[1] > 7 # labels if no conf column or pose objects
185
+ conf = None if labels else ti[:, 6] # check for confidence presence (label vs pred)
186
+
187
+ if boxes.shape[1]:
188
+ if boxes.max() <= 1.01: # if normalized with tolerance 0.01
189
+ boxes[[0, 2]] *= w # scale to pixels
190
+ boxes[[1, 3]] *= h
191
+ elif scale < 1: # absolute coords need scale if image scales
192
+ boxes *= scale
193
+ boxes[[0, 2]] += x
194
+ boxes[[1, 3]] += y
195
+ for j, box in enumerate(boxes.T.tolist()):
196
+ cls = classes[j]
197
+ color = colors(cls)
198
+ cls = names[cls] if names else cls
199
+ if labels or conf[j] > 0.25: # 0.25 conf thresh
200
+ label = f'{cls}' if labels else f'{cls} {conf[j]:.1f}'
201
+ annotator.box_label(box, label, color=color)
202
+ annotator.im.save(fname) # save
203
+
204
+
205
+ def plot_lr_scheduler(optimizer, scheduler, epochs=300, save_dir=''):
206
+ # Plot LR simulating training for full epochs
207
+ optimizer, scheduler = copy(optimizer), copy(scheduler) # do not modify originals
208
+ y = []
209
+ for _ in range(epochs):
210
+ scheduler.step()
211
+ y.append(optimizer.param_groups[0]['lr'])
212
+ plt.plot(y, '.-', label='LR')
213
+ plt.xlabel('epoch')
214
+ plt.ylabel('LR')
215
+ plt.grid()
216
+ plt.xlim(0, epochs)
217
+ plt.ylim(0)
218
+ plt.savefig(Path(save_dir) / 'LR.png', dpi=200)
219
+ plt.close()
220
+
221
+
222
+ def plot_val_txt(): # from utils.plots import *; plot_val()
223
+ # Plot val.txt histograms
224
+ x = np.loadtxt('val.txt', dtype=np.float32)
225
+ box = xyxy2xywh(x[:, :4])
226
+ cx, cy = box[:, 0], box[:, 1]
227
+
228
+ fig, ax = plt.subplots(1, 1, figsize=(6, 6), tight_layout=True)
229
+ ax.hist2d(cx, cy, bins=600, cmax=10, cmin=0)
230
+ ax.set_aspect('equal')
231
+ plt.savefig('hist2d.png', dpi=300)
232
+
233
+ fig, ax = plt.subplots(1, 2, figsize=(12, 6), tight_layout=True)
234
+ ax[0].hist(cx, bins=600)
235
+ ax[1].hist(cy, bins=600)
236
+ plt.savefig('hist1d.png', dpi=200)
237
+
238
+
239
+ def plot_targets_txt(): # from utils.plots import *; plot_targets_txt()
240
+ # Plot targets.txt histograms
241
+ x = np.loadtxt('targets.txt', dtype=np.float32).T
242
+ s = ['x targets', 'y targets', 'width targets', 'height targets']
243
+ fig, ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)
244
+ ax = ax.ravel()
245
+ for i in range(4):
246
+ ax[i].hist(x[i], bins=100, label='%.3g +/- %.3g' % (x[i].mean(), x[i].std()))
247
+ ax[i].legend()
248
+ ax[i].set_title(s[i])
249
+ plt.savefig('targets.jpg', dpi=200)
250
+
251
+
252
+ def plot_study_txt(path='', x=None): # from utils.plots import *; plot_study_txt()
253
+ # Plot study.txt generated by val.py
254
+ plot2 = False # plot additional results
255
+ if plot2:
256
+ ax = plt.subplots(2, 4, figsize=(10, 6), tight_layout=True)[1].ravel()
257
+
258
+ fig2, ax2 = plt.subplots(1, 1, figsize=(8, 4), tight_layout=True)
259
+ # for f in [Path(path) / f'study_coco_{x}.txt' for x in ['yolov5s6', 'yolov5m6', 'yolov5l6', 'yolov5x6']]:
260
+ for f in sorted(Path(path).glob('study*.txt')):
261
+ y = np.loadtxt(f, dtype=np.float32, usecols=[0, 1, 2, 3, 7, 8, 9], ndmin=2).T
262
+ x = np.arange(y.shape[1]) if x is None else np.array(x)
263
+ if plot2:
264
+ s = ['P', 'R', 'mAP@.5', 'mAP@.5:.95', 't_preprocess (ms/img)', 't_inference (ms/img)', 't_NMS (ms/img)']
265
+ for i in range(7):
266
+ ax[i].plot(x, y[i], '.-', linewidth=2, markersize=8)
267
+ ax[i].set_title(s[i])
268
+
269
+ j = y[3].argmax() + 1
270
+ ax2.plot(y[5, 1:j], y[3, 1:j] * 1E2, '.-', linewidth=2, markersize=8,
271
+ label=f.stem.replace('study_coco_', '').replace('yolo', 'YOLO'))
272
+
273
+ ax2.plot(1E3 / np.array([209, 140, 97, 58, 35, 18]), [34.6, 40.5, 43.0, 47.5, 49.7, 51.5],
274
+ 'k.-', linewidth=2, markersize=8, alpha=.25, label='EfficientDet')
275
+
276
+ ax2.grid(alpha=0.2)
277
+ ax2.set_yticks(np.arange(20, 60, 5))
278
+ ax2.set_xlim(0, 57)
279
+ ax2.set_ylim(30, 55)
280
+ ax2.set_xlabel('GPU Speed (ms/img)')
281
+ ax2.set_ylabel('COCO AP val')
282
+ ax2.legend(loc='lower right')
283
+ plt.savefig(str(Path(path).name) + '.png', dpi=300)
284
+
285
+
286
+ def plot_labels(labels, names=(), save_dir=Path('')):
287
+ # plot dataset labels
288
+ print('Plotting labels... ')
289
+ c, b = labels[:, 0], labels[:, 1:].transpose() # classes, boxes
290
+ nc = int(c.max() + 1) # number of classes
291
+ x = pd.DataFrame(b.transpose(), columns=['x', 'y', 'width', 'height'])
292
+
293
+ # seaborn correlogram
294
+ sn.pairplot(x, corner=True, diag_kind='auto', kind='hist', diag_kws=dict(bins=50), plot_kws=dict(pmax=0.9))
295
+ plt.savefig(save_dir / 'labels_correlogram.jpg', dpi=200)
296
+ plt.close()
297
+
298
+ # matplotlib labels
299
+ matplotlib.use('svg') # faster
300
+ ax = plt.subplots(2, 2, figsize=(8, 8), tight_layout=True)[1].ravel()
301
+ y = ax[0].hist(c, bins=np.linspace(0, nc, nc + 1) - 0.5, rwidth=0.8)
302
+ # [y[2].patches[i].set_color([x / 255 for x in colors(i)]) for i in range(nc)] # update colors bug #3195
303
+ ax[0].set_ylabel('instances')
304
+ if 0 < len(names) < 30:
305
+ ax[0].set_xticks(range(len(names)))
306
+ ax[0].set_xticklabels(names, rotation=90, fontsize=10)
307
+ else:
308
+ ax[0].set_xlabel('classes')
309
+ sn.histplot(x, x='x', y='y', ax=ax[2], bins=50, pmax=0.9)
310
+ sn.histplot(x, x='width', y='height', ax=ax[3], bins=50, pmax=0.9)
311
+
312
+ # rectangles
313
+ labels[:, 1:3] = 0.5 # center
314
+ labels[:, 1:] = xywh2xyxy(labels[:, 1:]) * 2000
315
+ img = Image.fromarray(np.ones((2000, 2000, 3), dtype=np.uint8) * 255)
316
+ for cls, *box in labels[:1000]:
317
+ ImageDraw.Draw(img).rectangle(box, width=1, outline=colors(cls)) # plot
318
+ ax[1].imshow(img)
319
+ ax[1].axis('off')
320
+
321
+ for a in [0, 1, 2, 3]:
322
+ for s in ['top', 'right', 'left', 'bottom']:
323
+ ax[a].spines[s].set_visible(False)
324
+
325
+ plt.savefig(save_dir / 'labels.jpg', dpi=200)
326
+ matplotlib.use('Agg')
327
+ plt.close()
328
+
329
+
330
+ def profile_idetection(start=0, stop=0, labels=(), save_dir=''):
331
+ # Plot iDetection '*.txt' per-image logs. from utils.plots import *; profile_idetection()
332
+ ax = plt.subplots(2, 4, figsize=(12, 6), tight_layout=True)[1].ravel()
333
+ s = ['Images', 'Free Storage (GB)', 'RAM Usage (GB)', 'Battery', 'dt_raw (ms)', 'dt_smooth (ms)', 'real-world FPS']
334
+ files = list(Path(save_dir).glob('frames*.txt'))
335
+ for fi, f in enumerate(files):
336
+ try:
337
+ results = np.loadtxt(f, ndmin=2).T[:, 90:-30] # clip first and last rows
338
+ n = results.shape[1] # number of rows
339
+ x = np.arange(start, min(stop, n) if stop else n)
340
+ results = results[:, x]
341
+ t = (results[0] - results[0].min()) # set t0=0s
342
+ results[0] = x
343
+ for i, a in enumerate(ax):
344
+ if i < len(results):
345
+ label = labels[fi] if len(labels) else f.stem.replace('frames_', '')
346
+ a.plot(t, results[i], marker='.', label=label, linewidth=1, markersize=5)
347
+ a.set_title(s[i])
348
+ a.set_xlabel('time (s)')
349
+ # if fi == len(files) - 1:
350
+ # a.set_ylim(bottom=0)
351
+ for side in ['top', 'right']:
352
+ a.spines[side].set_visible(False)
353
+ else:
354
+ a.remove()
355
+ except Exception as e:
356
+ print('Warning: Plotting error for %s; %s' % (f, e))
357
+ ax[1].legend()
358
+ plt.savefig(Path(save_dir) / 'idetection_profile.png', dpi=200)
359
+
360
+
361
+ def plot_evolve(evolve_csv='path/to/evolve.csv'): # from utils.plots import *; plot_evolve()
362
+ # Plot evolve.csv hyp evolution results
363
+ evolve_csv = Path(evolve_csv)
364
+ data = pd.read_csv(evolve_csv)
365
+ keys = [x.strip() for x in data.columns]
366
+ x = data.values
367
+ f = fitness(x)
368
+ j = np.argmax(f) # max fitness index
369
+ plt.figure(figsize=(10, 12), tight_layout=True)
370
+ matplotlib.rc('font', **{'size': 8})
371
+ for i, k in enumerate(keys[7:]):
372
+ v = x[:, 7 + i]
373
+ mu = v[j] # best single result
374
+ plt.subplot(6, 5, i + 1)
375
+ plt.scatter(v, f, c=hist2d(v, f, 20), cmap='viridis', alpha=.8, edgecolors='none')
376
+ plt.plot(mu, f.max(), 'k+', markersize=15)
377
+ plt.title('%s = %.3g' % (k, mu), fontdict={'size': 9}) # limit to 40 characters
378
+ if i % 5 != 0:
379
+ plt.yticks([])
380
+ print('%15s: %.3g' % (k, mu))
381
+ f = evolve_csv.with_suffix('.png') # filename
382
+ plt.savefig(f, dpi=200)
383
+ plt.close()
384
+ print(f'Saved {f}')
385
+
386
+
387
+ def plot_results(file='path/to/results.csv', dir=''):
388
+ # Plot training results.csv. Usage: from utils.plots import *; plot_results('path/to/results.csv')
389
+ save_dir = Path(file).parent if file else Path(dir)
390
+ fig, ax = plt.subplots(2, 5, figsize=(12, 6), tight_layout=True)
391
+ ax = ax.ravel()
392
+ files = list(save_dir.glob('results*.csv'))
393
+ assert len(files), f'No results.csv files found in {save_dir.resolve()}, nothing to plot.'
394
+ for fi, f in enumerate(files):
395
+ try:
396
+ data = pd.read_csv(f)
397
+ s = [x.strip() for x in data.columns]
398
+ x = data.values[:, 0]
399
+ for i, j in enumerate([1, 2, 3, 4, 5, 8, 9, 10, 6, 7]):
400
+ y = data.values[:, j]
401
+ # y[y == 0] = np.nan # don't show zero values
402
+ ax[i].plot(x, y, marker='.', label=f.stem, linewidth=2, markersize=8)
403
+ ax[i].set_title(s[j], fontsize=12)
404
+ # if j in [8, 9, 10]: # share train and val loss y axes
405
+ # ax[i].get_shared_y_axes().join(ax[i], ax[i - 5])
406
+ except Exception as e:
407
+ print(f'Warning: Plotting error for {f}: {e}')
408
+ ax[1].legend()
409
+ fig.savefig(save_dir / 'results.png', dpi=200)
410
+ plt.close()
411
+
412
+
413
+ def feature_visualization(x, module_type, stage, n=32, save_dir=Path('runs/detect/exp')):
414
+ """
415
+ x: Features to be visualized
416
+ module_type: Module type
417
+ stage: Module stage within model
418
+ n: Maximum number of feature maps to plot
419
+ save_dir: Directory to save results
420
+ """
421
+ if 'Detect' not in module_type:
422
+ batch, channels, height, width = x.shape # batch, channels, height, width
423
+ if height > 1 and width > 1:
424
+ f = f"stage{stage}_{module_type.split('.')[-1]}_features.png" # filename
425
+
426
+ blocks = torch.chunk(x[0].cpu(), channels, dim=0) # select batch index 0, block by channels
427
+ n = min(n, channels) # number of plots
428
+ fig, ax = plt.subplots(math.ceil(n / 8), 8, tight_layout=True) # 8 rows x n/8 cols
429
+ ax = ax.ravel()
430
+ plt.subplots_adjust(wspace=0.05, hspace=0.05)
431
+ for i in range(n):
432
+ ax[i].imshow(blocks[i].squeeze()) # cmap='gray'
433
+ ax[i].axis('off')
434
+
435
+ print(f'Saving {save_dir / f}... ({n}/{channels})')
436
+ plt.savefig(save_dir / f, dpi=300, bbox_inches='tight')
437
+ plt.close()
utils/torch_utils.py ADDED
@@ -0,0 +1,350 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
2
+ """
3
+ PyTorch utils
4
+ """
5
+
6
+ import datetime
7
+ import logging
8
+ import math
9
+ import os
10
+ import platform
11
+ import subprocess
12
+ import time
13
+ from contextlib import contextmanager
14
+ from copy import deepcopy
15
+ from pathlib import Path
16
+
17
+ import torch
18
+ import torch.backends.cudnn as cudnn
19
+ import torch.distributed as dist
20
+ import torch.nn as nn
21
+ import torch.nn.functional as F
22
+ import torchvision
23
+
24
+ try:
25
+ import thop # for FLOPs computation
26
+ except ImportError:
27
+ thop = None
28
+
29
+ LOGGER = logging.getLogger(__name__)
30
+
31
+
32
+ @contextmanager
33
+ def torch_distributed_zero_first(local_rank: int):
34
+ """
35
+ Decorator to make all processes in distributed training wait for each local_master to do something.
36
+ """
37
+ if local_rank not in [-1, 0]:
38
+ dist.barrier(device_ids=[local_rank])
39
+ yield
40
+ if local_rank == 0:
41
+ dist.barrier(device_ids=[0])
42
+
43
+
44
+ def init_torch_seeds(seed=0):
45
+ # Speed-reproducibility tradeoff https://pytorch.org/docs/stable/notes/randomness.html
46
+ torch.manual_seed(seed)
47
+ if seed == 0: # slower, more reproducible
48
+ cudnn.benchmark, cudnn.deterministic = False, True
49
+ else: # faster, less reproducible
50
+ cudnn.benchmark, cudnn.deterministic = True, False
51
+
52
+
53
+ def date_modified(path=__file__):
54
+ # return human-readable file modification date, i.e. '2021-3-26'
55
+ t = datetime.datetime.fromtimestamp(Path(path).stat().st_mtime)
56
+ return f'{t.year}-{t.month}-{t.day}'
57
+
58
+
59
+ def git_describe(path=Path(__file__).parent): # path must be a directory
60
+ # return human-readable git description, i.e. v5.0-5-g3e25f1e https://git-scm.com/docs/git-describe
61
+ s = f'git -C {path} describe --tags --long --always'
62
+ try:
63
+ return subprocess.check_output(s, shell=True, stderr=subprocess.STDOUT).decode()[:-1]
64
+ except subprocess.CalledProcessError as e:
65
+ return '' # not a git repository
66
+
67
+
68
+ def select_device(device='', batch_size=None):
69
+ # device = 'cpu' or '0' or '0,1,2,3'
70
+ s = f'YOLOv5 🚀 {git_describe() or date_modified()} torch {torch.__version__} ' # string
71
+ device = str(device).strip().lower().replace('cuda:', '') # to string, 'cuda:0' to '0'
72
+ cpu = device == 'cpu'
73
+ if cpu:
74
+ os.environ['CUDA_VISIBLE_DEVICES'] = '-1' # force torch.cuda.is_available() = False
75
+ elif device: # non-cpu device requested
76
+ os.environ['CUDA_VISIBLE_DEVICES'] = device # set environment variable
77
+ assert torch.cuda.is_available(), f'CUDA unavailable, invalid device {device} requested' # check availability
78
+
79
+ cuda = not cpu and torch.cuda.is_available()
80
+ if cuda:
81
+ devices = device.split(',') if device else '0' # range(torch.cuda.device_count()) # i.e. 0,1,6,7
82
+ n = len(devices) # device count
83
+ if n > 1 and batch_size: # check batch_size is divisible by device_count
84
+ assert batch_size % n == 0, f'batch-size {batch_size} not multiple of GPU count {n}'
85
+ space = ' ' * (len(s) + 1)
86
+ for i, d in enumerate(devices):
87
+ p = torch.cuda.get_device_properties(i)
88
+ s += f"{'' if i == 0 else space}CUDA:{d} ({p.name}, {p.total_memory / 1024 ** 2}MB)\n" # bytes to MB
89
+ else:
90
+ s += 'CPU\n'
91
+
92
+ LOGGER.info(s.encode().decode('ascii', 'ignore') if platform.system() == 'Windows' else s) # emoji-safe
93
+ return torch.device('cuda:0' if cuda else 'cpu')
94
+
95
+
96
+ def time_sync():
97
+ # pytorch-accurate time
98
+ if torch.cuda.is_available():
99
+ torch.cuda.synchronize()
100
+ return time.time()
101
+
102
+
103
+ def profile(input, ops, n=10, device=None):
104
+ # YOLOv5 speed/memory/FLOPs profiler
105
+ #
106
+ # Usage:
107
+ # input = torch.randn(16, 3, 640, 640)
108
+ # m1 = lambda x: x * torch.sigmoid(x)
109
+ # m2 = nn.SiLU()
110
+ # profile(input, [m1, m2], n=100) # profile over 100 iterations
111
+
112
+ results = []
113
+ logging.basicConfig(format="%(message)s", level=logging.INFO)
114
+ device = device or select_device()
115
+ print(f"{'Params':>12s}{'GFLOPs':>12s}{'GPU_mem (GB)':>14s}{'forward (ms)':>14s}{'backward (ms)':>14s}"
116
+ f"{'input':>24s}{'output':>24s}")
117
+
118
+ for x in input if isinstance(input, list) else [input]:
119
+ x = x.to(device)
120
+ x.requires_grad = True
121
+ for m in ops if isinstance(ops, list) else [ops]:
122
+ m = m.to(device) if hasattr(m, 'to') else m # device
123
+ m = m.half() if hasattr(m, 'half') and isinstance(x, torch.Tensor) and x.dtype is torch.float16 else m
124
+ tf, tb, t = 0., 0., [0., 0., 0.] # dt forward, backward
125
+ try:
126
+ flops = thop.profile(m, inputs=(x,), verbose=False)[0] / 1E9 * 2 # GFLOPs
127
+ except:
128
+ flops = 0
129
+
130
+ try:
131
+ for _ in range(n):
132
+ t[0] = time_sync()
133
+ y = m(x)
134
+ t[1] = time_sync()
135
+ try:
136
+ _ = (sum([yi.sum() for yi in y]) if isinstance(y, list) else y).sum().backward()
137
+ t[2] = time_sync()
138
+ except Exception as e: # no backward method
139
+ print(e)
140
+ t[2] = float('nan')
141
+ tf += (t[1] - t[0]) * 1000 / n # ms per op forward
142
+ tb += (t[2] - t[1]) * 1000 / n # ms per op backward
143
+ mem = torch.cuda.memory_reserved() / 1E9 if torch.cuda.is_available() else 0 # (GB)
144
+ s_in = tuple(x.shape) if isinstance(x, torch.Tensor) else 'list'
145
+ s_out = tuple(y.shape) if isinstance(y, torch.Tensor) else 'list'
146
+ p = sum(list(x.numel() for x in m.parameters())) if isinstance(m, nn.Module) else 0 # parameters
147
+ print(f'{p:12}{flops:12.4g}{mem:>14.3f}{tf:14.4g}{tb:14.4g}{str(s_in):>24s}{str(s_out):>24s}')
148
+ results.append([p, flops, mem, tf, tb, s_in, s_out])
149
+ except Exception as e:
150
+ print(e)
151
+ results.append(None)
152
+ torch.cuda.empty_cache()
153
+ return results
154
+
155
+
156
+ def is_parallel(model):
157
+ # Returns True if model is of type DP or DDP
158
+ return type(model) in (nn.parallel.DataParallel, nn.parallel.DistributedDataParallel)
159
+
160
+
161
+ def de_parallel(model):
162
+ # De-parallelize a model: returns single-GPU model if model is of type DP or DDP
163
+ return model.module if is_parallel(model) else model
164
+
165
+
166
+ def intersect_dicts(da, db, exclude=()):
167
+ # Dictionary intersection of matching keys and shapes, omitting 'exclude' keys, using da values
168
+ return {k: v for k, v in da.items() if k in db and not any(x in k for x in exclude) and v.shape == db[k].shape}
169
+
170
+
171
+ def initialize_weights(model):
172
+ for m in model.modules():
173
+ t = type(m)
174
+ if t is nn.Conv2d:
175
+ pass # nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
176
+ elif t is nn.BatchNorm2d:
177
+ m.eps = 1e-3
178
+ m.momentum = 0.03
179
+ elif t in [nn.Hardswish, nn.LeakyReLU, nn.ReLU, nn.ReLU6]:
180
+ m.inplace = True
181
+
182
+
183
+ def find_modules(model, mclass=nn.Conv2d):
184
+ # Finds layer indices matching module class 'mclass'
185
+ return [i for i, m in enumerate(model.module_list) if isinstance(m, mclass)]
186
+
187
+
188
+ def sparsity(model):
189
+ # Return global model sparsity
190
+ a, b = 0., 0.
191
+ for p in model.parameters():
192
+ a += p.numel()
193
+ b += (p == 0).sum()
194
+ return b / a
195
+
196
+
197
+ def prune(model, amount=0.3):
198
+ # Prune model to requested global sparsity
199
+ import torch.nn.utils.prune as prune
200
+ print('Pruning model... ', end='')
201
+ for name, m in model.named_modules():
202
+ if isinstance(m, nn.Conv2d):
203
+ prune.l1_unstructured(m, name='weight', amount=amount) # prune
204
+ prune.remove(m, 'weight') # make permanent
205
+ print(' %.3g global sparsity' % sparsity(model))
206
+
207
+
208
+ def fuse_conv_and_bn(conv, bn):
209
+ # Fuse convolution and batchnorm layers https://tehnokv.com/posts/fusing-batchnorm-and-conv/
210
+ fusedconv = nn.Conv2d(conv.in_channels,
211
+ conv.out_channels,
212
+ kernel_size=conv.kernel_size,
213
+ stride=conv.stride,
214
+ padding=conv.padding,
215
+ groups=conv.groups,
216
+ bias=True).requires_grad_(False).to(conv.weight.device)
217
+
218
+ # prepare filters
219
+ w_conv = conv.weight.clone().view(conv.out_channels, -1)
220
+ w_bn = torch.diag(bn.weight.div(torch.sqrt(bn.eps + bn.running_var)))
221
+ fusedconv.weight.copy_(torch.mm(w_bn, w_conv).view(fusedconv.weight.shape))
222
+
223
+ # prepare spatial bias
224
+ b_conv = torch.zeros(conv.weight.size(0), device=conv.weight.device) if conv.bias is None else conv.bias
225
+ b_bn = bn.bias - bn.weight.mul(bn.running_mean).div(torch.sqrt(bn.running_var + bn.eps))
226
+ fusedconv.bias.copy_(torch.mm(w_bn, b_conv.reshape(-1, 1)).reshape(-1) + b_bn)
227
+
228
+ return fusedconv
229
+
230
+
231
+ def model_info(model, verbose=False, img_size=640):
232
+ # Model information. img_size may be int or list, i.e. img_size=640 or img_size=[640, 320]
233
+ n_p = sum(x.numel() for x in model.parameters()) # number parameters
234
+ n_g = sum(x.numel() for x in model.parameters() if x.requires_grad) # number gradients
235
+ if verbose:
236
+ print('%5s %40s %9s %12s %20s %10s %10s' % ('layer', 'name', 'gradient', 'parameters', 'shape', 'mu', 'sigma'))
237
+ for i, (name, p) in enumerate(model.named_parameters()):
238
+ name = name.replace('module_list.', '')
239
+ print('%5g %40s %9s %12g %20s %10.3g %10.3g' %
240
+ (i, name, p.requires_grad, p.numel(), list(p.shape), p.mean(), p.std()))
241
+
242
+ try: # FLOPs
243
+ from thop import profile
244
+ stride = max(int(model.stride.max()), 32) if hasattr(model, 'stride') else 32
245
+ img = torch.zeros((1, model.yaml.get('ch', 3), stride, stride), device=next(model.parameters()).device) # input
246
+ flops = profile(deepcopy(model), inputs=(img,), verbose=False)[0] / 1E9 * 2 # stride GFLOPs
247
+ img_size = img_size if isinstance(img_size, list) else [img_size, img_size] # expand if int/float
248
+ fs = ', %.1f GFLOPs' % (flops * img_size[0] / stride * img_size[1] / stride) # 640x640 GFLOPs
249
+ except (ImportError, Exception):
250
+ fs = ''
251
+
252
+ LOGGER.info(f"Model Summary: {len(list(model.modules()))} layers, {n_p} parameters, {n_g} gradients{fs}")
253
+
254
+
255
+ def load_classifier(name='resnet101', n=2):
256
+ # Loads a pretrained model reshaped to n-class output
257
+ model = torchvision.models.__dict__[name](pretrained=True)
258
+
259
+ # ResNet model properties
260
+ # input_size = [3, 224, 224]
261
+ # input_space = 'RGB'
262
+ # input_range = [0, 1]
263
+ # mean = [0.485, 0.456, 0.406]
264
+ # std = [0.229, 0.224, 0.225]
265
+
266
+ # Reshape output to n classes
267
+ filters = model.fc.weight.shape[1]
268
+ model.fc.bias = nn.Parameter(torch.zeros(n), requires_grad=True)
269
+ model.fc.weight = nn.Parameter(torch.zeros(n, filters), requires_grad=True)
270
+ model.fc.out_features = n
271
+ return model
272
+
273
+
274
+ def scale_img(img, ratio=1.0, same_shape=False, gs=32): # img(16,3,256,416)
275
+ # scales img(bs,3,y,x) by ratio constrained to gs-multiple
276
+ if ratio == 1.0:
277
+ return img
278
+ else:
279
+ h, w = img.shape[2:]
280
+ s = (int(h * ratio), int(w * ratio)) # new size
281
+ img = F.interpolate(img, size=s, mode='bilinear', align_corners=False) # resize
282
+ if not same_shape: # pad/crop img
283
+ h, w = [math.ceil(x * ratio / gs) * gs for x in (h, w)]
284
+ return F.pad(img, [0, w - s[1], 0, h - s[0]], value=0.447) # value = imagenet mean
285
+
286
+
287
+ def copy_attr(a, b, include=(), exclude=()):
288
+ # Copy attributes from b to a, options to only include [...] and to exclude [...]
289
+ for k, v in b.__dict__.items():
290
+ if (len(include) and k not in include) or k.startswith('_') or k in exclude:
291
+ continue
292
+ else:
293
+ setattr(a, k, v)
294
+
295
+
296
+ class EarlyStopping:
297
+ # YOLOv5 simple early stopper
298
+ def __init__(self, patience=30):
299
+ self.best_fitness = 0.0 # i.e. mAP
300
+ self.best_epoch = 0
301
+ self.patience = patience or float('inf') # epochs to wait after fitness stops improving to stop
302
+ self.possible_stop = False # possible stop may occur next epoch
303
+
304
+ def __call__(self, epoch, fitness):
305
+ if fitness >= self.best_fitness: # >= 0 to allow for early zero-fitness stage of training
306
+ self.best_epoch = epoch
307
+ self.best_fitness = fitness
308
+ delta = epoch - self.best_epoch # epochs without improvement
309
+ self.possible_stop = delta >= (self.patience - 1) # possible stop may occur next epoch
310
+ stop = delta >= self.patience # stop training if patience exceeded
311
+ if stop:
312
+ LOGGER.info(f'EarlyStopping patience {self.patience} exceeded, stopping training.')
313
+ return stop
314
+
315
+
316
+ class ModelEMA:
317
+ """ Model Exponential Moving Average from https://github.com/rwightman/pytorch-image-models
318
+ Keep a moving average of everything in the model state_dict (parameters and buffers).
319
+ This is intended to allow functionality like
320
+ https://www.tensorflow.org/api_docs/python/tf/train/ExponentialMovingAverage
321
+ A smoothed version of the weights is necessary for some training schemes to perform well.
322
+ This class is sensitive where it is initialized in the sequence of model init,
323
+ GPU assignment and distributed training wrappers.
324
+ """
325
+
326
+ def __init__(self, model, decay=0.9999, updates=0):
327
+ # Create EMA
328
+ self.ema = deepcopy(model.module if is_parallel(model) else model).eval() # FP32 EMA
329
+ # if next(model.parameters()).device.type != 'cpu':
330
+ # self.ema.half() # FP16 EMA
331
+ self.updates = updates # number of EMA updates
332
+ self.decay = lambda x: decay * (1 - math.exp(-x / 2000)) # decay exponential ramp (to help early epochs)
333
+ for p in self.ema.parameters():
334
+ p.requires_grad_(False)
335
+
336
+ def update(self, model):
337
+ # Update EMA parameters
338
+ with torch.no_grad():
339
+ self.updates += 1
340
+ d = self.decay(self.updates)
341
+
342
+ msd = model.module.state_dict() if is_parallel(model) else model.state_dict() # model state_dict
343
+ for k, v in self.ema.state_dict().items():
344
+ if v.dtype.is_floating_point:
345
+ v *= d
346
+ v += (1. - d) * msd[k].detach()
347
+
348
+ def update_attr(self, model, include=(), exclude=('process_group', 'reducer')):
349
+ # Update EMA attributes
350
+ copy_attr(self.ema, model, include, exclude)
val.py ADDED
@@ -0,0 +1,336 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import argparse
2
+ import json
3
+ import os, os.path as osp
4
+ import sys
5
+ from pathlib import Path
6
+
7
+ import numpy as np
8
+ import torch
9
+ from tqdm import tqdm
10
+
11
+ FILE = Path(__file__).absolute()
12
+ sys.path.append(FILE.parents[0].as_posix()) # add kapao/ to path
13
+
14
+ from models.experimental import attempt_load
15
+ from utils.datasets import create_dataloader
16
+ from utils.augmentations import letterbox
17
+ from utils.general import check_dataset, check_file, check_img_size, \
18
+ non_max_suppression_kp, scale_coords, set_logging, colorstr
19
+ from utils.torch_utils import select_device, time_sync
20
+ import tempfile
21
+ import cv2
22
+
23
+ PAD_COLOR = (114 / 255, 114 / 255, 114 / 255)
24
+
25
+
26
+ def run_nms(data, model_out):
27
+ if data['iou_thres'] == data['iou_thres_kp'] and data['conf_thres_kp'] >= data['conf_thres']:
28
+ # Combined NMS saves ~0.2 ms / image
29
+ dets = non_max_suppression_kp(model_out, data['conf_thres'], data['iou_thres'], num_coords=data['num_coords'])
30
+ person_dets = [d[d[:, 5] == 0] for d in dets]
31
+ kp_dets = [d[d[:, 4] >= data['conf_thres_kp']] for d in dets]
32
+ kp_dets = [d[d[:, 5] > 0] for d in kp_dets]
33
+ else:
34
+ person_dets = non_max_suppression_kp(model_out, data['conf_thres'], data['iou_thres'],
35
+ classes=[0],
36
+ num_coords=data['num_coords'])
37
+
38
+ kp_dets = non_max_suppression_kp(model_out, data['conf_thres_kp'], data['iou_thres_kp'],
39
+ classes=list(range(1, 1 + len(data['kp_flip']))),
40
+ num_coords=data['num_coords'])
41
+ return person_dets, kp_dets
42
+
43
+
44
+ def post_process_batch(data, imgs, paths, shapes, person_dets, kp_dets,
45
+ two_stage=False, pad=0, device='cpu', model=None, origins=None):
46
+
47
+ batch_bboxes, batch_poses, batch_scores, batch_ids = [], [], [], []
48
+ n_fused = np.zeros(data['num_coords'] // 2)
49
+
50
+ if origins is None: # used only for two-stage inference so set to 0 if None
51
+ origins = [np.array([0, 0, 0]) for _ in range(len(person_dets))]
52
+
53
+ # process each image in batch
54
+ for si, (pd, kpd, origin) in enumerate(zip(person_dets, kp_dets, origins)):
55
+ nd = pd.shape[0]
56
+ nkp = kpd.shape[0]
57
+
58
+ if nd:
59
+ path, shape = Path(paths[si]) if len(paths) else '', shapes[si][0]
60
+ img_id = int(osp.splitext(osp.split(path)[-1])[0]) if path else si
61
+
62
+ # TWO-STAGE INFERENCE (EXPERIMENTAL)
63
+ if two_stage:
64
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
65
+ crops, origins, crop_shapes = [], [], []
66
+
67
+ for bbox in pd[:, :4].cpu().numpy():
68
+ x1, y1, x2, y2 = map(int, map(round, bbox))
69
+ x1, x2 = max(x1, 0), min(x2, data['imgsz'])
70
+ y1, y2 = max(y1, 0), min(y2, data['imgsz'])
71
+ h0, w0 = y2 - y1, x2 - x1
72
+ crop_shapes.append([(h0, w0)])
73
+ crop = np.transpose(imgs[si][:, y1:y2, x1:x2].cpu().numpy(), (1, 2, 0))
74
+ crop = cv2.copyMakeBorder(crop, pad, pad, pad, pad, cv2.BORDER_CONSTANT, value=PAD_COLOR) # add padding
75
+ h0 += 2 * pad
76
+ w0 += 2 * pad
77
+ origins = [np.array([x1 - pad, y1 - pad, 0])]
78
+ crop_pre = letterbox(crop, data['imgsz'], color=PAD_COLOR, stride=gs, auto=False)[0]
79
+ crop_input = torch.Tensor(np.transpose(np.expand_dims(crop_pre, axis=0), (0, 3, 1, 2))).to(device)
80
+
81
+ out = model(crop_input, augment=True, kp_flip=data['kp_flip'], scales=data['scales'], flips=data['flips'])[0]
82
+ person_dets, kp_dets = run_nms(data, out)
83
+ _, poses, scores, img_ids, _ = post_process_batch(
84
+ data, crop_input, paths, [[(h0, w0)]], person_dets, kp_dets, device=device, origins=origins)
85
+
86
+ # map back to original image
87
+ if len(poses):
88
+ poses = np.stack(poses, axis=0)
89
+ poses = poses[:, :, :2].reshape(poses.shape[0], -1)
90
+ poses = scale_coords(imgs[si].shape[1:], poses, shape)
91
+ poses = poses.reshape(poses.shape[0], data['num_coords'] // 2, 2)
92
+ poses = np.concatenate((poses, np.zeros((poses.shape[0], data['num_coords'] // 2, 1))), axis=-1)
93
+ poses = [p for p in poses] # convert back to list
94
+
95
+ # SINGLE-STAGE INFERENCE
96
+ else:
97
+ scores = pd[:, 4].cpu().numpy() # person detection score
98
+ bboxes = scale_coords(imgs[si].shape[1:], pd[:, :4], shape).round().cpu().numpy()
99
+ poses = scale_coords(imgs[si].shape[1:], pd[:, -data['num_coords']:], shape).cpu().numpy()
100
+ poses = poses.reshape((nd, -data['num_coords'], 2))
101
+ poses = np.concatenate((poses, np.zeros((nd, poses.shape[1], 1))), axis=-1)
102
+
103
+ if data['use_kp_dets'] and nkp:
104
+ mask = scores > data['conf_thres_kp_person']
105
+ poses_mask = poses[mask]
106
+
107
+ if len(poses_mask):
108
+ kpd[:, :4] = scale_coords(imgs[si].shape[1:], kpd[:, :4], shape)
109
+ kpd = kpd[:, :6].cpu()
110
+
111
+ for x1, y1, x2, y2, conf, cls in kpd:
112
+ x, y = np.mean((x1, x2)), np.mean((y1, y2))
113
+ pose_kps = poses_mask[:, int(cls - 1)]
114
+ dist = np.linalg.norm(pose_kps[:, :2] - np.array([[x, y]]), axis=-1)
115
+ kp_match = np.argmin(dist)
116
+ if conf > pose_kps[kp_match, 2] and dist[kp_match] < data['overwrite_tol']:
117
+ pose_kps[kp_match] = [x, y, conf]
118
+ n_fused[int(cls - 1)] += 1
119
+ poses[mask] = poses_mask
120
+
121
+ poses = [p + origin for p in poses]
122
+
123
+ batch_bboxes.extend(bboxes)
124
+ batch_poses.extend(poses)
125
+ batch_scores.extend(scores)
126
+ batch_ids.extend([img_id] * len(scores))
127
+
128
+ return batch_bboxes, batch_poses, batch_scores, batch_ids, n_fused
129
+
130
+
131
+ @torch.no_grad()
132
+ def run(data,
133
+ weights=None, # model.pt path(s)
134
+ batch_size=16, # batch size
135
+ imgsz=1280, # inference size (pixels)
136
+ task='val', # train, val, test, speed or study
137
+ device='', # cuda device, i.e. 0 or 0,1,2,3 or cpu
138
+ conf_thres=0.001, # confidence threshold
139
+ iou_thres=0.65, # NMS IoU threshold
140
+ no_kp_dets=False,
141
+ conf_thres_kp=0.2,
142
+ iou_thres_kp=0.25,
143
+ conf_thres_kp_person=0.3,
144
+ overwrite_tol=50, # pixels for kp det overwrite
145
+ scales=[1],
146
+ flips=[None],
147
+ rect=False,
148
+ half=True, # use FP16 half-precision inference
149
+ model=None,
150
+ dataloader=None,
151
+ compute_loss=None,
152
+ two_stage=False,
153
+ pad=0
154
+ ):
155
+
156
+ if two_stage:
157
+ assert batch_size == 1, 'Batch size must be set to 1 for two-stage processing'
158
+ assert conf_thres >= 0.01, 'Confidence threshold must be >= 0.01 for two-stage processing'
159
+ assert not rect, 'Cannot use rectangular inference with two-stage processing'
160
+ assert not half, 'Two-stage processing must use full precision'
161
+
162
+ use_kp_dets = not no_kp_dets
163
+
164
+ # Initialize/load model and set device
165
+ training = model is not None
166
+ if training: # called by train.py
167
+ device = next(model.parameters()).device # get model device
168
+ else: # called directly
169
+ device = select_device(device, batch_size=batch_size)
170
+
171
+ # Load model
172
+ model = attempt_load(weights, map_location=device) # load FP32 model
173
+ gs = max(int(model.stride.max()), 32) # grid size (max stride)
174
+ imgsz = check_img_size(imgsz, s=gs) # check image size
175
+
176
+ # Data
177
+ data = check_dataset(data) # check
178
+
179
+ # add inference settings to data dict
180
+ data['imgsz'] = imgsz
181
+ data['conf_thres'] = conf_thres
182
+ data['iou_thres'] = iou_thres
183
+ data['use_kp_dets'] = use_kp_dets
184
+ data['conf_thres_kp'] = conf_thres_kp
185
+ data['iou_thres_kp'] = iou_thres_kp
186
+ data['conf_thres_kp_person'] = conf_thres_kp_person
187
+ data['overwrite_tol'] = overwrite_tol
188
+ data['scales'] = scales
189
+ data['flips'] = flips
190
+
191
+ is_coco = 'coco' in data['path']
192
+ if is_coco:
193
+ from pycocotools.coco import COCO
194
+ from pycocotools.cocoeval import COCOeval
195
+ else:
196
+ from crowdposetools.coco import COCO
197
+ from crowdposetools.cocoeval import COCOeval
198
+
199
+ # Half
200
+ half &= device.type != 'cpu' # half precision only supported on CUDA
201
+ if half:
202
+ model.half()
203
+
204
+ model.eval()
205
+ nc = int(data['nc']) # number of classes
206
+
207
+ # Dataloader
208
+ if not training:
209
+ if device.type != 'cpu':
210
+ model(torch.zeros(1, 3, imgsz, imgsz).to(device).type_as(next(model.parameters()))) # run once
211
+ task = task if task in ('train', 'val', 'test') else 'val' # path to train/val/test images
212
+ dataloader = create_dataloader(data[task], data['labels'], imgsz, batch_size, gs, rect=rect,
213
+ prefix=colorstr(f'{task}: '), kp_flip=data['kp_flip'])[0]
214
+
215
+ seen = 0
216
+ mp, mr, map50, mAP, t0, t1, t2 = 0., 0., 0., 0., 0., 0., 0.
217
+ loss = torch.zeros(4, device=device)
218
+ json_dump = []
219
+ n_fused = np.zeros(data['num_coords'] // 2)
220
+
221
+ for batch_i, (imgs, targets, paths, shapes) in enumerate(tqdm(dataloader, desc='Processing {} images'.format(task))):
222
+ t_ = time_sync()
223
+ imgs = imgs.to(device, non_blocking=True)
224
+ imgs = imgs.half() if half else imgs.float() # uint8 to fp16/32
225
+ imgs /= 255.0 # 0 - 255 to 0.0 - 1.0
226
+ targets = targets.to(device)
227
+ nb, _, height, width = imgs.shape # batch size, channels, height, width
228
+ t = time_sync()
229
+ t0 += t - t_
230
+
231
+ # Run model
232
+ out, train_out = model(imgs, augment=True, kp_flip=data['kp_flip'], scales=data['scales'], flips=data['flips'])
233
+ t1 += time_sync() - t
234
+
235
+ # Compute loss
236
+ if train_out: # only computed if no scale / flipping
237
+ if compute_loss:
238
+ loss += compute_loss([x.float() for x in train_out], targets)[1] # box, obj, cls, kp
239
+
240
+ t = time_sync()
241
+
242
+ # NMS
243
+ person_dets, kp_dets = run_nms(data, out)
244
+
245
+ # Fuse keypoint and pose detections
246
+ _, poses, scores, img_ids, n_fused_batch = post_process_batch(
247
+ data, imgs, paths, shapes, person_dets, kp_dets, two_stage, pad, device, model)
248
+
249
+ t2 += time_sync() - t
250
+ seen += len(imgs)
251
+ n_fused += n_fused_batch
252
+
253
+ for i, (pose, score, img_id) in enumerate(zip(poses, scores, img_ids)):
254
+ json_dump.append({
255
+ 'image_id': img_id,
256
+ 'category_id': 1,
257
+ 'keypoints': pose.reshape(-1).tolist(),
258
+ 'score': float(score) # person score
259
+ })
260
+
261
+ if not training: # save json
262
+ save_dir, weights_name = osp.split(weights)
263
+ json_name = '{}_{}_c{}_i{}_ck{}_ik{}_ckp{}_t{}.json'.format(
264
+ task, osp.splitext(weights_name)[0],
265
+ conf_thres, iou_thres, conf_thres_kp, iou_thres_kp,
266
+ conf_thres_kp_person, overwrite_tol
267
+ )
268
+ json_path = osp.join(save_dir, json_name)
269
+ else:
270
+ tmp = tempfile.NamedTemporaryFile(mode='w+b')
271
+ json_path = tmp.name
272
+
273
+ with open(json_path, 'w') as f:
274
+ json.dump(json_dump, f)
275
+
276
+ if task in ('train', 'val'):
277
+ annot = osp.join(data['path'], data['{}_annotations'.format(task)])
278
+ coco = COCO(annot)
279
+ result = coco.loadRes(json_path)
280
+ eval = COCOeval(coco, result, iouType='keypoints')
281
+ eval.evaluate()
282
+ eval.accumulate()
283
+ eval.summarize()
284
+ mAP, map50 = eval.stats[:2]
285
+
286
+ if training:
287
+ tmp.close()
288
+
289
+ # Print speeds
290
+ t = tuple(x / seen * 1E3 for x in (t0, t1, t2)) # speeds per image
291
+ if not training and task != 'test':
292
+ os.rename(json_path, osp.splitext(json_path)[0] + '_ap{:.4f}.json'.format(mAP))
293
+ shape = (batch_size, 3, imgsz, imgsz)
294
+ print(f'Speed: %.3fms pre-process, %.3fms inference, %.3fms NMS per image at shape {shape}' % t)
295
+ print('Keypoint Objects Fused:', n_fused)
296
+ model.float() # for training
297
+ return (mp, mr, map50, mAP, *(loss.cpu() / len(dataloader)).tolist()), np.zeros(nc), t # for compatibility with train
298
+
299
+
300
+ def parse_opt():
301
+ parser = argparse.ArgumentParser(prog='val.py')
302
+ parser.add_argument('--data', type=str, default='data/coco-kp.yaml', help='dataset.yaml path')
303
+ parser.add_argument('--weights', default='kapao_s_coco.pt')
304
+ parser.add_argument('--batch-size', type=int, default=1, help='batch size')
305
+ parser.add_argument('--imgsz', type=int, default=1280, help='inference size (pixels)')
306
+ parser.add_argument('--task', default='val', help='train, val, test')
307
+ parser.add_argument('--device', default='', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
308
+ parser.add_argument('--conf-thres', type=float, default=0.001, help='confidence threshold')
309
+ parser.add_argument('--iou-thres', type=float, default=0.65, help='NMS IoU threshold')
310
+ parser.add_argument('--no-kp-dets', action='store_true', help='do not use keypoint objects')
311
+ parser.add_argument('--conf-thres-kp', type=float, default=0.2)
312
+ parser.add_argument('--conf-thres-kp-person', type=float, default=0.3)
313
+ parser.add_argument('--iou-thres-kp', type=float, default=0.25)
314
+ parser.add_argument('--overwrite-tol', type=int, default=50)
315
+ parser.add_argument('--scales', type=float, nargs='+', default=[1])
316
+ parser.add_argument('--flips', type=int, nargs='+', default=[-1])
317
+ parser.add_argument('--rect', action='store_true', help='rectangular input image')
318
+ parser.add_argument('--half', action='store_true', help='use FP16 half-precision inference')
319
+ parser.add_argument('--two-stage', action='store_true', help='use two-stage inference (experimental)')
320
+ parser.add_argument('--pad', type=int, default=0, help='padding for two-stage inference')
321
+ opt = parser.parse_args()
322
+ opt.flips = [None if f == -1 else f for f in opt.flips]
323
+ opt.data = check_file(opt.data) # check file
324
+ return opt
325
+
326
+
327
+ def main(opt):
328
+ set_logging()
329
+ print(colorstr('val: ') + ', '.join(f'{k}={v}' for k, v in vars(opt).items()))
330
+ if opt.task in ('train', 'val', 'test'): # run normally
331
+ run(**vars(opt))
332
+
333
+
334
+ if __name__ == "__main__":
335
+ opt = parse_opt()
336
+ main(opt)