Upload 4 files
Browse files
best.pt
ADDED
@@ -0,0 +1,3 @@
|
|
|
|
|
|
|
|
|
1 |
+
version https://git-lfs.github.com/spec/v1
|
2 |
+
oid sha256:a2ed7f935848ec90e985a008cb63b90e82e30e1615d93720cf6bbebccd762cf4
|
3 |
+
size 14492776
|
data.yaml
ADDED
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
train: F:\yolov5\images\train
|
2 |
+
val: F:\yolov5\images\val
|
3 |
+
nc: 10 # Number of classes (change to the actual number of object classes)
|
4 |
+
names: ['Arbacia_lixula', 'Astropecten_spinulosus', 'Callistoctopus_macropus','Diadema_setosum','Echinaster_sepositus','Loligo_vulgaris','Octopus_vulgaris','Sphyraena_sphyraena','Seranus_scribba','Pterois_miles']
|
5 |
+
|
6 |
+
|
detect.py
ADDED
@@ -0,0 +1,438 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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.25, # 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 |
+
"""
|
103 |
+
Runs YOLOv5 detection inference on various sources like images, videos, directories, streams, etc.
|
104 |
+
|
105 |
+
Args:
|
106 |
+
weights (str | Path): Path to the model weights file or a Triton URL. Default is 'yolov5s.pt'.
|
107 |
+
source (str | Path): Input source, which can be a file, directory, URL, glob pattern, screen capture, or webcam
|
108 |
+
index. Default is 'data/images'.
|
109 |
+
data (str | Path): Path to the dataset YAML file. Default is 'data/coco128.yaml'.
|
110 |
+
imgsz (tuple[int, int]): Inference image size as a tuple (height, width). Default is (640, 640).
|
111 |
+
conf_thres (float): Confidence threshold for detections. Default is 0.25.
|
112 |
+
iou_thres (float): Intersection Over Union (IOU) threshold for non-max suppression. Default is 0.45.
|
113 |
+
max_det (int): Maximum number of detections per image. Default is 1000.
|
114 |
+
device (str): CUDA device identifier (e.g., '0' or '0,1,2,3') or 'cpu'. Default is an empty string, which uses the
|
115 |
+
best available device.
|
116 |
+
view_img (bool): If True, display inference results using OpenCV. Default is False.
|
117 |
+
save_txt (bool): If True, save results in a text file. Default is False.
|
118 |
+
save_csv (bool): If True, save results in a CSV file. Default is False.
|
119 |
+
save_conf (bool): If True, include confidence scores in the saved results. Default is False.
|
120 |
+
save_crop (bool): If True, save cropped prediction boxes. Default is False.
|
121 |
+
nosave (bool): If True, do not save inference images or videos. Default is False.
|
122 |
+
classes (list[int]): List of class indices to filter detections by. Default is None.
|
123 |
+
agnostic_nms (bool): If True, perform class-agnostic non-max suppression. Default is False.
|
124 |
+
augment (bool): If True, use augmented inference. Default is False.
|
125 |
+
visualize (bool): If True, visualize feature maps. Default is False.
|
126 |
+
update (bool): If True, update all models' weights. Default is False.
|
127 |
+
project (str | Path): Directory to save results. Default is 'runs/detect'.
|
128 |
+
name (str): Name of the current experiment; used to create a subdirectory within 'project'. Default is 'exp'.
|
129 |
+
exist_ok (bool): If True, existing directories with the same name are reused instead of being incremented. Default is
|
130 |
+
False.
|
131 |
+
line_thickness (int): Thickness of bounding box lines in pixels. Default is 3.
|
132 |
+
hide_labels (bool): If True, do not display labels on bounding boxes. Default is False.
|
133 |
+
hide_conf (bool): If True, do not display confidence scores on bounding boxes. Default is False.
|
134 |
+
half (bool): If True, use FP16 half-precision inference. Default is False.
|
135 |
+
dnn (bool): If True, use OpenCV DNN backend for ONNX inference. Default is False.
|
136 |
+
vid_stride (int): Stride for processing video frames, to skip frames between processing. Default is 1.
|
137 |
+
|
138 |
+
Returns:
|
139 |
+
None
|
140 |
+
|
141 |
+
Examples:
|
142 |
+
```python
|
143 |
+
from ultralytics import run
|
144 |
+
|
145 |
+
# Run inference on an image
|
146 |
+
run(source='data/images/example.jpg', weights='yolov5s.pt', device='0')
|
147 |
+
|
148 |
+
# Run inference on a video with specific confidence threshold
|
149 |
+
run(source='data/videos/example.mp4', weights='yolov5s.pt', conf_thres=0.4, device='0')
|
150 |
+
```
|
151 |
+
"""
|
152 |
+
source = str(source)
|
153 |
+
save_img = not nosave and not source.endswith(".txt") # save inference images
|
154 |
+
is_file = Path(source).suffix[1:] in (IMG_FORMATS + VID_FORMATS)
|
155 |
+
is_url = source.lower().startswith(("rtsp://", "rtmp://", "http://", "https://"))
|
156 |
+
webcam = source.isnumeric() or source.endswith(".streams") or (is_url and not is_file)
|
157 |
+
screenshot = source.lower().startswith("screen")
|
158 |
+
if is_url and is_file:
|
159 |
+
source = check_file(source) # download
|
160 |
+
|
161 |
+
# Directories
|
162 |
+
save_dir = increment_path(Path(project) / name, exist_ok=exist_ok) # increment run
|
163 |
+
(save_dir / "labels" if save_txt else save_dir).mkdir(parents=True, exist_ok=True) # make dir
|
164 |
+
|
165 |
+
# Load model
|
166 |
+
device = select_device(device)
|
167 |
+
model = DetectMultiBackend(weights, device=device, dnn=dnn, data=data, fp16=half)
|
168 |
+
stride, names, pt = model.stride, model.names, model.pt
|
169 |
+
imgsz = check_img_size(imgsz, s=stride) # check image size
|
170 |
+
|
171 |
+
# Dataloader
|
172 |
+
bs = 1 # batch_size
|
173 |
+
if webcam:
|
174 |
+
view_img = check_imshow(warn=True)
|
175 |
+
dataset = LoadStreams(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
176 |
+
bs = len(dataset)
|
177 |
+
elif screenshot:
|
178 |
+
dataset = LoadScreenshots(source, img_size=imgsz, stride=stride, auto=pt)
|
179 |
+
else:
|
180 |
+
dataset = LoadImages(source, img_size=imgsz, stride=stride, auto=pt, vid_stride=vid_stride)
|
181 |
+
vid_path, vid_writer = [None] * bs, [None] * bs
|
182 |
+
|
183 |
+
# Run inference
|
184 |
+
model.warmup(imgsz=(1 if pt or model.triton else bs, 3, *imgsz)) # warmup
|
185 |
+
seen, windows, dt = 0, [], (Profile(device=device), Profile(device=device), Profile(device=device))
|
186 |
+
for path, im, im0s, vid_cap, s in dataset:
|
187 |
+
with dt[0]:
|
188 |
+
im = torch.from_numpy(im).to(model.device)
|
189 |
+
im = im.half() if model.fp16 else im.float() # uint8 to fp16/32
|
190 |
+
im /= 255 # 0 - 255 to 0.0 - 1.0
|
191 |
+
if len(im.shape) == 3:
|
192 |
+
im = im[None] # expand for batch dim
|
193 |
+
if model.xml and im.shape[0] > 1:
|
194 |
+
ims = torch.chunk(im, im.shape[0], 0)
|
195 |
+
|
196 |
+
# Inference
|
197 |
+
with dt[1]:
|
198 |
+
visualize = increment_path(save_dir / Path(path).stem, mkdir=True) if visualize else False
|
199 |
+
if model.xml and im.shape[0] > 1:
|
200 |
+
pred = None
|
201 |
+
for image in ims:
|
202 |
+
if pred is None:
|
203 |
+
pred = model(image, augment=augment, visualize=visualize).unsqueeze(0)
|
204 |
+
else:
|
205 |
+
pred = torch.cat((pred, model(image, augment=augment, visualize=visualize).unsqueeze(0)), dim=0)
|
206 |
+
pred = [pred, None]
|
207 |
+
else:
|
208 |
+
pred = model(im, augment=augment, visualize=visualize)
|
209 |
+
# NMS
|
210 |
+
with dt[2]:
|
211 |
+
pred = non_max_suppression(pred, conf_thres, iou_thres, classes, agnostic_nms, max_det=max_det)
|
212 |
+
|
213 |
+
# Second-stage classifier (optional)
|
214 |
+
# pred = utils.general.apply_classifier(pred, classifier_model, im, im0s)
|
215 |
+
|
216 |
+
# Define the path for the CSV file
|
217 |
+
csv_path = save_dir / "predictions.csv"
|
218 |
+
|
219 |
+
# Create or append to the CSV file
|
220 |
+
def write_to_csv(image_name, prediction, confidence):
|
221 |
+
"""Writes prediction data for an image to a CSV file, appending if the file exists."""
|
222 |
+
data = {"Image Name": image_name, "Prediction": prediction, "Confidence": confidence}
|
223 |
+
with open(csv_path, mode="a", newline="") as f:
|
224 |
+
writer = csv.DictWriter(f, fieldnames=data.keys())
|
225 |
+
if not csv_path.is_file():
|
226 |
+
writer.writeheader()
|
227 |
+
writer.writerow(data)
|
228 |
+
|
229 |
+
# Process predictions
|
230 |
+
for i, det in enumerate(pred): # per image
|
231 |
+
seen += 1
|
232 |
+
if webcam: # batch_size >= 1
|
233 |
+
p, im0, frame = path[i], im0s[i].copy(), dataset.count
|
234 |
+
s += f"{i}: "
|
235 |
+
else:
|
236 |
+
p, im0, frame = path, im0s.copy(), getattr(dataset, "frame", 0)
|
237 |
+
|
238 |
+
p = Path(p) # to Path
|
239 |
+
save_path = str(save_dir / p.name) # im.jpg
|
240 |
+
txt_path = str(save_dir / "labels" / p.stem) + ("" if dataset.mode == "image" else f"_{frame}") # im.txt
|
241 |
+
s += "{:g}x{:g} ".format(*im.shape[2:]) # print string
|
242 |
+
gn = torch.tensor(im0.shape)[[1, 0, 1, 0]] # normalization gain whwh
|
243 |
+
imc = im0.copy() if save_crop else im0 # for save_crop
|
244 |
+
annotator = Annotator(im0, line_width=line_thickness, example=str(names))
|
245 |
+
if len(det):
|
246 |
+
# Rescale boxes from img_size to im0 size
|
247 |
+
det[:, :4] = scale_boxes(im.shape[2:], det[:, :4], im0.shape).round()
|
248 |
+
|
249 |
+
# Print results
|
250 |
+
for c in det[:, 5].unique():
|
251 |
+
n = (det[:, 5] == c).sum() # detections per class
|
252 |
+
s += f"{n} {names[int(c)]}{'s' * (n > 1)}, " # add to string
|
253 |
+
|
254 |
+
# Write results
|
255 |
+
for *xyxy, conf, cls in reversed(det):
|
256 |
+
c = int(cls) # integer class
|
257 |
+
label = names[c] if hide_conf else f"{names[c]}"
|
258 |
+
confidence = float(conf)
|
259 |
+
confidence_str = f"{confidence:.2f}"
|
260 |
+
|
261 |
+
if save_csv:
|
262 |
+
write_to_csv(p.name, label, confidence_str)
|
263 |
+
|
264 |
+
if save_txt: # Write to file
|
265 |
+
if save_format == 0:
|
266 |
+
coords = (
|
267 |
+
(xyxy2xywh(torch.tensor(xyxy).view(1, 4)) / gn).view(-1).tolist()
|
268 |
+
) # normalized xywh
|
269 |
+
else:
|
270 |
+
coords = (torch.tensor(xyxy).view(1, 4) / gn).view(-1).tolist() # xyxy
|
271 |
+
line = (cls, *coords, conf) if save_conf else (cls, *coords) # label format
|
272 |
+
with open(f"{txt_path}.txt", "a") as f:
|
273 |
+
f.write(("%g " * len(line)).rstrip() % line + "\n")
|
274 |
+
|
275 |
+
if save_img or save_crop or view_img: # Add bbox to image
|
276 |
+
c = int(cls) # integer class
|
277 |
+
label = None if hide_labels else (names[c] if hide_conf else f"{names[c]} {conf:.2f}")
|
278 |
+
annotator.box_label(xyxy, label, color=colors(c, True))
|
279 |
+
if save_crop:
|
280 |
+
save_one_box(xyxy, imc, file=save_dir / "crops" / names[c] / f"{p.stem}.jpg", BGR=True)
|
281 |
+
|
282 |
+
# Stream results
|
283 |
+
im0 = annotator.result()
|
284 |
+
if view_img:
|
285 |
+
if platform.system() == "Linux" and p not in windows:
|
286 |
+
windows.append(p)
|
287 |
+
cv2.namedWindow(str(p), cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO) # allow window resize (Linux)
|
288 |
+
cv2.resizeWindow(str(p), im0.shape[1], im0.shape[0])
|
289 |
+
cv2.imshow(str(p), im0)
|
290 |
+
cv2.waitKey(1) # 1 millisecond
|
291 |
+
|
292 |
+
# Save results (image with detections)
|
293 |
+
if save_img:
|
294 |
+
if dataset.mode == "image":
|
295 |
+
cv2.imwrite(save_path, im0)
|
296 |
+
else: # 'video' or 'stream'
|
297 |
+
if vid_path[i] != save_path: # new video
|
298 |
+
vid_path[i] = save_path
|
299 |
+
if isinstance(vid_writer[i], cv2.VideoWriter):
|
300 |
+
vid_writer[i].release() # release previous video writer
|
301 |
+
if vid_cap: # video
|
302 |
+
fps = vid_cap.get(cv2.CAP_PROP_FPS)
|
303 |
+
w = int(vid_cap.get(cv2.CAP_PROP_FRAME_WIDTH))
|
304 |
+
h = int(vid_cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
|
305 |
+
else: # stream
|
306 |
+
fps, w, h = 30, im0.shape[1], im0.shape[0]
|
307 |
+
save_path = str(Path(save_path).with_suffix(".mp4")) # force *.mp4 suffix on results videos
|
308 |
+
vid_writer[i] = cv2.VideoWriter(save_path, cv2.VideoWriter_fourcc(*"mp4v"), fps, (w, h))
|
309 |
+
vid_writer[i].write(im0)
|
310 |
+
|
311 |
+
# Print time (inference-only)
|
312 |
+
LOGGER.info(f"{s}{'' if len(det) else '(no detections), '}{dt[1].dt * 1E3:.1f}ms")
|
313 |
+
|
314 |
+
# Print results
|
315 |
+
t = tuple(x.t / seen * 1e3 for x in dt) # speeds per image
|
316 |
+
LOGGER.info(f"Speed: %.1fms pre-process, %.1fms inference, %.1fms NMS per image at shape {(1, 3, *imgsz)}" % t)
|
317 |
+
if save_txt or save_img:
|
318 |
+
s = f"\n{len(list(save_dir.glob('labels/*.txt')))} labels saved to {save_dir / 'labels'}" if save_txt else ""
|
319 |
+
LOGGER.info(f"Results saved to {colorstr('bold', save_dir)}{s}")
|
320 |
+
if update:
|
321 |
+
strip_optimizer(weights[0]) # update model (to fix SourceChangeWarning)
|
322 |
+
|
323 |
+
|
324 |
+
def parse_opt():
|
325 |
+
"""
|
326 |
+
Parse command-line arguments for YOLOv5 detection, allowing custom inference options and model configurations.
|
327 |
+
|
328 |
+
Args:
|
329 |
+
--weights (str | list[str], optional): Model path or Triton URL. Defaults to ROOT / 'yolov5s.pt'.
|
330 |
+
--source (str, optional): File/dir/URL/glob/screen/0(webcam). Defaults to ROOT / 'data/images'.
|
331 |
+
--data (str, optional): Dataset YAML path. Provides dataset configuration information.
|
332 |
+
--imgsz (list[int], optional): Inference size (height, width). Defaults to [640].
|
333 |
+
--conf-thres (float, optional): Confidence threshold. Defaults to 0.25.
|
334 |
+
--iou-thres (float, optional): NMS IoU threshold. Defaults to 0.45.
|
335 |
+
--max-det (int, optional): Maximum number of detections per image. Defaults to 1000.
|
336 |
+
--device (str, optional): CUDA device, i.e., '0' or '0,1,2,3' or 'cpu'. Defaults to "".
|
337 |
+
--view-img (bool, optional): Flag to display results. Defaults to False.
|
338 |
+
--save-txt (bool, optional): Flag to save results to *.txt files. Defaults to False.
|
339 |
+
--save-csv (bool, optional): Flag to save results in CSV format. Defaults to False.
|
340 |
+
--save-conf (bool, optional): Flag to save confidences in labels saved via --save-txt. Defaults to False.
|
341 |
+
--save-crop (bool, optional): Flag to save cropped prediction boxes. Defaults to False.
|
342 |
+
--nosave (bool, optional): Flag to prevent saving images/videos. Defaults to False.
|
343 |
+
--classes (list[int], optional): List of classes to filter results by, e.g., '--classes 0 2 3'. Defaults to None.
|
344 |
+
--agnostic-nms (bool, optional): Flag for class-agnostic NMS. Defaults to False.
|
345 |
+
--augment (bool, optional): Flag for augmented inference. Defaults to False.
|
346 |
+
--visualize (bool, optional): Flag for visualizing features. Defaults to False.
|
347 |
+
--update (bool, optional): Flag to update all models in the model directory. Defaults to False.
|
348 |
+
--project (str, optional): Directory to save results. Defaults to ROOT / 'runs/detect'.
|
349 |
+
--name (str, optional): Sub-directory name for saving results within --project. Defaults to 'exp'.
|
350 |
+
--exist-ok (bool, optional): Flag to allow overwriting if the project/name already exists. Defaults to False.
|
351 |
+
--line-thickness (int, optional): Thickness (in pixels) of bounding boxes. Defaults to 3.
|
352 |
+
--hide-labels (bool, optional): Flag to hide labels in the output. Defaults to False.
|
353 |
+
--hide-conf (bool, optional): Flag to hide confidences in the output. Defaults to False.
|
354 |
+
--half (bool, optional): Flag to use FP16 half-precision inference. Defaults to False.
|
355 |
+
--dnn (bool, optional): Flag to use OpenCV DNN for ONNX inference. Defaults to False.
|
356 |
+
--vid-stride (int, optional): Video frame-rate stride, determining the number of frames to skip in between
|
357 |
+
consecutive frames. Defaults to 1.
|
358 |
+
|
359 |
+
Returns:
|
360 |
+
argparse.Namespace: Parsed command-line arguments as an argparse.Namespace object.
|
361 |
+
|
362 |
+
Example:
|
363 |
+
```python
|
364 |
+
from ultralytics import YOLOv5
|
365 |
+
args = YOLOv5.parse_opt()
|
366 |
+
```
|
367 |
+
"""
|
368 |
+
parser = argparse.ArgumentParser()
|
369 |
+
parser.add_argument("--weights", nargs="+", type=str, default=ROOT / "yolov5s.pt", help="model path or triton URL")
|
370 |
+
parser.add_argument("--source", type=str, default=ROOT / "data/images", help="file/dir/URL/glob/screen/0(webcam)")
|
371 |
+
parser.add_argument("--data", type=str, default=ROOT / "data/coco128.yaml", help="(optional) dataset.yaml path")
|
372 |
+
parser.add_argument("--imgsz", "--img", "--img-size", nargs="+", type=int, default=[640], help="inference size h,w")
|
373 |
+
parser.add_argument("--conf-thres", type=float, default=0.25, help="confidence threshold")
|
374 |
+
parser.add_argument("--iou-thres", type=float, default=0.45, help="NMS IoU threshold")
|
375 |
+
parser.add_argument("--max-det", type=int, default=1000, help="maximum detections per image")
|
376 |
+
parser.add_argument("--device", default="", help="cuda device, i.e. 0 or 0,1,2,3 or cpu")
|
377 |
+
parser.add_argument("--view-img", action="store_true", help="show results")
|
378 |
+
parser.add_argument("--save-txt", action="store_true", help="save results to *.txt")
|
379 |
+
parser.add_argument(
|
380 |
+
"--save-format",
|
381 |
+
type=int,
|
382 |
+
default=0,
|
383 |
+
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",
|
384 |
+
)
|
385 |
+
parser.add_argument("--save-csv", action="store_true", help="save results in CSV format")
|
386 |
+
parser.add_argument("--save-conf", action="store_true", help="save confidences in --save-txt labels")
|
387 |
+
parser.add_argument("--save-crop", action="store_true", help="save cropped prediction boxes")
|
388 |
+
parser.add_argument("--nosave", action="store_true", help="do not save images/videos")
|
389 |
+
parser.add_argument("--classes", nargs="+", type=int, help="filter by class: --classes 0, or --classes 0 2 3")
|
390 |
+
parser.add_argument("--agnostic-nms", action="store_true", help="class-agnostic NMS")
|
391 |
+
parser.add_argument("--augment", action="store_true", help="augmented inference")
|
392 |
+
parser.add_argument("--visualize", action="store_true", help="visualize features")
|
393 |
+
parser.add_argument("--update", action="store_true", help="update all models")
|
394 |
+
parser.add_argument("--project", default=ROOT / "runs/detect", help="save results to project/name")
|
395 |
+
parser.add_argument("--name", default="exp", help="save results to project/name")
|
396 |
+
parser.add_argument("--exist-ok", action="store_true", help="existing project/name ok, do not increment")
|
397 |
+
parser.add_argument("--line-thickness", default=3, type=int, help="bounding box thickness (pixels)")
|
398 |
+
parser.add_argument("--hide-labels", default=False, action="store_true", help="hide labels")
|
399 |
+
parser.add_argument("--hide-conf", default=False, action="store_true", help="hide confidences")
|
400 |
+
parser.add_argument("--half", action="store_true", help="use FP16 half-precision inference")
|
401 |
+
parser.add_argument("--dnn", action="store_true", help="use OpenCV DNN for ONNX inference")
|
402 |
+
parser.add_argument("--vid-stride", type=int, default=1, help="video frame-rate stride")
|
403 |
+
opt = parser.parse_args()
|
404 |
+
opt.imgsz *= 2 if len(opt.imgsz) == 1 else 1 # expand
|
405 |
+
print_args(vars(opt))
|
406 |
+
return opt
|
407 |
+
|
408 |
+
|
409 |
+
def main(opt):
|
410 |
+
"""
|
411 |
+
Executes YOLOv5 model inference based on provided command-line arguments, validating dependencies before running.
|
412 |
+
|
413 |
+
Args:
|
414 |
+
opt (argparse.Namespace): Command-line arguments for YOLOv5 detection. See function `parse_opt` for details.
|
415 |
+
|
416 |
+
Returns:
|
417 |
+
None
|
418 |
+
|
419 |
+
Note:
|
420 |
+
This function performs essential pre-execution checks and initiates the YOLOv5 detection process based on user-specified
|
421 |
+
options. Refer to the usage guide and examples for more information about different sources and formats at:
|
422 |
+
https://github.com/ultralytics/ultralytics
|
423 |
+
|
424 |
+
Example usage:
|
425 |
+
|
426 |
+
```python
|
427 |
+
if __name__ == "__main__":
|
428 |
+
opt = parse_opt()
|
429 |
+
main(opt)
|
430 |
+
```
|
431 |
+
"""
|
432 |
+
check_requirements(ROOT / "requirements.txt", exclude=("tensorboard", "thop"))
|
433 |
+
run(**vars(opt))
|
434 |
+
|
435 |
+
|
436 |
+
if __name__ == "__main__":
|
437 |
+
opt = parse_opt()
|
438 |
+
main(opt)
|
requirements.txt
ADDED
@@ -0,0 +1,49 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
# YOLOv5 requirements
|
2 |
+
# Usage: pip install -r requirements.txt
|
3 |
+
|
4 |
+
# Base ------------------------------------------------------------------------
|
5 |
+
gitpython>=3.1.30
|
6 |
+
matplotlib>=3.3
|
7 |
+
numpy>=1.23.5
|
8 |
+
opencv-python>=4.1.1
|
9 |
+
pillow>=10.3.0
|
10 |
+
psutil # system resources
|
11 |
+
PyYAML>=5.3.1
|
12 |
+
requests>=2.32.2
|
13 |
+
scipy>=1.4.1
|
14 |
+
thop>=0.1.1 # FLOPs computation
|
15 |
+
torch>=1.8.0 # see https://pytorch.org/get-started/locally (recommended)
|
16 |
+
torchvision>=0.9.0
|
17 |
+
tqdm>=4.66.3
|
18 |
+
ultralytics>=8.2.34 # https://ultralytics.com
|
19 |
+
# protobuf<=3.20.1 # https://github.com/ultralytics/yolov5/issues/8012
|
20 |
+
|
21 |
+
# Logging ---------------------------------------------------------------------
|
22 |
+
# tensorboard>=2.4.1
|
23 |
+
# clearml>=1.2.0
|
24 |
+
# comet
|
25 |
+
|
26 |
+
# Plotting --------------------------------------------------------------------
|
27 |
+
pandas>=1.1.4
|
28 |
+
seaborn>=0.11.0
|
29 |
+
|
30 |
+
# Export ----------------------------------------------------------------------
|
31 |
+
# coremltools>=6.0 # CoreML export
|
32 |
+
# onnx>=1.10.0 # ONNX export
|
33 |
+
# onnx-simplifier>=0.4.1 # ONNX simplifier
|
34 |
+
# nvidia-pyindex # TensorRT export
|
35 |
+
# nvidia-tensorrt # TensorRT export
|
36 |
+
# scikit-learn<=1.1.2 # CoreML quantization
|
37 |
+
# tensorflow>=2.4.0,<=2.13.1 # TF exports (-cpu, -aarch64, -macos)
|
38 |
+
# tensorflowjs>=3.9.0 # TF.js export
|
39 |
+
# openvino-dev>=2023.0 # OpenVINO export
|
40 |
+
|
41 |
+
# Deploy ----------------------------------------------------------------------
|
42 |
+
setuptools>=70.0.0 # Snyk vulnerability fix
|
43 |
+
# tritonclient[all]~=2.24.0
|
44 |
+
|
45 |
+
# Extras ----------------------------------------------------------------------
|
46 |
+
# ipython # interactive notebook
|
47 |
+
# mss # screenshots
|
48 |
+
# albumentations>=1.0.3
|
49 |
+
# pycocotools>=2.0.6 # COCO mAP
|