ultralytics 8.2.68__py3-none-any.whl → 8.2.70__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 ultralytics might be problematic. Click here for more details.

Files changed (37) hide show
  1. tests/test_cli.py +4 -16
  2. ultralytics/__init__.py +3 -2
  3. ultralytics/cfg/__init__.py +4 -0
  4. ultralytics/data/augment.py +1 -1
  5. ultralytics/hub/google/__init__.py +3 -3
  6. ultralytics/models/__init__.py +2 -1
  7. ultralytics/models/fastsam/__init__.py +1 -2
  8. ultralytics/models/fastsam/model.py +18 -0
  9. ultralytics/models/fastsam/predict.py +116 -1
  10. ultralytics/models/sam/build.py +2 -2
  11. ultralytics/models/sam/model.py +10 -2
  12. ultralytics/models/sam/modules/decoders.py +1 -42
  13. ultralytics/models/sam/modules/encoders.py +3 -1
  14. ultralytics/models/sam/modules/sam.py +5 -7
  15. ultralytics/models/sam/modules/transformer.py +4 -3
  16. ultralytics/models/sam/predict.py +12 -6
  17. ultralytics/models/sam2/__init__.py +6 -0
  18. ultralytics/models/sam2/build.py +156 -0
  19. ultralytics/models/sam2/model.py +97 -0
  20. ultralytics/models/sam2/modules/__init__.py +1 -0
  21. ultralytics/models/sam2/modules/decoders.py +305 -0
  22. ultralytics/models/sam2/modules/encoders.py +332 -0
  23. ultralytics/models/sam2/modules/memory_attention.py +170 -0
  24. ultralytics/models/sam2/modules/sam2.py +804 -0
  25. ultralytics/models/sam2/modules/sam2_blocks.py +715 -0
  26. ultralytics/models/sam2/modules/utils.py +191 -0
  27. ultralytics/models/sam2/predict.py +182 -0
  28. ultralytics/nn/modules/transformer.py +5 -3
  29. ultralytics/utils/ops.py +1 -1
  30. ultralytics/utils/torch_utils.py +9 -6
  31. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/METADATA +1 -1
  32. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/RECORD +36 -26
  33. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/WHEEL +1 -1
  34. ultralytics/models/fastsam/prompt.py +0 -352
  35. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/LICENSE +0 -0
  36. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/entry_points.txt +0 -0
  37. {ultralytics-8.2.68.dist-info → ultralytics-8.2.70.dist-info}/top_level.txt +0 -0
@@ -1,352 +0,0 @@
1
- # Ultralytics YOLO 🚀, AGPL-3.0 license
2
-
3
- import os
4
- from pathlib import Path
5
-
6
- import cv2
7
- import numpy as np
8
- import torch
9
- from PIL import Image
10
- from torch import Tensor
11
-
12
- from ultralytics.utils import TQDM, checks
13
-
14
-
15
- class FastSAMPrompt:
16
- """
17
- Fast Segment Anything Model class for image annotation and visualization.
18
-
19
- Attributes:
20
- device (str): Computing device ('cuda' or 'cpu').
21
- results: Object detection or segmentation results.
22
- source: Source image or image path.
23
- clip: CLIP model for linear assignment.
24
- """
25
-
26
- def __init__(self, source, results, device="cuda") -> None:
27
- """Initializes FastSAMPrompt with given source, results and device, and assigns clip for linear assignment."""
28
- if isinstance(source, (str, Path)) and os.path.isdir(source):
29
- raise ValueError("FastSAM only accepts image paths and PIL Image sources, not directories.")
30
- self.device = device
31
- self.results = results
32
- self.source = source
33
-
34
- # Import and assign clip
35
- try:
36
- import clip
37
- except ImportError:
38
- checks.check_requirements("git+https://github.com/ultralytics/CLIP.git")
39
- import clip
40
- self.clip = clip
41
-
42
- @staticmethod
43
- def _segment_image(image, bbox):
44
- """Segments the given image according to the provided bounding box coordinates."""
45
- image_array = np.array(image)
46
- segmented_image_array = np.zeros_like(image_array)
47
- x1, y1, x2, y2 = bbox
48
- segmented_image_array[y1:y2, x1:x2] = image_array[y1:y2, x1:x2]
49
- segmented_image = Image.fromarray(segmented_image_array)
50
- black_image = Image.new("RGB", image.size, (255, 255, 255))
51
- # transparency_mask = np.zeros_like((), dtype=np.uint8)
52
- transparency_mask = np.zeros((image_array.shape[0], image_array.shape[1]), dtype=np.uint8)
53
- transparency_mask[y1:y2, x1:x2] = 255
54
- transparency_mask_image = Image.fromarray(transparency_mask, mode="L")
55
- black_image.paste(segmented_image, mask=transparency_mask_image)
56
- return black_image
57
-
58
- @staticmethod
59
- def _format_results(result, filter=0):
60
- """Formats detection results into list of annotations each containing ID, segmentation, bounding box, score and
61
- area.
62
- """
63
- annotations = []
64
- n = len(result.masks.data) if result.masks is not None else 0
65
- for i in range(n):
66
- mask = result.masks.data[i] == 1.0
67
- if torch.sum(mask) >= filter:
68
- annotation = {
69
- "id": i,
70
- "segmentation": mask.cpu().numpy(),
71
- "bbox": result.boxes.data[i],
72
- "score": result.boxes.conf[i],
73
- }
74
- annotation["area"] = annotation["segmentation"].sum()
75
- annotations.append(annotation)
76
- return annotations
77
-
78
- @staticmethod
79
- def _get_bbox_from_mask(mask):
80
- """Applies morphological transformations to the mask, displays it, and if with_contours is True, draws
81
- contours.
82
- """
83
- mask = mask.astype(np.uint8)
84
- contours, hierarchy = cv2.findContours(mask, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
85
- x1, y1, w, h = cv2.boundingRect(contours[0])
86
- x2, y2 = x1 + w, y1 + h
87
- if len(contours) > 1:
88
- for b in contours:
89
- x_t, y_t, w_t, h_t = cv2.boundingRect(b)
90
- x1 = min(x1, x_t)
91
- y1 = min(y1, y_t)
92
- x2 = max(x2, x_t + w_t)
93
- y2 = max(y2, y_t + h_t)
94
- return [x1, y1, x2, y2]
95
-
96
- def plot(
97
- self,
98
- annotations,
99
- output,
100
- bbox=None,
101
- points=None,
102
- point_label=None,
103
- mask_random_color=True,
104
- better_quality=True,
105
- retina=False,
106
- with_contours=True,
107
- ):
108
- """
109
- Plots annotations, bounding boxes, and points on images and saves the output.
110
-
111
- Args:
112
- annotations (list): Annotations to be plotted.
113
- output (str or Path): Output directory for saving the plots.
114
- bbox (list, optional): Bounding box coordinates [x1, y1, x2, y2]. Defaults to None.
115
- points (list, optional): Points to be plotted. Defaults to None.
116
- point_label (list, optional): Labels for the points. Defaults to None.
117
- mask_random_color (bool, optional): Whether to use random color for masks. Defaults to True.
118
- better_quality (bool, optional): Whether to apply morphological transformations for better mask quality.
119
- Defaults to True.
120
- retina (bool, optional): Whether to use retina mask. Defaults to False.
121
- with_contours (bool, optional): Whether to plot contours. Defaults to True.
122
- """
123
- import matplotlib.pyplot as plt
124
-
125
- pbar = TQDM(annotations, total=len(annotations))
126
- for ann in pbar:
127
- result_name = os.path.basename(ann.path)
128
- image = ann.orig_img[..., ::-1] # BGR to RGB
129
- original_h, original_w = ann.orig_shape
130
- # For macOS only
131
- # plt.switch_backend('TkAgg')
132
- plt.figure(figsize=(original_w / 100, original_h / 100))
133
- # Add subplot with no margin.
134
- plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
135
- plt.margins(0, 0)
136
- plt.gca().xaxis.set_major_locator(plt.NullLocator())
137
- plt.gca().yaxis.set_major_locator(plt.NullLocator())
138
- plt.imshow(image)
139
-
140
- if ann.masks is not None:
141
- masks = ann.masks.data
142
- if better_quality:
143
- if isinstance(masks[0], torch.Tensor):
144
- masks = np.array(masks.cpu())
145
- for i, mask in enumerate(masks):
146
- mask = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_CLOSE, np.ones((3, 3), np.uint8))
147
- masks[i] = cv2.morphologyEx(mask.astype(np.uint8), cv2.MORPH_OPEN, np.ones((8, 8), np.uint8))
148
-
149
- self.fast_show_mask(
150
- masks,
151
- plt.gca(),
152
- random_color=mask_random_color,
153
- bbox=bbox,
154
- points=points,
155
- pointlabel=point_label,
156
- retinamask=retina,
157
- target_height=original_h,
158
- target_width=original_w,
159
- )
160
-
161
- if with_contours:
162
- contour_all = []
163
- temp = np.zeros((original_h, original_w, 1))
164
- for i, mask in enumerate(masks):
165
- mask = mask.astype(np.uint8)
166
- if not retina:
167
- mask = cv2.resize(mask, (original_w, original_h), interpolation=cv2.INTER_NEAREST)
168
- contours, _ = cv2.findContours(mask, cv2.RETR_TREE, cv2.CHAIN_APPROX_SIMPLE)
169
- contour_all.extend(iter(contours))
170
- cv2.drawContours(temp, contour_all, -1, (255, 255, 255), 2)
171
- color = np.array([0 / 255, 0 / 255, 1.0, 0.8])
172
- contour_mask = temp / 255 * color.reshape(1, 1, -1)
173
- plt.imshow(contour_mask)
174
-
175
- # Save the figure
176
- save_path = Path(output) / result_name
177
- save_path.parent.mkdir(exist_ok=True, parents=True)
178
- plt.axis("off")
179
- plt.savefig(save_path, bbox_inches="tight", pad_inches=0, transparent=True)
180
- plt.close()
181
- pbar.set_description(f"Saving {result_name} to {save_path}")
182
-
183
- @staticmethod
184
- def fast_show_mask(
185
- annotation,
186
- ax,
187
- random_color=False,
188
- bbox=None,
189
- points=None,
190
- pointlabel=None,
191
- retinamask=True,
192
- target_height=960,
193
- target_width=960,
194
- ):
195
- """
196
- Quickly shows the mask annotations on the given matplotlib axis.
197
-
198
- Args:
199
- annotation (array-like): Mask annotation.
200
- ax (matplotlib.axes.Axes): Matplotlib axis.
201
- random_color (bool, optional): Whether to use random color for masks. Defaults to False.
202
- bbox (list, optional): Bounding box coordinates [x1, y1, x2, y2]. Defaults to None.
203
- points (list, optional): Points to be plotted. Defaults to None.
204
- pointlabel (list, optional): Labels for the points. Defaults to None.
205
- retinamask (bool, optional): Whether to use retina mask. Defaults to True.
206
- target_height (int, optional): Target height for resizing. Defaults to 960.
207
- target_width (int, optional): Target width for resizing. Defaults to 960.
208
- """
209
- import matplotlib.pyplot as plt
210
-
211
- n, h, w = annotation.shape # batch, height, width
212
-
213
- areas = np.sum(annotation, axis=(1, 2))
214
- annotation = annotation[np.argsort(areas)]
215
-
216
- index = (annotation != 0).argmax(axis=0)
217
- if random_color:
218
- color = np.random.random((n, 1, 1, 3))
219
- else:
220
- color = np.ones((n, 1, 1, 3)) * np.array([30 / 255, 144 / 255, 1.0])
221
- transparency = np.ones((n, 1, 1, 1)) * 0.6
222
- visual = np.concatenate([color, transparency], axis=-1)
223
- mask_image = np.expand_dims(annotation, -1) * visual
224
-
225
- show = np.zeros((h, w, 4))
226
- h_indices, w_indices = np.meshgrid(np.arange(h), np.arange(w), indexing="ij")
227
- indices = (index[h_indices, w_indices], h_indices, w_indices, slice(None))
228
-
229
- show[h_indices, w_indices, :] = mask_image[indices]
230
- if bbox is not None:
231
- x1, y1, x2, y2 = bbox
232
- ax.add_patch(plt.Rectangle((x1, y1), x2 - x1, y2 - y1, fill=False, edgecolor="b", linewidth=1))
233
- # Draw point
234
- if points is not None:
235
- plt.scatter(
236
- [point[0] for i, point in enumerate(points) if pointlabel[i] == 1],
237
- [point[1] for i, point in enumerate(points) if pointlabel[i] == 1],
238
- s=20,
239
- c="y",
240
- )
241
- plt.scatter(
242
- [point[0] for i, point in enumerate(points) if pointlabel[i] == 0],
243
- [point[1] for i, point in enumerate(points) if pointlabel[i] == 0],
244
- s=20,
245
- c="m",
246
- )
247
-
248
- if not retinamask:
249
- show = cv2.resize(show, (target_width, target_height), interpolation=cv2.INTER_NEAREST)
250
- ax.imshow(show)
251
-
252
- @torch.no_grad()
253
- def retrieve(self, model, preprocess, elements, search_text: str, device) -> Tensor:
254
- """Processes images and text with a model, calculates similarity, and returns softmax score."""
255
- preprocessed_images = [preprocess(image).to(device) for image in elements]
256
- tokenized_text = self.clip.tokenize([search_text]).to(device)
257
- stacked_images = torch.stack(preprocessed_images)
258
- image_features = model.encode_image(stacked_images)
259
- text_features = model.encode_text(tokenized_text)
260
- image_features /= image_features.norm(dim=-1, keepdim=True)
261
- text_features /= text_features.norm(dim=-1, keepdim=True)
262
- probs = 100.0 * image_features @ text_features.T
263
- return probs[:, 0].softmax(dim=0)
264
-
265
- def _crop_image(self, format_results):
266
- """Crops an image based on provided annotation format and returns cropped images and related data."""
267
- image = Image.fromarray(cv2.cvtColor(self.results[0].orig_img, cv2.COLOR_BGR2RGB))
268
- ori_w, ori_h = image.size
269
- annotations = format_results
270
- mask_h, mask_w = annotations[0]["segmentation"].shape
271
- if ori_w != mask_w or ori_h != mask_h:
272
- image = image.resize((mask_w, mask_h))
273
- cropped_images = []
274
- filter_id = []
275
- for _, mask in enumerate(annotations):
276
- if np.sum(mask["segmentation"]) <= 100:
277
- filter_id.append(_)
278
- continue
279
- bbox = self._get_bbox_from_mask(mask["segmentation"]) # bbox from mask
280
- cropped_images.append(self._segment_image(image, bbox)) # save cropped image
281
-
282
- return cropped_images, filter_id, annotations
283
-
284
- def box_prompt(self, bbox):
285
- """Modifies the bounding box properties and calculates IoU between masks and bounding box."""
286
- if self.results[0].masks is not None:
287
- assert bbox[2] != 0 and bbox[3] != 0, "Bounding box width and height should not be zero"
288
- masks = self.results[0].masks.data
289
- target_height, target_width = self.results[0].orig_shape
290
- h = masks.shape[1]
291
- w = masks.shape[2]
292
- if h != target_height or w != target_width:
293
- bbox = [
294
- int(bbox[0] * w / target_width),
295
- int(bbox[1] * h / target_height),
296
- int(bbox[2] * w / target_width),
297
- int(bbox[3] * h / target_height),
298
- ]
299
- bbox[0] = max(round(bbox[0]), 0)
300
- bbox[1] = max(round(bbox[1]), 0)
301
- bbox[2] = min(round(bbox[2]), w)
302
- bbox[3] = min(round(bbox[3]), h)
303
-
304
- # IoUs = torch.zeros(len(masks), dtype=torch.float32)
305
- bbox_area = (bbox[3] - bbox[1]) * (bbox[2] - bbox[0])
306
-
307
- masks_area = torch.sum(masks[:, bbox[1] : bbox[3], bbox[0] : bbox[2]], dim=(1, 2))
308
- orig_masks_area = torch.sum(masks, dim=(1, 2))
309
-
310
- union = bbox_area + orig_masks_area - masks_area
311
- iou = masks_area / union
312
- max_iou_index = torch.argmax(iou)
313
-
314
- self.results[0].masks.data = torch.tensor(np.array([masks[max_iou_index].cpu().numpy()]))
315
- return self.results
316
-
317
- def point_prompt(self, points, pointlabel): # numpy
318
- """Adjusts points on detected masks based on user input and returns the modified results."""
319
- if self.results[0].masks is not None:
320
- masks = self._format_results(self.results[0], 0)
321
- target_height, target_width = self.results[0].orig_shape
322
- h = masks[0]["segmentation"].shape[0]
323
- w = masks[0]["segmentation"].shape[1]
324
- if h != target_height or w != target_width:
325
- points = [[int(point[0] * w / target_width), int(point[1] * h / target_height)] for point in points]
326
- onemask = np.zeros((h, w))
327
- for annotation in masks:
328
- mask = annotation["segmentation"] if isinstance(annotation, dict) else annotation
329
- for i, point in enumerate(points):
330
- if mask[point[1], point[0]] == 1 and pointlabel[i] == 1:
331
- onemask += mask
332
- if mask[point[1], point[0]] == 1 and pointlabel[i] == 0:
333
- onemask -= mask
334
- onemask = onemask >= 1
335
- self.results[0].masks.data = torch.tensor(np.array([onemask]))
336
- return self.results
337
-
338
- def text_prompt(self, text, clip_download_root=None):
339
- """Processes a text prompt, applies it to existing results and returns the updated results."""
340
- if self.results[0].masks is not None:
341
- format_results = self._format_results(self.results[0], 0)
342
- cropped_images, filter_id, annotations = self._crop_image(format_results)
343
- clip_model, preprocess = self.clip.load("ViT-B/32", download_root=clip_download_root, device=self.device)
344
- scores = self.retrieve(clip_model, preprocess, cropped_images, text, device=self.device)
345
- max_idx = torch.argmax(scores)
346
- max_idx += sum(np.array(filter_id) <= int(max_idx))
347
- self.results[0].masks.data = torch.tensor(np.array([annotations[max_idx]["segmentation"]]))
348
- return self.results
349
-
350
- def everything_prompt(self):
351
- """Returns the processed results from the previous methods in the class."""
352
- return self.results