segment-everything 0.1.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.
- segment_everything/__init__.py +5 -0
- segment_everything/augmentation/albumentations_helper.py +0 -0
- segment_everything/detect_and_segment.py +131 -0
- segment_everything/napari_helper.py +15 -0
- segment_everything/prompt_generator.py +188 -0
- segment_everything/py.typed +5 -0
- segment_everything/stacked_label_dataset.py +113 -0
- segment_everything/stacked_labels.py +428 -0
- segment_everything/vendored/PromptGuidedDecoder/Prompt_guided_Mask_Decoder.pt +0 -0
- segment_everything/vendored/__init__.py +5 -0
- segment_everything/vendored/dice.py +158 -0
- segment_everything/vendored/efficientvit/__init__.py +0 -0
- segment_everything/vendored/efficientvit/apps/__init__.py +0 -0
- segment_everything/vendored/efficientvit/apps/data_provider/__init__.py +7 -0
- segment_everything/vendored/efficientvit/apps/data_provider/augment/__init__.py +6 -0
- segment_everything/vendored/efficientvit/apps/data_provider/augment/bbox.py +30 -0
- segment_everything/vendored/efficientvit/apps/data_provider/augment/color_aug.py +78 -0
- segment_everything/vendored/efficientvit/apps/data_provider/base.py +254 -0
- segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/__init__.py +6 -0
- segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/_data_loader.py +1538 -0
- segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/_data_worker.py +357 -0
- segment_everything/vendored/efficientvit/apps/data_provider/random_resolution/controller.py +100 -0
- segment_everything/vendored/efficientvit/apps/setup.py +150 -0
- segment_everything/vendored/efficientvit/apps/trainer/__init__.py +6 -0
- segment_everything/vendored/efficientvit/apps/trainer/base.py +318 -0
- segment_everything/vendored/efficientvit/apps/trainer/run_config.py +129 -0
- segment_everything/vendored/efficientvit/apps/utils/__init__.py +12 -0
- segment_everything/vendored/efficientvit/apps/utils/dist.py +32 -0
- segment_everything/vendored/efficientvit/apps/utils/ema.py +52 -0
- segment_everything/vendored/efficientvit/apps/utils/export.py +45 -0
- segment_everything/vendored/efficientvit/apps/utils/init.py +66 -0
- segment_everything/vendored/efficientvit/apps/utils/lr.py +52 -0
- segment_everything/vendored/efficientvit/apps/utils/metric.py +43 -0
- segment_everything/vendored/efficientvit/apps/utils/misc.py +101 -0
- segment_everything/vendored/efficientvit/apps/utils/opt.py +28 -0
- segment_everything/vendored/efficientvit/cls_model_zoo.py +79 -0
- segment_everything/vendored/efficientvit/clscore/__init__.py +0 -0
- segment_everything/vendored/efficientvit/clscore/data_provider/__init__.py +5 -0
- segment_everything/vendored/efficientvit/clscore/data_provider/imagenet.py +142 -0
- segment_everything/vendored/efficientvit/clscore/trainer/__init__.py +6 -0
- segment_everything/vendored/efficientvit/clscore/trainer/cls_run_config.py +18 -0
- segment_everything/vendored/efficientvit/clscore/trainer/cls_trainer.py +265 -0
- segment_everything/vendored/efficientvit/clscore/trainer/utils/__init__.py +7 -0
- segment_everything/vendored/efficientvit/clscore/trainer/utils/label_smooth.py +18 -0
- segment_everything/vendored/efficientvit/clscore/trainer/utils/metric.py +23 -0
- segment_everything/vendored/efficientvit/clscore/trainer/utils/mixup.py +67 -0
- segment_everything/vendored/efficientvit/models/__init__.py +0 -0
- segment_everything/vendored/efficientvit/models/efficientvit/__init__.py +8 -0
- segment_everything/vendored/efficientvit/models/efficientvit/backbone.py +380 -0
- segment_everything/vendored/efficientvit/models/efficientvit/cls.py +188 -0
- segment_everything/vendored/efficientvit/models/efficientvit/sam.py +181 -0
- segment_everything/vendored/efficientvit/models/efficientvit/seg.py +373 -0
- segment_everything/vendored/efficientvit/models/nn/__init__.py +8 -0
- segment_everything/vendored/efficientvit/models/nn/act.py +30 -0
- segment_everything/vendored/efficientvit/models/nn/drop.py +104 -0
- segment_everything/vendored/efficientvit/models/nn/norm.py +164 -0
- segment_everything/vendored/efficientvit/models/nn/ops.py +597 -0
- segment_everything/vendored/efficientvit/models/utils/__init__.py +7 -0
- segment_everything/vendored/efficientvit/models/utils/list.py +53 -0
- segment_everything/vendored/efficientvit/models/utils/network.py +73 -0
- segment_everything/vendored/efficientvit/models/utils/random.py +65 -0
- segment_everything/vendored/efficientvit/sam_model_zoo.py +45 -0
- segment_everything/vendored/efficientvit/seg_model_zoo.py +70 -0
- segment_everything/vendored/get_object_aware.py +26 -0
- segment_everything/vendored/mobilesamv2/__init__.py +16 -0
- segment_everything/vendored/mobilesamv2/automatic_mask_generator.py +415 -0
- segment_everything/vendored/mobilesamv2/build_sam.py +246 -0
- segment_everything/vendored/mobilesamv2/modeling/__init__.py +11 -0
- segment_everything/vendored/mobilesamv2/modeling/common.py +43 -0
- segment_everything/vendored/mobilesamv2/modeling/image_encoder.py +394 -0
- segment_everything/vendored/mobilesamv2/modeling/mask_decoder.py +213 -0
- segment_everything/vendored/mobilesamv2/modeling/prompt_encoder.py +217 -0
- segment_everything/vendored/mobilesamv2/modeling/sam.py +203 -0
- segment_everything/vendored/mobilesamv2/modeling/transformer.py +240 -0
- segment_everything/vendored/mobilesamv2/predictor.py +384 -0
- segment_everything/vendored/mobilesamv2/utils/__init__.py +5 -0
- segment_everything/vendored/mobilesamv2/utils/amg.py +347 -0
- segment_everything/vendored/mobilesamv2/utils/onnx.py +144 -0
- segment_everything/vendored/mobilesamv2/utils/transforms.py +103 -0
- segment_everything/vendored/object_detection/__init__.py +0 -0
- segment_everything/vendored/object_detection/ultralytics/__init__.py +5 -0
- segment_everything/vendored/object_detection/ultralytics/nn/__init__.py +9 -0
- segment_everything/vendored/object_detection/ultralytics/nn/autobackend.py +658 -0
- segment_everything/vendored/object_detection/ultralytics/nn/autoshape.py +397 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/__init__.py +110 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/block.py +304 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/conv.py +297 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/head.py +468 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/transformer.py +378 -0
- segment_everything/vendored/object_detection/ultralytics/nn/modules/utils.py +78 -0
- segment_everything/vendored/object_detection/ultralytics/nn/tasks.py +1049 -0
- segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/__init__.py +6 -0
- segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/model.py +104 -0
- segment_everything/vendored/object_detection/ultralytics/prompt_mobilesamv2/predict.py +95 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/__init__.py +5 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/cfg/__init__.py +588 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/cfg/default.yaml +117 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/__init__.py +9 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/annotator.py +53 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/augment.py +899 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/base.py +286 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/build.py +213 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/converter.py +358 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/dataloaders/__init__.py +0 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/dataloaders/stream_loaders.py +459 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/dataset.py +274 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/dataset_wrappers.py +53 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/download_weights.sh +18 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_coco.sh +60 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_coco128.sh +17 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/get_imagenet.sh +51 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/data/utils.py +716 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/engine/__init__.py +0 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/engine/exporter.py +1214 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/engine/model.py +641 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/engine/predictor.py +461 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/engine/results.py +741 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/__init__.py +893 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/autobatch.py +108 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/callbacks/__init__.py +5 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/callbacks/base.py +212 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/checks.py +547 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/dist.py +67 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/downloads.py +353 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/errors.py +12 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/files.py +100 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/instance.py +391 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/loss.py +579 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/metrics.py +1189 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/ops.py +870 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/patches.py +45 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/plotting.py +767 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/tal.py +276 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/torch_utils.py +684 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/utils/tuner.py +54 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/v8/__init__.py +5 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/v8/detect/__init__.py +5 -0
- segment_everything/vendored/object_detection/ultralytics/yolo/v8/detect/predict.py +69 -0
- segment_everything/vendored/tinyvit/__init__.py +2 -0
- segment_everything/vendored/tinyvit/tiny_vit.py +867 -0
- segment_everything/weights_helper.py +124 -0
- segment_everything-0.1.0.dist-info/METADATA +53 -0
- segment_everything-0.1.0.dist-info/RECORD +145 -0
- segment_everything-0.1.0.dist-info/WHEEL +4 -0
- segment_everything-0.1.0.dist-info/licenses/LICENSE +28 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
2
|
+
|
|
3
|
+
from itertools import repeat
|
|
4
|
+
from multiprocessing.pool import ThreadPool
|
|
5
|
+
from pathlib import Path
|
|
6
|
+
|
|
7
|
+
import cv2
|
|
8
|
+
import numpy as np
|
|
9
|
+
import torch
|
|
10
|
+
import torchvision
|
|
11
|
+
from tqdm import tqdm
|
|
12
|
+
|
|
13
|
+
from ..utils import LOCAL_RANK, NUM_THREADS, TQDM_BAR_FORMAT, is_dir_writeable
|
|
14
|
+
from .augment import Compose, Format, Instances, LetterBox, classify_albumentations, classify_transforms, v8_transforms
|
|
15
|
+
from .base import BaseDataset
|
|
16
|
+
from .utils import HELP_URL, LOGGER, get_hash, img2label_paths, verify_image_label
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class YOLODataset(BaseDataset):
|
|
20
|
+
"""
|
|
21
|
+
Dataset class for loading object detection and/or segmentation labels in YOLO format.
|
|
22
|
+
|
|
23
|
+
Args:
|
|
24
|
+
data (dict, optional): A dataset YAML dictionary. Defaults to None.
|
|
25
|
+
use_segments (bool, optional): If True, segmentation masks are used as labels. Defaults to False.
|
|
26
|
+
use_keypoints (bool, optional): If True, keypoints are used as labels. Defaults to False.
|
|
27
|
+
|
|
28
|
+
Returns:
|
|
29
|
+
(torch.utils.data.Dataset): A PyTorch dataset object that can be used for training an object detection model.
|
|
30
|
+
"""
|
|
31
|
+
cache_version = '1.0.2' # dataset labels *.cache version, >= 1.0.0 for YOLOv8
|
|
32
|
+
rand_interp_methods = [cv2.INTER_NEAREST, cv2.INTER_LINEAR, cv2.INTER_CUBIC, cv2.INTER_AREA, cv2.INTER_LANCZOS4]
|
|
33
|
+
|
|
34
|
+
def __init__(self, *args, data=None, use_segments=False, use_keypoints=False, **kwargs):
|
|
35
|
+
self.use_segments = use_segments
|
|
36
|
+
self.use_keypoints = use_keypoints
|
|
37
|
+
self.data = data
|
|
38
|
+
assert not (self.use_segments and self.use_keypoints), 'Can not use both segments and keypoints.'
|
|
39
|
+
super().__init__(*args, **kwargs)
|
|
40
|
+
|
|
41
|
+
def cache_labels(self, path=Path('./labels.cache')):
|
|
42
|
+
"""Cache dataset labels, check images and read shapes.
|
|
43
|
+
Args:
|
|
44
|
+
path (Path): path where to save the cache file (default: Path('./labels.cache')).
|
|
45
|
+
Returns:
|
|
46
|
+
(dict): labels.
|
|
47
|
+
"""
|
|
48
|
+
x = {'labels': []}
|
|
49
|
+
nm, nf, ne, nc, msgs = 0, 0, 0, 0, [] # number missing, found, empty, corrupt, messages
|
|
50
|
+
desc = f'{self.prefix}Scanning {path.parent / path.stem}...'
|
|
51
|
+
total = len(self.im_files)
|
|
52
|
+
nkpt, ndim = self.data.get('kpt_shape', (0, 0))
|
|
53
|
+
if self.use_keypoints and (nkpt <= 0 or ndim not in (2, 3)):
|
|
54
|
+
raise ValueError("'kpt_shape' in data.yaml missing or incorrect. Should be a list with [number of "
|
|
55
|
+
"keypoints, number of dims (2 for x,y or 3 for x,y,visible)], i.e. 'kpt_shape: [17, 3]'")
|
|
56
|
+
with ThreadPool(NUM_THREADS) as pool:
|
|
57
|
+
results = pool.imap(func=verify_image_label,
|
|
58
|
+
iterable=zip(self.im_files, self.label_files, repeat(self.prefix),
|
|
59
|
+
repeat(self.use_keypoints), repeat(len(self.data['names'])), repeat(nkpt),
|
|
60
|
+
repeat(ndim)))
|
|
61
|
+
pbar = tqdm(results, desc=desc, total=total, bar_format=TQDM_BAR_FORMAT)
|
|
62
|
+
for im_file, lb, shape, segments, keypoint, nm_f, nf_f, ne_f, nc_f, msg in pbar:
|
|
63
|
+
nm += nm_f
|
|
64
|
+
nf += nf_f
|
|
65
|
+
ne += ne_f
|
|
66
|
+
nc += nc_f
|
|
67
|
+
if im_file:
|
|
68
|
+
x['labels'].append(
|
|
69
|
+
dict(
|
|
70
|
+
im_file=im_file,
|
|
71
|
+
shape=shape,
|
|
72
|
+
cls=lb[:, 0:1], # n, 1
|
|
73
|
+
bboxes=lb[:, 1:], # n, 4
|
|
74
|
+
segments=segments,
|
|
75
|
+
keypoints=keypoint,
|
|
76
|
+
normalized=True,
|
|
77
|
+
bbox_format='xywh'))
|
|
78
|
+
if msg:
|
|
79
|
+
msgs.append(msg)
|
|
80
|
+
pbar.desc = f'{desc} {nf} images, {nm + ne} backgrounds, {nc} corrupt'
|
|
81
|
+
pbar.close()
|
|
82
|
+
|
|
83
|
+
if msgs:
|
|
84
|
+
LOGGER.info('\n'.join(msgs))
|
|
85
|
+
if nf == 0:
|
|
86
|
+
LOGGER.warning(f'{self.prefix}WARNING ⚠️ No labels found in {path}. {HELP_URL}')
|
|
87
|
+
x['hash'] = get_hash(self.label_files + self.im_files)
|
|
88
|
+
x['results'] = nf, nm, ne, nc, len(self.im_files)
|
|
89
|
+
x['msgs'] = msgs # warnings
|
|
90
|
+
x['version'] = self.cache_version # cache version
|
|
91
|
+
if is_dir_writeable(path.parent):
|
|
92
|
+
if path.exists():
|
|
93
|
+
path.unlink() # remove *.cache file if exists
|
|
94
|
+
np.save(str(path), x) # save cache for next time
|
|
95
|
+
path.with_suffix('.cache.npy').rename(path) # remove .npy suffix
|
|
96
|
+
LOGGER.info(f'{self.prefix}New cache created: {path}')
|
|
97
|
+
else:
|
|
98
|
+
LOGGER.warning(f'{self.prefix}WARNING ⚠️ Cache directory {path.parent} is not writeable, cache not saved.')
|
|
99
|
+
return x
|
|
100
|
+
|
|
101
|
+
def get_labels(self):
|
|
102
|
+
"""Returns dictionary of labels for YOLO training."""
|
|
103
|
+
self.label_files = img2label_paths(self.im_files)
|
|
104
|
+
cache_path = Path(self.label_files[0]).parent.with_suffix('.cache')
|
|
105
|
+
try:
|
|
106
|
+
import gc
|
|
107
|
+
gc.disable() # reduce pickle load time https://github.com/ultralytics/ultralytics/pull/1585
|
|
108
|
+
cache, exists = np.load(str(cache_path), allow_pickle=True).item(), True # load dict
|
|
109
|
+
gc.enable()
|
|
110
|
+
assert cache['version'] == self.cache_version # matches current version
|
|
111
|
+
assert cache['hash'] == get_hash(self.label_files + self.im_files) # identical hash
|
|
112
|
+
except (FileNotFoundError, AssertionError, AttributeError):
|
|
113
|
+
cache, exists = self.cache_labels(cache_path), False # run cache ops
|
|
114
|
+
|
|
115
|
+
# Display cache
|
|
116
|
+
nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupt, total
|
|
117
|
+
if exists and LOCAL_RANK in (-1, 0):
|
|
118
|
+
d = f'Scanning {cache_path}... {nf} images, {nm + ne} backgrounds, {nc} corrupt'
|
|
119
|
+
tqdm(None, desc=self.prefix + d, total=n, initial=n, bar_format=TQDM_BAR_FORMAT) # display cache results
|
|
120
|
+
if cache['msgs']:
|
|
121
|
+
LOGGER.info('\n'.join(cache['msgs'])) # display warnings
|
|
122
|
+
if nf == 0: # number of labels found
|
|
123
|
+
raise FileNotFoundError(f'{self.prefix}No labels found in {cache_path}, can not start training. {HELP_URL}')
|
|
124
|
+
|
|
125
|
+
# Read cache
|
|
126
|
+
[cache.pop(k) for k in ('hash', 'version', 'msgs')] # remove items
|
|
127
|
+
labels = cache['labels']
|
|
128
|
+
self.im_files = [lb['im_file'] for lb in labels] # update im_files
|
|
129
|
+
|
|
130
|
+
# Check if the dataset is all boxes or all segments
|
|
131
|
+
lengths = ((len(lb['cls']), len(lb['bboxes']), len(lb['segments'])) for lb in labels)
|
|
132
|
+
len_cls, len_boxes, len_segments = (sum(x) for x in zip(*lengths))
|
|
133
|
+
if len_segments and len_boxes != len_segments:
|
|
134
|
+
LOGGER.warning(
|
|
135
|
+
f'WARNING ⚠️ Box and segment counts should be equal, but got len(segments) = {len_segments}, '
|
|
136
|
+
f'len(boxes) = {len_boxes}. To resolve this only boxes will be used and all segments will be removed. '
|
|
137
|
+
'To avoid this please supply either a detect or segment dataset, not a detect-segment mixed dataset.')
|
|
138
|
+
for lb in labels:
|
|
139
|
+
lb['segments'] = []
|
|
140
|
+
if len_cls == 0:
|
|
141
|
+
raise ValueError(f'All labels empty in {cache_path}, can not start training without labels. {HELP_URL}')
|
|
142
|
+
return labels
|
|
143
|
+
|
|
144
|
+
# TODO: use hyp config to set all these augmentations
|
|
145
|
+
def build_transforms(self, hyp=None):
|
|
146
|
+
"""Builds and appends transforms to the list."""
|
|
147
|
+
if self.augment:
|
|
148
|
+
hyp.mosaic = hyp.mosaic if self.augment and not self.rect else 0.0
|
|
149
|
+
hyp.mixup = hyp.mixup if self.augment and not self.rect else 0.0
|
|
150
|
+
transforms = v8_transforms(self, self.imgsz, hyp)
|
|
151
|
+
else:
|
|
152
|
+
transforms = Compose([LetterBox(new_shape=(self.imgsz, self.imgsz), scaleup=False)])
|
|
153
|
+
transforms.append(
|
|
154
|
+
Format(bbox_format='xywh',
|
|
155
|
+
normalize=True,
|
|
156
|
+
return_mask=self.use_segments,
|
|
157
|
+
return_keypoint=self.use_keypoints,
|
|
158
|
+
batch_idx=True,
|
|
159
|
+
mask_ratio=hyp.mask_ratio,
|
|
160
|
+
mask_overlap=hyp.overlap_mask))
|
|
161
|
+
return transforms
|
|
162
|
+
|
|
163
|
+
def close_mosaic(self, hyp):
|
|
164
|
+
"""Sets mosaic, copy_paste and mixup options to 0.0 and builds transformations."""
|
|
165
|
+
hyp.mosaic = 0.0 # set mosaic ratio=0.0
|
|
166
|
+
hyp.copy_paste = 0.0 # keep the same behavior as previous v8 close-mosaic
|
|
167
|
+
hyp.mixup = 0.0 # keep the same behavior as previous v8 close-mosaic
|
|
168
|
+
self.transforms = self.build_transforms(hyp)
|
|
169
|
+
|
|
170
|
+
def update_labels_info(self, label):
|
|
171
|
+
"""custom your label format here."""
|
|
172
|
+
# NOTE: cls is not with bboxes now, classification and semantic segmentation need an independent cls label
|
|
173
|
+
# we can make it also support classification and semantic segmentation by add or remove some dict keys there.
|
|
174
|
+
bboxes = label.pop('bboxes')
|
|
175
|
+
segments = label.pop('segments')
|
|
176
|
+
keypoints = label.pop('keypoints', None)
|
|
177
|
+
bbox_format = label.pop('bbox_format')
|
|
178
|
+
normalized = label.pop('normalized')
|
|
179
|
+
label['instances'] = Instances(bboxes, segments, keypoints, bbox_format=bbox_format, normalized=normalized)
|
|
180
|
+
return label
|
|
181
|
+
|
|
182
|
+
@staticmethod
|
|
183
|
+
def collate_fn(batch):
|
|
184
|
+
"""Collates data samples into batches."""
|
|
185
|
+
new_batch = {}
|
|
186
|
+
keys = batch[0].keys()
|
|
187
|
+
values = list(zip(*[list(b.values()) for b in batch]))
|
|
188
|
+
for i, k in enumerate(keys):
|
|
189
|
+
value = values[i]
|
|
190
|
+
if k == 'img':
|
|
191
|
+
value = torch.stack(value, 0)
|
|
192
|
+
if k in ['masks', 'keypoints', 'bboxes', 'cls']:
|
|
193
|
+
value = torch.cat(value, 0)
|
|
194
|
+
new_batch[k] = value
|
|
195
|
+
new_batch['batch_idx'] = list(new_batch['batch_idx'])
|
|
196
|
+
for i in range(len(new_batch['batch_idx'])):
|
|
197
|
+
new_batch['batch_idx'][i] += i # add target image index for build_targets()
|
|
198
|
+
new_batch['batch_idx'] = torch.cat(new_batch['batch_idx'], 0)
|
|
199
|
+
return new_batch
|
|
200
|
+
|
|
201
|
+
|
|
202
|
+
# Classification dataloaders -------------------------------------------------------------------------------------------
|
|
203
|
+
class ClassificationDataset(torchvision.datasets.ImageFolder):
|
|
204
|
+
"""
|
|
205
|
+
YOLO Classification Dataset.
|
|
206
|
+
|
|
207
|
+
Args:
|
|
208
|
+
root (str): Dataset path.
|
|
209
|
+
|
|
210
|
+
Attributes:
|
|
211
|
+
cache_ram (bool): True if images should be cached in RAM, False otherwise.
|
|
212
|
+
cache_disk (bool): True if images should be cached on disk, False otherwise.
|
|
213
|
+
samples (list): List of samples containing file, index, npy, and im.
|
|
214
|
+
torch_transforms (callable): torchvision transforms applied to the dataset.
|
|
215
|
+
album_transforms (callable, optional): Albumentations transforms applied to the dataset if augment is True.
|
|
216
|
+
"""
|
|
217
|
+
|
|
218
|
+
def __init__(self, root, args, augment=False, cache=False):
|
|
219
|
+
"""
|
|
220
|
+
Initialize YOLO object with root, image size, augmentations, and cache settings.
|
|
221
|
+
|
|
222
|
+
Args:
|
|
223
|
+
root (str): Dataset path.
|
|
224
|
+
args (Namespace): Argument parser containing dataset related settings.
|
|
225
|
+
augment (bool, optional): True if dataset should be augmented, False otherwise. Defaults to False.
|
|
226
|
+
cache (bool | str | optional): Cache setting, can be True, False, 'ram' or 'disk'. Defaults to False.
|
|
227
|
+
"""
|
|
228
|
+
super().__init__(root=root)
|
|
229
|
+
if augment and args.fraction < 1.0: # reduce training fraction
|
|
230
|
+
self.samples = self.samples[:round(len(self.samples) * args.fraction)]
|
|
231
|
+
self.cache_ram = cache is True or cache == 'ram'
|
|
232
|
+
self.cache_disk = cache == 'disk'
|
|
233
|
+
self.samples = [list(x) + [Path(x[0]).with_suffix('.npy'), None] for x in self.samples] # file, index, npy, im
|
|
234
|
+
self.torch_transforms = classify_transforms(args.imgsz)
|
|
235
|
+
self.album_transforms = classify_albumentations(
|
|
236
|
+
augment=augment,
|
|
237
|
+
size=args.imgsz,
|
|
238
|
+
scale=(1.0 - args.scale, 1.0), # (0.08, 1.0)
|
|
239
|
+
hflip=args.fliplr,
|
|
240
|
+
vflip=args.flipud,
|
|
241
|
+
hsv_h=args.hsv_h, # HSV-Hue augmentation (fraction)
|
|
242
|
+
hsv_s=args.hsv_s, # HSV-Saturation augmentation (fraction)
|
|
243
|
+
hsv_v=args.hsv_v, # HSV-Value augmentation (fraction)
|
|
244
|
+
mean=(0.0, 0.0, 0.0), # IMAGENET_MEAN
|
|
245
|
+
std=(1.0, 1.0, 1.0), # IMAGENET_STD
|
|
246
|
+
auto_aug=False) if augment else None
|
|
247
|
+
|
|
248
|
+
def __getitem__(self, i):
|
|
249
|
+
"""Returns subset of data and targets corresponding to given indices."""
|
|
250
|
+
f, j, fn, im = self.samples[i] # filename, index, filename.with_suffix('.npy'), image
|
|
251
|
+
if self.cache_ram and im is None:
|
|
252
|
+
im = self.samples[i][3] = cv2.imread(f)
|
|
253
|
+
elif self.cache_disk:
|
|
254
|
+
if not fn.exists(): # load npy
|
|
255
|
+
np.save(fn.as_posix(), cv2.imread(f))
|
|
256
|
+
im = np.load(fn)
|
|
257
|
+
else: # read image
|
|
258
|
+
im = cv2.imread(f) # BGR
|
|
259
|
+
if self.album_transforms:
|
|
260
|
+
sample = self.album_transforms(image=cv2.cvtColor(im, cv2.COLOR_BGR2RGB))['image']
|
|
261
|
+
else:
|
|
262
|
+
sample = self.torch_transforms(im)
|
|
263
|
+
return {'img': sample, 'cls': j}
|
|
264
|
+
|
|
265
|
+
def __len__(self) -> int:
|
|
266
|
+
return len(self.samples)
|
|
267
|
+
|
|
268
|
+
|
|
269
|
+
# TODO: support semantic segmentation
|
|
270
|
+
class SemanticDataset(BaseDataset):
|
|
271
|
+
|
|
272
|
+
def __init__(self):
|
|
273
|
+
"""Initialize a SemanticDataset object."""
|
|
274
|
+
super().__init__()
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
2
|
+
|
|
3
|
+
import collections
|
|
4
|
+
from copy import deepcopy
|
|
5
|
+
|
|
6
|
+
from .augment import LetterBox
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class MixAndRectDataset:
|
|
10
|
+
"""
|
|
11
|
+
A dataset class that applies mosaic and mixup transformations as well as rectangular training.
|
|
12
|
+
|
|
13
|
+
Attributes:
|
|
14
|
+
dataset: The base dataset.
|
|
15
|
+
imgsz: The size of the images in the dataset.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(self, dataset):
|
|
19
|
+
"""
|
|
20
|
+
Args:
|
|
21
|
+
dataset (BaseDataset): The base dataset to apply transformations to.
|
|
22
|
+
"""
|
|
23
|
+
self.dataset = dataset
|
|
24
|
+
self.imgsz = dataset.imgsz
|
|
25
|
+
|
|
26
|
+
def __len__(self):
|
|
27
|
+
"""Returns the number of items in the dataset."""
|
|
28
|
+
return len(self.dataset)
|
|
29
|
+
|
|
30
|
+
def __getitem__(self, index):
|
|
31
|
+
"""
|
|
32
|
+
Applies mosaic, mixup and rectangular training transformations to an item in the dataset.
|
|
33
|
+
|
|
34
|
+
Args:
|
|
35
|
+
index (int): Index of the item in the dataset.
|
|
36
|
+
|
|
37
|
+
Returns:
|
|
38
|
+
(dict): A dictionary containing the transformed item data.
|
|
39
|
+
"""
|
|
40
|
+
labels = deepcopy(self.dataset[index])
|
|
41
|
+
for transform in self.dataset.transforms.tolist():
|
|
42
|
+
# Mosaic and mixup
|
|
43
|
+
if hasattr(transform, 'get_indexes'):
|
|
44
|
+
indexes = transform.get_indexes(self.dataset)
|
|
45
|
+
if not isinstance(indexes, collections.abc.Sequence):
|
|
46
|
+
indexes = [indexes]
|
|
47
|
+
labels['mix_labels'] = [deepcopy(self.dataset[index]) for index in indexes]
|
|
48
|
+
if self.dataset.rect and isinstance(transform, LetterBox):
|
|
49
|
+
transform.new_shape = self.dataset.batch_shapes[self.dataset.batch[index]]
|
|
50
|
+
labels = transform(labels)
|
|
51
|
+
if 'mix_labels' in labels:
|
|
52
|
+
labels.pop('mix_labels')
|
|
53
|
+
return labels
|
segment_everything/vendored/object_detection/ultralytics/yolo/data/scripts/download_weights.sh
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
3
|
+
# Download latest models from https://github.com/ultralytics/assets/releases
|
|
4
|
+
# Example usage: bash ultralytics/yolo/data/scripts/download_weights.sh
|
|
5
|
+
# parent
|
|
6
|
+
# └── weights
|
|
7
|
+
# ├── yolov8n.pt ← downloads here
|
|
8
|
+
# ├── yolov8s.pt
|
|
9
|
+
# └── ...
|
|
10
|
+
|
|
11
|
+
python - <<EOF
|
|
12
|
+
from ultralytics.yolo.utils.downloads import attempt_download_asset
|
|
13
|
+
|
|
14
|
+
assets = [f'yolov8{size}{suffix}.pt' for size in 'nsmlx' for suffix in ('', '-cls', '-seg')]
|
|
15
|
+
for x in assets:
|
|
16
|
+
attempt_download_asset(f'weights/{x}')
|
|
17
|
+
|
|
18
|
+
EOF
|
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
3
|
+
# Download COCO 2017 dataset http://cocodataset.org
|
|
4
|
+
# Example usage: bash data/scripts/get_coco.sh
|
|
5
|
+
# parent
|
|
6
|
+
# ├── ultralytics
|
|
7
|
+
# └── datasets
|
|
8
|
+
# └── coco ← downloads here
|
|
9
|
+
|
|
10
|
+
# Arguments (optional) Usage: bash data/scripts/get_coco.sh --train --val --test --segments
|
|
11
|
+
if [ "$#" -gt 0 ]; then
|
|
12
|
+
for opt in "$@"; do
|
|
13
|
+
case "${opt}" in
|
|
14
|
+
--train) train=true ;;
|
|
15
|
+
--val) val=true ;;
|
|
16
|
+
--test) test=true ;;
|
|
17
|
+
--segments) segments=true ;;
|
|
18
|
+
--sama) sama=true ;;
|
|
19
|
+
esac
|
|
20
|
+
done
|
|
21
|
+
else
|
|
22
|
+
train=true
|
|
23
|
+
val=true
|
|
24
|
+
test=false
|
|
25
|
+
segments=false
|
|
26
|
+
sama=false
|
|
27
|
+
fi
|
|
28
|
+
|
|
29
|
+
# Download/unzip labels
|
|
30
|
+
d='../datasets' # unzip directory
|
|
31
|
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
|
32
|
+
if [ "$segments" == "true" ]; then
|
|
33
|
+
f='coco2017labels-segments.zip' # 169 MB
|
|
34
|
+
elif [ "$sama" == "true" ]; then
|
|
35
|
+
f='coco2017labels-segments-sama.zip' # 199 MB https://www.sama.com/sama-coco-dataset/
|
|
36
|
+
else
|
|
37
|
+
f='coco2017labels.zip' # 46 MB
|
|
38
|
+
fi
|
|
39
|
+
echo 'Downloading' $url$f ' ...'
|
|
40
|
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
|
41
|
+
|
|
42
|
+
# Download/unzip images
|
|
43
|
+
d='../datasets/coco/images' # unzip directory
|
|
44
|
+
url=http://images.cocodataset.org/zips/
|
|
45
|
+
if [ "$train" == "true" ]; then
|
|
46
|
+
f='train2017.zip' # 19G, 118k images
|
|
47
|
+
echo 'Downloading' $url$f '...'
|
|
48
|
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
|
49
|
+
fi
|
|
50
|
+
if [ "$val" == "true" ]; then
|
|
51
|
+
f='val2017.zip' # 1G, 5k images
|
|
52
|
+
echo 'Downloading' $url$f '...'
|
|
53
|
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
|
54
|
+
fi
|
|
55
|
+
if [ "$test" == "true" ]; then
|
|
56
|
+
f='test2017.zip' # 7G, 41k images (optional)
|
|
57
|
+
echo 'Downloading' $url$f '...'
|
|
58
|
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
|
59
|
+
fi
|
|
60
|
+
wait # finish background tasks
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
3
|
+
# Download COCO128 dataset https://www.kaggle.com/ultralytics/coco128 (first 128 images from COCO train2017)
|
|
4
|
+
# Example usage: bash data/scripts/get_coco128.sh
|
|
5
|
+
# parent
|
|
6
|
+
# ├── ultralytics
|
|
7
|
+
# └── datasets
|
|
8
|
+
# └── coco128 ← downloads here
|
|
9
|
+
|
|
10
|
+
# Download/unzip images and labels
|
|
11
|
+
d='../datasets' # unzip directory
|
|
12
|
+
url=https://github.com/ultralytics/yolov5/releases/download/v1.0/
|
|
13
|
+
f='coco128.zip' # or 'coco128-segments.zip', 68 MB
|
|
14
|
+
echo 'Downloading' $url$f ' ...'
|
|
15
|
+
curl -L $url$f -o $f -# && unzip -q $f -d $d && rm $f &
|
|
16
|
+
|
|
17
|
+
wait # finish background tasks
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
#!/bin/bash
|
|
2
|
+
# Ultralytics YOLO 🚀, AGPL-3.0 license
|
|
3
|
+
# Download ILSVRC2012 ImageNet dataset https://image-net.org
|
|
4
|
+
# Example usage: bash data/scripts/get_imagenet.sh
|
|
5
|
+
# parent
|
|
6
|
+
# ├── ultralytics
|
|
7
|
+
# └── datasets
|
|
8
|
+
# └── imagenet ← downloads here
|
|
9
|
+
|
|
10
|
+
# Arguments (optional) Usage: bash data/scripts/get_imagenet.sh --train --val
|
|
11
|
+
if [ "$#" -gt 0 ]; then
|
|
12
|
+
for opt in "$@"; do
|
|
13
|
+
case "${opt}" in
|
|
14
|
+
--train) train=true ;;
|
|
15
|
+
--val) val=true ;;
|
|
16
|
+
esac
|
|
17
|
+
done
|
|
18
|
+
else
|
|
19
|
+
train=true
|
|
20
|
+
val=true
|
|
21
|
+
fi
|
|
22
|
+
|
|
23
|
+
# Make dir
|
|
24
|
+
d='../datasets/imagenet' # unzip directory
|
|
25
|
+
mkdir -p $d && cd $d
|
|
26
|
+
|
|
27
|
+
# Download/unzip train
|
|
28
|
+
if [ "$train" == "true" ]; then
|
|
29
|
+
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_train.tar # download 138G, 1281167 images
|
|
30
|
+
mkdir train && mv ILSVRC2012_img_train.tar train/ && cd train
|
|
31
|
+
tar -xf ILSVRC2012_img_train.tar && rm -f ILSVRC2012_img_train.tar
|
|
32
|
+
find . -name "*.tar" | while read NAME; do
|
|
33
|
+
mkdir -p "${NAME%.tar}"
|
|
34
|
+
tar -xf "${NAME}" -C "${NAME%.tar}"
|
|
35
|
+
rm -f "${NAME}"
|
|
36
|
+
done
|
|
37
|
+
cd ..
|
|
38
|
+
fi
|
|
39
|
+
|
|
40
|
+
# Download/unzip val
|
|
41
|
+
if [ "$val" == "true" ]; then
|
|
42
|
+
wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar # download 6.3G, 50000 images
|
|
43
|
+
mkdir val && mv ILSVRC2012_img_val.tar val/ && cd val && tar -xf ILSVRC2012_img_val.tar
|
|
44
|
+
wget -qO- https://raw.githubusercontent.com/soumith/imagenetloader.torch/master/valprep.sh | bash # move into subdirs
|
|
45
|
+
fi
|
|
46
|
+
|
|
47
|
+
# Delete corrupted image (optional: PNG under JPEG name that may cause dataloaders to fail)
|
|
48
|
+
# rm train/n04266014/n04266014_10835.JPEG
|
|
49
|
+
|
|
50
|
+
# TFRecords (optional)
|
|
51
|
+
# wget https://raw.githubusercontent.com/tensorflow/models/master/research/slim/datasets/imagenet_lsvrc_2015_synsets.txt
|