bplusplus 1.1.0__py3-none-any.whl → 1.2.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Potentially problematic release.
This version of bplusplus might be problematic. Click here for more details.
- bplusplus/__init__.py +4 -2
- bplusplus/collect.py +69 -5
- bplusplus/hierarchical/test.py +670 -0
- bplusplus/hierarchical/train.py +676 -0
- bplusplus/prepare.py +228 -64
- bplusplus/resnet/test.py +473 -0
- bplusplus/resnet/train.py +329 -0
- bplusplus-1.2.0.dist-info/METADATA +249 -0
- bplusplus-1.2.0.dist-info/RECORD +12 -0
- bplusplus/yolov5detect/__init__.py +0 -1
- bplusplus/yolov5detect/detect.py +0 -444
- bplusplus/yolov5detect/export.py +0 -1530
- bplusplus/yolov5detect/insect.yaml +0 -8
- bplusplus/yolov5detect/models/__init__.py +0 -0
- bplusplus/yolov5detect/models/common.py +0 -1109
- bplusplus/yolov5detect/models/experimental.py +0 -130
- bplusplus/yolov5detect/models/hub/anchors.yaml +0 -56
- bplusplus/yolov5detect/models/hub/yolov3-spp.yaml +0 -52
- bplusplus/yolov5detect/models/hub/yolov3-tiny.yaml +0 -42
- bplusplus/yolov5detect/models/hub/yolov3.yaml +0 -52
- bplusplus/yolov5detect/models/hub/yolov5-bifpn.yaml +0 -49
- bplusplus/yolov5detect/models/hub/yolov5-fpn.yaml +0 -43
- bplusplus/yolov5detect/models/hub/yolov5-p2.yaml +0 -55
- bplusplus/yolov5detect/models/hub/yolov5-p34.yaml +0 -42
- bplusplus/yolov5detect/models/hub/yolov5-p6.yaml +0 -57
- bplusplus/yolov5detect/models/hub/yolov5-p7.yaml +0 -68
- bplusplus/yolov5detect/models/hub/yolov5-panet.yaml +0 -49
- bplusplus/yolov5detect/models/hub/yolov5l6.yaml +0 -61
- bplusplus/yolov5detect/models/hub/yolov5m6.yaml +0 -61
- bplusplus/yolov5detect/models/hub/yolov5n6.yaml +0 -61
- bplusplus/yolov5detect/models/hub/yolov5s-LeakyReLU.yaml +0 -50
- bplusplus/yolov5detect/models/hub/yolov5s-ghost.yaml +0 -49
- bplusplus/yolov5detect/models/hub/yolov5s-transformer.yaml +0 -49
- bplusplus/yolov5detect/models/hub/yolov5s6.yaml +0 -61
- bplusplus/yolov5detect/models/hub/yolov5x6.yaml +0 -61
- bplusplus/yolov5detect/models/segment/yolov5l-seg.yaml +0 -49
- bplusplus/yolov5detect/models/segment/yolov5m-seg.yaml +0 -49
- bplusplus/yolov5detect/models/segment/yolov5n-seg.yaml +0 -49
- bplusplus/yolov5detect/models/segment/yolov5s-seg.yaml +0 -49
- bplusplus/yolov5detect/models/segment/yolov5x-seg.yaml +0 -49
- bplusplus/yolov5detect/models/tf.py +0 -797
- bplusplus/yolov5detect/models/yolo.py +0 -495
- bplusplus/yolov5detect/models/yolov5l.yaml +0 -49
- bplusplus/yolov5detect/models/yolov5m.yaml +0 -49
- bplusplus/yolov5detect/models/yolov5n.yaml +0 -49
- bplusplus/yolov5detect/models/yolov5s.yaml +0 -49
- bplusplus/yolov5detect/models/yolov5x.yaml +0 -49
- bplusplus/yolov5detect/utils/__init__.py +0 -97
- bplusplus/yolov5detect/utils/activations.py +0 -134
- bplusplus/yolov5detect/utils/augmentations.py +0 -448
- bplusplus/yolov5detect/utils/autoanchor.py +0 -175
- bplusplus/yolov5detect/utils/autobatch.py +0 -70
- bplusplus/yolov5detect/utils/aws/__init__.py +0 -0
- bplusplus/yolov5detect/utils/aws/mime.sh +0 -26
- bplusplus/yolov5detect/utils/aws/resume.py +0 -41
- bplusplus/yolov5detect/utils/aws/userdata.sh +0 -27
- bplusplus/yolov5detect/utils/callbacks.py +0 -72
- bplusplus/yolov5detect/utils/dataloaders.py +0 -1385
- bplusplus/yolov5detect/utils/docker/Dockerfile +0 -73
- bplusplus/yolov5detect/utils/docker/Dockerfile-arm64 +0 -40
- bplusplus/yolov5detect/utils/docker/Dockerfile-cpu +0 -42
- bplusplus/yolov5detect/utils/downloads.py +0 -136
- bplusplus/yolov5detect/utils/flask_rest_api/README.md +0 -70
- bplusplus/yolov5detect/utils/flask_rest_api/example_request.py +0 -17
- bplusplus/yolov5detect/utils/flask_rest_api/restapi.py +0 -49
- bplusplus/yolov5detect/utils/general.py +0 -1294
- bplusplus/yolov5detect/utils/google_app_engine/Dockerfile +0 -25
- bplusplus/yolov5detect/utils/google_app_engine/additional_requirements.txt +0 -6
- bplusplus/yolov5detect/utils/google_app_engine/app.yaml +0 -16
- bplusplus/yolov5detect/utils/loggers/__init__.py +0 -476
- bplusplus/yolov5detect/utils/loggers/clearml/README.md +0 -222
- bplusplus/yolov5detect/utils/loggers/clearml/__init__.py +0 -0
- bplusplus/yolov5detect/utils/loggers/clearml/clearml_utils.py +0 -230
- bplusplus/yolov5detect/utils/loggers/clearml/hpo.py +0 -90
- bplusplus/yolov5detect/utils/loggers/comet/README.md +0 -250
- bplusplus/yolov5detect/utils/loggers/comet/__init__.py +0 -551
- bplusplus/yolov5detect/utils/loggers/comet/comet_utils.py +0 -151
- bplusplus/yolov5detect/utils/loggers/comet/hpo.py +0 -126
- bplusplus/yolov5detect/utils/loggers/comet/optimizer_config.json +0 -135
- bplusplus/yolov5detect/utils/loggers/wandb/__init__.py +0 -0
- bplusplus/yolov5detect/utils/loggers/wandb/wandb_utils.py +0 -210
- bplusplus/yolov5detect/utils/loss.py +0 -259
- bplusplus/yolov5detect/utils/metrics.py +0 -381
- bplusplus/yolov5detect/utils/plots.py +0 -517
- bplusplus/yolov5detect/utils/segment/__init__.py +0 -0
- bplusplus/yolov5detect/utils/segment/augmentations.py +0 -100
- bplusplus/yolov5detect/utils/segment/dataloaders.py +0 -366
- bplusplus/yolov5detect/utils/segment/general.py +0 -160
- bplusplus/yolov5detect/utils/segment/loss.py +0 -198
- bplusplus/yolov5detect/utils/segment/metrics.py +0 -225
- bplusplus/yolov5detect/utils/segment/plots.py +0 -152
- bplusplus/yolov5detect/utils/torch_utils.py +0 -482
- bplusplus/yolov5detect/utils/triton.py +0 -90
- bplusplus-1.1.0.dist-info/METADATA +0 -179
- bplusplus-1.1.0.dist-info/RECORD +0 -92
- {bplusplus-1.1.0.dist-info → bplusplus-1.2.0.dist-info}/LICENSE +0 -0
- {bplusplus-1.1.0.dist-info → bplusplus-1.2.0.dist-info}/WHEEL +0 -0
bplusplus/yolov5detect/detect.py
DELETED
|
@@ -1,444 +0,0 @@
|
|
|
1
|
-
# Ultralytics YOLOv5 🚀, AGPL-3.0 license
|
|
2
|
-
"""
|
|
3
|
-
Run YOLOv5 detection inference on images, videos, directories, globs, YouTube, webcam, streams, etc.
|
|
4
|
-
|
|
5
|
-
Usage - sources:
|
|
6
|
-
$ python detect.py --weights yolov5s.pt --source 0 # webcam
|
|
7
|
-
img.jpg # image
|
|
8
|
-
vid.mp4 # video
|
|
9
|
-
screen # screenshot
|
|
10
|
-
path/ # directory
|
|
11
|
-
list.txt # list of images
|
|
12
|
-
list.streams # list of streams
|
|
13
|
-
'path/*.jpg' # glob
|
|
14
|
-
'https://youtu.be/LNwODJXcvt4' # YouTube
|
|
15
|
-
'rtsp://example.com/media.mp4' # RTSP, RTMP, HTTP stream
|
|
16
|
-
|
|
17
|
-
Usage - formats:
|
|
18
|
-
$ python detect.py --weights yolov5s.pt # PyTorch
|
|
19
|
-
yolov5s.torchscript # TorchScript
|
|
20
|
-
yolov5s.onnx # ONNX Runtime or OpenCV DNN with --dnn
|
|
21
|
-
yolov5s_openvino_model # OpenVINO
|
|
22
|
-
yolov5s.engine # TensorRT
|
|
23
|
-
yolov5s.mlpackage # CoreML (macOS-only)
|
|
24
|
-
yolov5s_saved_model # TensorFlow SavedModel
|
|
25
|
-
yolov5s.pb # TensorFlow GraphDef
|
|
26
|
-
yolov5s.tflite # TensorFlow Lite
|
|
27
|
-
yolov5s_edgetpu.tflite # TensorFlow Edge TPU
|
|
28
|
-
yolov5s_paddle_model # PaddlePaddle
|
|
29
|
-
"""
|
|
30
|
-
|
|
31
|
-
import argparse
|
|
32
|
-
import csv
|
|
33
|
-
import os
|
|
34
|
-
import platform
|
|
35
|
-
import sys
|
|
36
|
-
from pathlib import Path
|
|
37
|
-
|
|
38
|
-
import torch
|
|
39
|
-
|
|
40
|
-
FILE = Path(__file__).resolve()
|
|
41
|
-
ROOT = FILE.parents[0] # YOLOv5 root directory
|
|
42
|
-
if str(ROOT) not in sys.path:
|
|
43
|
-
sys.path.append(str(ROOT)) # add ROOT to PATH
|
|
44
|
-
ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
|
|
45
|
-
|
|
46
|
-
from ultralytics.utils.plotting import Annotator, colors, save_one_box
|
|
47
|
-
|
|
48
|
-
from models.common import DetectMultiBackend
|
|
49
|
-
from utils.dataloaders import IMG_FORMATS, VID_FORMATS, LoadImages, LoadScreenshots, LoadStreams
|
|
50
|
-
from utils.general import (
|
|
51
|
-
LOGGER,
|
|
52
|
-
Profile,
|
|
53
|
-
check_file,
|
|
54
|
-
check_img_size,
|
|
55
|
-
check_imshow,
|
|
56
|
-
check_requirements,
|
|
57
|
-
colorstr,
|
|
58
|
-
cv2,
|
|
59
|
-
increment_path,
|
|
60
|
-
non_max_suppression,
|
|
61
|
-
print_args,
|
|
62
|
-
scale_boxes,
|
|
63
|
-
strip_optimizer,
|
|
64
|
-
xyxy2xywh,
|
|
65
|
-
)
|
|
66
|
-
from utils.torch_utils import select_device, smart_inference_mode
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
@smart_inference_mode()
|
|
70
|
-
def run(
|
|
71
|
-
weights=ROOT / "yolov5s.pt", # model path or triton URL
|
|
72
|
-
source=ROOT / "data/images", # file/dir/URL/glob/screen/0(webcam)
|
|
73
|
-
data=ROOT / "data/coco128.yaml", # dataset.yaml path
|
|
74
|
-
imgsz=(640, 640), # inference size (height, width)
|
|
75
|
-
conf_thres=0.5, # confidence threshold
|
|
76
|
-
iou_thres=0.45, # NMS IOU threshold
|
|
77
|
-
max_det=1000, # maximum detections per image
|
|
78
|
-
device="", # cuda device, i.e. 0 or 0,1,2,3 or cpu
|
|
79
|
-
view_img=False, # show results
|
|
80
|
-
save_txt=False, # save results to *.txt
|
|
81
|
-
save_format=0, # save boxes coordinates in YOLO format or Pascal-VOC format (0 for YOLO and 1 for Pascal-VOC)
|
|
82
|
-
save_csv=False, # save results in CSV format
|
|
83
|
-
save_conf=False, # save confidences in --save-txt labels
|
|
84
|
-
save_crop=False, # save cropped prediction boxes
|
|
85
|
-
nosave=False, # do not save images/videos
|
|
86
|
-
classes=None, # filter by class: --class 0, or --class 0 2 3
|
|
87
|
-
agnostic_nms=False, # class-agnostic NMS
|
|
88
|
-
augment=False, # augmented inference
|
|
89
|
-
visualize=False, # visualize features
|
|
90
|
-
update=False, # update all models
|
|
91
|
-
project=ROOT / "runs/detect", # save results to project/name
|
|
92
|
-
name="exp", # save results to project/name
|
|
93
|
-
exist_ok=False, # existing project/name ok, do not increment
|
|
94
|
-
line_thickness=3, # bounding box thickness (pixels)
|
|
95
|
-
hide_labels=False, # hide labels
|
|
96
|
-
hide_conf=False, # hide confidences
|
|
97
|
-
half=False, # use FP16 half-precision inference
|
|
98
|
-
dnn=False, # use OpenCV DNN for ONNX inference
|
|
99
|
-
vid_stride=1, # video frame-rate stride
|
|
100
|
-
):
|
|
101
|
-
"""
|
|
102
|
-
Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc.
|
|
103
|
-
|
|
104
|
-
Args:
|
|
105
|
-
weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'.
|
|
106
|
-
source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam
|
|
107
|
-
index. Default is 'data/images'.
|
|
108
|
-
data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'.
|
|
109
|
-
imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640).
|
|
110
|
-
conf_thres (float): Confidence threshold for detections. Default is 0.25.
|
|
111
|
-
iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45.
|
|
112
|
-
max_det (int): Maximum number of detections per image. Default is 1000.
|
|
113
|
-
device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the
|
|
114
|
-
best available device.
|
|
115
|
-
view_img (bool): If True, display inference results using OpenCV. Default is False.
|
|
116
|
-
save_txt (bool): If True, save results in a text file. Default is False.
|
|
117
|
-
save_csv (bool): If True, save results in a CSV file. Default is False.
|
|
118
|
-
save_conf (bool): If True, include confidence scores in the saved results. Default is False.
|
|
119
|
-
save_crop (bool): If True, save cropped prediction boxes. Default is False.
|
|
120
|
-
nosave (bool): If True, do not save inference images or videos. Default is False.
|
|
121
|
-
classes (list[int]): List of class indices to filter detections by. Default is None.
|
|
122
|
-
agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
|
|
123
|
-
augment (bool): If True, use augmented inference. Default is False.
|
|
124
|
-
visualize (bool): If True, visualize feature maps. Default is False.
|
|
125
|
-
update (bool): If True, update all models' weights. Default is False.
|
|
126
|
-
project (str | Path): Directory to save results. Default is 'runs/detect'.
|
|
127
|
-
name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
|
|
128
|
-
exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is
|
|
129
|
-
False.
|
|
130
|
-
line_thickness (int): Thickness of bounding box lines in pixels. Default is 3.
|
|
131
|
-
hide_labels (bool): If True, do not display labels on bounding boxes. Default is False.
|
|
132
|
-
hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False.
|
|
133
|
-
half (bool): If True, use FP16 half-precision inference. Default is False.
|
|
134
|
-
dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False.
|
|
135
|
-
vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1.
|
|
136
|
-
|
|
137
|
-
Returns:
|
|
138
|
-
None
|
|
139
|
-
|
|
140
|
-
Examples:
|
|
141
|
-
```python
|
|
142
|
-
from ultralytics import run
|
|
143
|
-
|
|
144
|
-
# Run inference on an image
|
|
145
|
-
run(source='data/images/example.jpg', weights='yolov5s.pt', device='0')
|
|
146
|
-
|
|
147
|
-
# Run inference on a video with specific confidence threshold
|
|
148
|
-
run(source='data/videos/example.mp4', weights='yolov5s.pt', conf_thres=0.4, device='0')
|
|
149
|
-
```
|
|
150
|
-
"""
|
|
151
|
-
source = str(source)
|
|
152
|
-
save_img = not nosave and not source.endswith(".txt") # save inference images
|
|
153
|
-
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
|
154
|
-
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
|
|
155
|
-
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
|
|
156
|
-
screenshot = source.lower().startswith("screen")
|
|
157
|
-
if is_url and is_file:
|
|
158
|
-
source = check_file(source) # download
|
|
159
|
-
|
|
160
|
-
# Directories
|
|
161
|
-
# save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
|
162
|
-
# (save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
|
163
|
-
|
|
164
|
-
save_dir = Path(project) / "labels" #static path to make work with yolo_labels.py (EDIT: Orlando Closs)
|
|
165
|
-
inference_dir = Path(project) / "inference" #(EDIT: Orlando Closs)
|
|
166
|
-
|
|
167
|
-
# Load model
|
|
168
|
-
device = select_device(device)
|
|
169
|
-
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
|
170
|
-
stride, names, pt = model.stride, model.names, model.pt
|
|
171
|
-
imgsz = check_img_size(imgsz, s=stride) # check image size
|
|
172
|
-
|
|
173
|
-
# Dataloader
|
|
174
|
-
bs = 1 # batch_size
|
|
175
|
-
if webcam:
|
|
176
|
-
view_img = check_imshow(warn=True)
|
|
177
|
-
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
|
178
|
-
bs = len(dataset)
|
|
179
|
-
elif screenshot:
|
|
180
|
-
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
|
181
|
-
else:
|
|
182
|
-
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
|
183
|
-
vid_path, vid_writer = [None] * bs, [None] * bs
|
|
184
|
-
|
|
185
|
-
# Run inference
|
|
186
|
-
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
|
|
187
|
-
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
|
|
188
|
-
for path, im, im0s, vid_cap, s in dataset:
|
|
189
|
-
try:
|
|
190
|
-
with dt[0]:
|
|
191
|
-
im = torch.from_numpy(im).to(model.device)
|
|
192
|
-
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
|
193
|
-
im /= 255 # 0 - 255 to 0.0 - 1.0
|
|
194
|
-
if len(im.shape) == 3:
|
|
195
|
-
im = im[None] # expand for batch dim
|
|
196
|
-
if model.xml and im.shape[0] > 1:
|
|
197
|
-
ims = torch.chunk(im, im.shape[0], 0)
|
|
198
|
-
|
|
199
|
-
# Inference
|
|
200
|
-
with dt[1]:
|
|
201
|
-
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
|
202
|
-
if model.xml and im.shape[0] > 1:
|
|
203
|
-
pred = None
|
|
204
|
-
for image in ims:
|
|
205
|
-
if pred is None:
|
|
206
|
-
pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
|
|
207
|
-
else:
|
|
208
|
-
pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
|
|
209
|
-
pred = [pred, None]
|
|
210
|
-
else:
|
|
211
|
-
pred = model(im, augment=augment, visualize=visualize)
|
|
212
|
-
# NMS
|
|
213
|
-
with dt[2]:
|
|
214
|
-
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
|
215
|
-
|
|
216
|
-
# Second-stage classifier (optional)
|
|
217
|
-
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
|
218
|
-
|
|
219
|
-
# Define the path for the CSV file
|
|
220
|
-
csv_path = save_dir / "predictions.csv"
|
|
221
|
-
except Exception as e:
|
|
222
|
-
print(f"Error processing image {path}: {e}")
|
|
223
|
-
continue
|
|
224
|
-
|
|
225
|
-
# Create or append to the CSV file
|
|
226
|
-
def write_to_csv(image_name, prediction, confidence):
|
|
227
|
-
"""Writes prediction data for an image to a CSV file, appending if the file exists."""
|
|
228
|
-
data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
|
|
229
|
-
with open(csv_path, mode="a", newline="") as f:
|
|
230
|
-
writer = csv.DictWriter(f, fieldnames=data.keys())
|
|
231
|
-
if not csv_path.is_file():
|
|
232
|
-
writer.writeheader()
|
|
233
|
-
writer.writerow(data)
|
|
234
|
-
|
|
235
|
-
# Process predictions
|
|
236
|
-
for i, det in enumerate(pred): # per image
|
|
237
|
-
seen += 1
|
|
238
|
-
if webcam: # batch_size >= 1
|
|
239
|
-
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
|
240
|
-
s += f"{i}: "
|
|
241
|
-
else:
|
|
242
|
-
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
|
|
243
|
-
|
|
244
|
-
p = Path(p) # to Path
|
|
245
|
-
save_path = str(inference_dir / p.name) # im.jpg EDIT: Orlando Closs
|
|
246
|
-
txt_path = str(save_dir / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt EDIT: Orlando Closs
|
|
247
|
-
s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
|
|
248
|
-
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
|
249
|
-
imc = im0.copy() if save_crop else im0 # for save_crop
|
|
250
|
-
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
|
251
|
-
if len(det):
|
|
252
|
-
# Rescale boxes from img_size to im0 size
|
|
253
|
-
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
|
|
254
|
-
|
|
255
|
-
# Print results
|
|
256
|
-
for c in det[:, 5].unique():
|
|
257
|
-
n = (det[:, 5] == c).sum() # detections per class
|
|
258
|
-
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
|
259
|
-
|
|
260
|
-
# Write results
|
|
261
|
-
for *xyxy, conf, cls in reversed(det):
|
|
262
|
-
c = int(cls) # integer class
|
|
263
|
-
label = names[c] if hide_conf else f"{names[c]}"
|
|
264
|
-
confidence = float(conf)
|
|
265
|
-
confidence_str = f"{confidence:.2f}"
|
|
266
|
-
|
|
267
|
-
if save_csv:
|
|
268
|
-
write_to_csv(p.name, label, confidence_str)
|
|
269
|
-
|
|
270
|
-
if save_txt: # Write to file
|
|
271
|
-
if save_format == 0:
|
|
272
|
-
coords = (
|
|
273
|
-
(xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
|
|
274
|
-
) # normalized xywh
|
|
275
|
-
else:
|
|
276
|
-
coords = (torch.tensor(xyxy).view(1, 4) / gn).view(-1).tolist() # xyxy
|
|
277
|
-
line = (cls, *coords, conf) if save_conf else (cls, *coords) # label format
|
|
278
|
-
with open(f"{txt_path}.txt", "a") as f:
|
|
279
|
-
f.write(("%g " * len(line)).rstrip() % line + "\n")
|
|
280
|
-
|
|
281
|
-
if save_img or save_crop or view_img: # Add bbox to image
|
|
282
|
-
c = int(cls) # integer class
|
|
283
|
-
label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
|
|
284
|
-
annotator.box_label(xyxy, label, color=colors(c, True))
|
|
285
|
-
if save_crop:
|
|
286
|
-
save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
|
|
287
|
-
|
|
288
|
-
# Stream results
|
|
289
|
-
im0 = annotator.result()
|
|
290
|
-
if view_img:
|
|
291
|
-
if platform.system() == "Linux" and p not in windows:
|
|
292
|
-
windows.append(p)
|
|
293
|
-
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
|
294
|
-
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
|
295
|
-
cv2.imshow(str(p), im0)
|
|
296
|
-
cv2.waitKey(1) # 1 millisecond
|
|
297
|
-
|
|
298
|
-
# Save results (image with detections)
|
|
299
|
-
if save_img:
|
|
300
|
-
if dataset.mode == "image":
|
|
301
|
-
cv2.imwrite(save_path, im0)
|
|
302
|
-
else: # 'video' or 'stream'
|
|
303
|
-
if vid_path[i] != save_path: # new video
|
|
304
|
-
vid_path[i] = save_path
|
|
305
|
-
if isinstance(vid_writer[i], cv2.VideoWriter):
|
|
306
|
-
vid_writer[i].release() # release previous video writer
|
|
307
|
-
if vid_cap: # video
|
|
308
|
-
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
|
309
|
-
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
|
310
|
-
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
|
311
|
-
else: # stream
|
|
312
|
-
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
|
313
|
-
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
|
|
314
|
-
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
|
315
|
-
vid_writer[i].write(im0)
|
|
316
|
-
|
|
317
|
-
# Print time (inference-only)
|
|
318
|
-
LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
|
|
319
|
-
|
|
320
|
-
# Print results
|
|
321
|
-
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
|
|
322
|
-
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
|
|
323
|
-
if save_txt or save_img:
|
|
324
|
-
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
|
|
325
|
-
# LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
|
326
|
-
if update:
|
|
327
|
-
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
def parse_opt():
|
|
331
|
-
"""
|
|
332
|
-
Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations.
|
|
333
|
-
|
|
334
|
-
Args:
|
|
335
|
-
--weights (str | list[str], optional): Model path or Triton URL. Defaults to ROOT / 'yolov5s.pt'.
|
|
336
|
-
--source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'.
|
|
337
|
-
--data (str, optional): Dataset YAML path. Provides dataset configuration information.
|
|
338
|
-
--imgsz (list[int], optional): Inference size (height, width). Defaults to [640].
|
|
339
|
-
--conf-thres (float, optional): Confidence threshold. Defaults to 0.25.
|
|
340
|
-
--iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45.
|
|
341
|
-
--max-det (int, optional): Maximum number of detections per image. Defaults to 1000.
|
|
342
|
-
--device (str, optional): CUDA device, i.e., '0' or '0,1,2,3' or 'cpu'. Defaults to "".
|
|
343
|
-
--view-img (bool, optional): Flag to display results. Defaults to False.
|
|
344
|
-
--save-txt (bool, optional): Flag to save results to *.txt files. Defaults to False.
|
|
345
|
-
--save-csv (bool, optional): Flag to save results in CSV format. Defaults to False.
|
|
346
|
-
--save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Defaults to False.
|
|
347
|
-
--save-crop (bool, optional): Flag to save cropped prediction boxes. Defaults to False.
|
|
348
|
-
--nosave (bool, optional): Flag to prevent saving images/videos. Defaults to False.
|
|
349
|
-
--classes (list[int], optional): List of classes to filter results by, e.g., '--classes 0 2 3'. Defaults to None.
|
|
350
|
-
--agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
|
|
351
|
-
--augment (bool, optional): Flag for augmented inference. Defaults to False.
|
|
352
|
-
--visualize (bool, optional): Flag for visualizing features. Defaults to False.
|
|
353
|
-
--update (bool, optional): Flag to update all models in the model directory. Defaults to False.
|
|
354
|
-
--project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
|
|
355
|
-
--name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
|
|
356
|
-
--exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Defaults to False.
|
|
357
|
-
--line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Defaults to 3.
|
|
358
|
-
--hide-labels (bool, optional): Flag to hide labels in the output. Defaults to False.
|
|
359
|
-
--hide-conf (bool, optional): Flag to hide confidences in the output. Defaults to False.
|
|
360
|
-
--half (bool, optional): Flag to use FP16 half-precision inference. Defaults to False.
|
|
361
|
-
--dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Defaults to False.
|
|
362
|
-
--vid-stride (int, optional): Video frame-rate stride, determining the number of frames to skip in between
|
|
363
|
-
consecutive frames. Defaults to 1.
|
|
364
|
-
|
|
365
|
-
Returns:
|
|
366
|
-
argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object.
|
|
367
|
-
|
|
368
|
-
Example:
|
|
369
|
-
```python
|
|
370
|
-
from ultralytics import YOLOv5
|
|
371
|
-
args = YOLOv5.parse_opt()
|
|
372
|
-
```
|
|
373
|
-
"""
|
|
374
|
-
parser = argparse.ArgumentParser()
|
|
375
|
-
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
|
|
376
|
-
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
|
|
377
|
-
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
|
|
378
|
-
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
|
|
379
|
-
parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
|
|
380
|
-
parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
|
|
381
|
-
parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
|
|
382
|
-
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
|
383
|
-
parser.add_argument("--view-img", action="store_true", help="show results")
|
|
384
|
-
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
|
|
385
|
-
parser.add_argument(
|
|
386
|
-
"--save-format",
|
|
387
|
-
type=int,
|
|
388
|
-
default=0,
|
|
389
|
-
help="whether to save boxes coordinates in YOLO format or Pascal-VOC format when save-txt is True, 0 for YOLO and 1 for Pascal-VOC",
|
|
390
|
-
)
|
|
391
|
-
parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
|
|
392
|
-
parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
|
|
393
|
-
parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes")
|
|
394
|
-
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
|
|
395
|
-
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
|
|
396
|
-
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
|
|
397
|
-
parser.add_argument("--augment", action="store_true", help="augmented inference")
|
|
398
|
-
parser.add_argument("--visualize", action="store_true", help="visualize features")
|
|
399
|
-
parser.add_argument("--update", action="store_true", help="update all models")
|
|
400
|
-
parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
|
|
401
|
-
parser.add_argument("--name", default="exp", help="save results to project/name")
|
|
402
|
-
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
|
403
|
-
parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)")
|
|
404
|
-
parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels")
|
|
405
|
-
parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences")
|
|
406
|
-
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
|
407
|
-
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
|
408
|
-
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
|
|
409
|
-
opt = parser.parse_args()
|
|
410
|
-
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
|
411
|
-
print_args(vars(opt))
|
|
412
|
-
return opt
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
def main(opt):
|
|
416
|
-
"""
|
|
417
|
-
Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running.
|
|
418
|
-
|
|
419
|
-
Args:
|
|
420
|
-
opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. See function `parse_opt` for details.
|
|
421
|
-
|
|
422
|
-
Returns:
|
|
423
|
-
None
|
|
424
|
-
|
|
425
|
-
Note:
|
|
426
|
-
This function performs essential pre-execution checks and initiates the YOLOv5 detection process based on user-specified
|
|
427
|
-
options. Refer to the usage guide and examples for more information about different sources and formats at:
|
|
428
|
-
https://github.com/ultralytics/ultralytics
|
|
429
|
-
|
|
430
|
-
Example usage:
|
|
431
|
-
|
|
432
|
-
```python
|
|
433
|
-
if __name__ == "__main__":
|
|
434
|
-
opt = parse_opt()
|
|
435
|
-
main(opt)
|
|
436
|
-
```
|
|
437
|
-
"""
|
|
438
|
-
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
|
439
|
-
run(**vars(opt))
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
if __name__ == "__main__":
|
|
443
|
-
opt = parse_opt()
|
|
444
|
-
main(opt)
|