sahi
¶
Classes¶
AutoDetectionModel
¶
Source code in sahi/auto_model.py
Functions¶
from_pretrained(model_type, model_path=None, model=None, config_path=None, device=None, mask_threshold=0.5, confidence_threshold=0.3, category_mapping=None, category_remapping=None, load_at_init=True, image_size=None, **kwargs)
staticmethod
¶
Loads a DetectionModel from given path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
¶ |
str
|
str Name of the detection framework (example: "ultralytics", "huggingface", "torchvision") |
required |
model_path
¶ |
str | None
|
str Path of the detection model (ex. 'model.pt') |
None
|
model
¶ |
Any | None
|
Any A pre-initialized model instance, if available |
None
|
config_path
¶ |
str | None
|
str Path of the config file (ex. 'mmdet/configs/cascade_rcnn_r50_fpn_1x.py') |
None
|
device
¶ |
str | None
|
str Device, "cpu" or "cuda:0" |
None
|
mask_threshold
¶ |
float
|
float Value to threshold mask pixels, should be between 0 and 1 |
0.5
|
confidence_threshold
¶ |
float
|
float All predictions with score < confidence_threshold will be discarded |
0.3
|
category_mapping
¶ |
dict | None
|
dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} |
None
|
load_at_init
¶ |
bool
|
bool If True, automatically loads the model at initialization |
True
|
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Returns:
| Type | Description |
|---|---|
DetectionModel
|
Returns an instance of a DetectionModel |
Raises:
| Type | Description |
|---|---|
ImportError
|
If given {model_type} framework is not installed |
Source code in sahi/auto_model.py
BoundingBox
dataclass
¶
BoundingBox represents a rectangular region in 2D space, typically used for object detection annotations.
Attributes:
| Name | Type | Description |
|---|---|---|
box |
Tuple[float, float, float, float]
|
The bounding box coordinates in the format (minx, miny, maxx, maxy). - minx (float): Minimum x-coordinate (left). - miny (float): Minimum y-coordinate (top). - maxx (float): Maximum x-coordinate (right). - maxy (float): Maximum y-coordinate (bottom). |
shift_amount |
Tuple[int, int]
|
The amount to shift the bounding box in the x and y directions. Defaults to (0, 0). |
BoundingBox Usage Example
Source code in sahi/annotation.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
Functions¶
get_expanded_box(ratio=0.1, max_x=None, max_y=None)
¶
Returns an expanded bounding box by increasing its size by a given ratio. The expansion is applied equally in all directions. Optionally, the expanded box can be clipped to maximum x and y boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratio
¶ |
float
|
The proportion by which to expand the box size. Default is 0.1 (10%). |
0.1
|
max_x
¶ |
int
|
The maximum allowed x-coordinate for the expanded box. If None, no maximum is applied. |
None
|
max_y
¶ |
int
|
The maximum allowed y-coordinate for the expanded box. If None, no maximum is applied. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BoundingBox |
A new BoundingBox instance representing the expanded box. |
Source code in sahi/annotation.py
get_shifted_box()
¶
Returns shifted BoundingBox.
Returns:
| Name | Type | Description |
|---|---|---|
BoundingBox |
A new BoundingBox instance representing the shifted box. |
Source code in sahi/annotation.py
to_coco_bbox()
¶
Returns the bounding box in COCO format: [xmin, ymin, width, height]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in COCO format. |
to_voc_bbox()
¶
Returns the bounding box in VOC format: [xmin, ymin, xmax, ymax]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in VOC format. |
to_xywh()
¶
Returns [xmin, ymin, width, height]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in the format [xmin, ymin, width, height]. |
Source code in sahi/annotation.py
to_xyxy()
¶
Returns: [xmin, ymin, xmax, ymax]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in the format [xmin, ymin, xmax, ymax]. |
Category
dataclass
¶
Category of the annotation.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
int
|
Unique identifier for the category. |
name |
str
|
Name of the category. |
Source code in sahi/annotation.py
DetectionModel
¶
Source code in sahi/models/base.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
Functions¶
__init__(model_path=None, model=None, config_path=None, device=None, mask_threshold=0.5, confidence_threshold=0.3, category_mapping=None, category_remapping=None, load_at_init=True, image_size=None)
¶
Init object detection/instance segmentation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
¶ |
str | None
|
str Path for the instance segmentation model weight |
None
|
config_path
¶ |
str | None
|
str Path for the mmdetection instance segmentation model config file |
None
|
device
¶ |
str | None
|
Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. |
None
|
mask_threshold
¶ |
float
|
float Value to threshold mask pixels, should be between 0 and 1 |
0.5
|
confidence_threshold
¶ |
float
|
float All predictions with score < confidence_threshold will be discarded |
0.3
|
category_mapping
¶ |
dict | None
|
dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} |
None
|
load_at_init
¶ |
bool
|
bool If True, automatically loads the model at initialization |
True
|
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Source code in sahi/models/base.py
check_dependencies(packages=None)
¶
Ensures required dependencies are installed.
If 'packages' is None, uses self.required_packages. Subclasses may still call with a custom list for dynamic needs.
Source code in sahi/models/base.py
convert_original_predictions(shift_amount=[[0, 0]], full_shape=None)
¶
Converts original predictions of the detection model to a list of prediction.ObjectPrediction object.
Should be called after perform_inference(). Args: shift_amount: list To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] full_shape: list Size of the full image after shifting, should be in the form of [height, width]
Source code in sahi/models/base.py
load_model()
¶
This function should be implemented in a way that detection model should be initialized and set to self.model.
(self.model_path, self.config_path, and self.device should be utilized)
perform_inference(image)
¶
This function should be implemented in a way that prediction should be performed using self.model and the prediction result should be set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. |
required |
Source code in sahi/models/base.py
set_device(device=None)
¶
Sets the device pytorch should use for the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
¶ |
str | None
|
Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. |
None
|
set_model(model, **kwargs)
¶
This function should be implemented to instantiate a DetectionModel out of an already loaded model Args: model: Any Loaded model
Mask
¶
Init Mask from coco segmentation representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
|
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
required | |
|
list[int]
|
List[int] Size of the full image, should be in the form of [height, width] |
required |
|
list
|
List[int] To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
Attributes¶
full_shape
property
¶
Returns full mask shape after shifting as [height, width]
shape
property
¶
Returns mask shape as [height, width]
shift_amount
property
¶
Returns the shift amount of the mask slice as [shift_x, shift_y]
Functions¶
from_bool_mask(bool_mask, full_shape, shift_amount=[0, 0])
classmethod
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bool_mask
¶ |
ndarray
|
np.ndarray with bool elements 2D mask of object, should have a shape of height*width |
required |
full_shape
¶ |
list[int]
|
List[int] Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list
|
List[int] To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_float_mask(mask, full_shape, mask_threshold=0.5, shift_amount=[0, 0])
classmethod
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
¶ |
ndarray
|
np.ndarray of np.float elements Mask values between 0 and 1 (should have a shape of height*width) |
required |
mask_threshold
¶ |
float
|
float Value to threshold mask pixels between 0 and 1 |
0.5
|
shift_amount
¶ |
list
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int]
|
List[int] Size of the full image after shifting, should be in the form of [height, width] |
required |
Source code in sahi/annotation.py
ObjectPrediction
¶
Bases: ObjectAnnotation
Class for handling detection model predictions.
Source code in sahi/prediction.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
Functions¶
__init__(bbox=None, category_id=None, category_name=None, segmentation=None, score=0.0, shift_amount=[0, 0], full_shape=None)
¶
Creates ObjectPrediction from bbox, score, category_id, category_name, segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
list[int] | None
|
list [minx, miny, maxx, maxy] |
None
|
score
¶ |
float
|
float Prediction score between 0 and 1 |
0.0
|
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
segmentation
¶ |
list[list[float]] | None
|
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
None
|
shift_amount
¶ |
list[int] | None
|
list To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int] | None
|
list Size of the full image after shifting, should be in the form of [height, width] |
None
|
Source code in sahi/prediction.py
get_shifted_object_prediction()
¶
Returns shifted version ObjectPrediction.
Shifts bbox and mask coords. Used for mapping sliced predictions over full image.
Source code in sahi/prediction.py
to_coco_prediction(image_id=None)
¶
Returns sahi.utils.coco.CocoPrediction representation of ObjectAnnotation.
Source code in sahi/prediction.py
to_fiftyone_detection(image_height, image_width)
¶
Returns fiftyone.Detection representation of ObjectPrediction.
Source code in sahi/prediction.py
Modules¶
annotation
¶
Classes¶
BoundingBox
dataclass
¶
BoundingBox represents a rectangular region in 2D space, typically used for object detection annotations.
Attributes:
| Name | Type | Description |
|---|---|---|
box |
Tuple[float, float, float, float]
|
The bounding box coordinates in the format (minx, miny, maxx, maxy). - minx (float): Minimum x-coordinate (left). - miny (float): Minimum y-coordinate (top). - maxx (float): Maximum x-coordinate (right). - maxy (float): Maximum y-coordinate (bottom). |
shift_amount |
Tuple[int, int]
|
The amount to shift the bounding box in the x and y directions. Defaults to (0, 0). |
BoundingBox Usage Example
Source code in sahi/annotation.py
17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 | |
get_expanded_box(ratio=0.1, max_x=None, max_y=None)
¶Returns an expanded bounding box by increasing its size by a given ratio. The expansion is applied equally in all directions. Optionally, the expanded box can be clipped to maximum x and y boundaries.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ratio
¶ |
float
|
The proportion by which to expand the box size. Default is 0.1 (10%). |
0.1
|
max_x
¶ |
int
|
The maximum allowed x-coordinate for the expanded box. If None, no maximum is applied. |
None
|
max_y
¶ |
int
|
The maximum allowed y-coordinate for the expanded box. If None, no maximum is applied. |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
BoundingBox |
A new BoundingBox instance representing the expanded box. |
Source code in sahi/annotation.py
get_shifted_box()
¶Returns shifted BoundingBox.
Returns:
| Name | Type | Description |
|---|---|---|
BoundingBox |
A new BoundingBox instance representing the shifted box. |
Source code in sahi/annotation.py
to_coco_bbox()
¶Returns the bounding box in COCO format: [xmin, ymin, width, height]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in COCO format. |
to_voc_bbox()
¶Returns the bounding box in VOC format: [xmin, ymin, xmax, ymax]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in VOC format. |
to_xywh()
¶Returns [xmin, ymin, width, height]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in the format [xmin, ymin, width, height]. |
Source code in sahi/annotation.py
to_xyxy()
¶Returns: [xmin, ymin, xmax, ymax]
Returns:
| Type | Description |
|---|---|
|
List[float]: A list containing the bounding box in the format [xmin, ymin, xmax, ymax]. |
Category
dataclass
¶
Category of the annotation.
Attributes:
| Name | Type | Description |
|---|---|---|
id |
int
|
Unique identifier for the category. |
name |
str
|
Name of the category. |
Source code in sahi/annotation.py
Mask
¶
Init Mask from coco segmentation representation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
required | |
full_shape
¶ |
list[int]
|
List[int] Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list
|
List[int] To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 | |
full_shape
property
¶Returns full mask shape after shifting as [height, width]
shape
property
¶Returns mask shape as [height, width]
shift_amount
property
¶Returns the shift amount of the mask slice as [shift_x, shift_y]
from_bool_mask(bool_mask, full_shape, shift_amount=[0, 0])
classmethod
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bool_mask
¶ |
ndarray
|
np.ndarray with bool elements 2D mask of object, should have a shape of height*width |
required |
full_shape
¶ |
list[int]
|
List[int] Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list
|
List[int] To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_float_mask(mask, full_shape, mask_threshold=0.5, shift_amount=[0, 0])
classmethod
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
mask
¶ |
ndarray
|
np.ndarray of np.float elements Mask values between 0 and 1 (should have a shape of height*width) |
required |
mask_threshold
¶ |
float
|
float Value to threshold mask pixels between 0 and 1 |
0.5
|
shift_amount
¶ |
list
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int]
|
List[int] Size of the full image after shifting, should be in the form of [height, width] |
required |
Source code in sahi/annotation.py
ObjectAnnotation
¶
All about an annotation such as Mask, Category, BoundingBox.
Source code in sahi/annotation.py
302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 | |
__init__(bbox=None, segmentation=None, category_id=None, category_name=None, shift_amount=[0, 0], full_shape=None)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
list[int] | None
|
List [minx, miny, maxx, maxy] |
None
|
segmentation
¶ |
ndarray | None
|
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
None
|
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int] | None
|
List Size of the full image after shifting, should be in the form of [height, width] |
None
|
Source code in sahi/annotation.py
deepcopy()
¶ from_bool_mask(bool_mask, category_id=None, category_name=None, shift_amount=[0, 0], full_shape=None)
classmethod
¶Creates ObjectAnnotation from bool_mask (2D np.ndarray)
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bool_mask
¶ |
np.ndarray with bool elements 2D mask of object, should have a shape of height*width |
required | |
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
full_shape
¶ |
list[int] | None
|
List Size of the full image, should be in the form of [height, width] |
None
|
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_coco_annotation_dict(annotation_dict, full_shape, category_name=None, shift_amount=[0, 0])
classmethod
¶Creates ObjectAnnotation object from category name and COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation_dict
¶ |
dict
|
dict COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id") |
required |
category_name
¶ |
str | None
|
str Category name of the annotation |
None
|
full_shape
¶ |
list[int]
|
List Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_coco_bbox(bbox, category_id=None, category_name=None, shift_amount=[0, 0], full_shape=None)
classmethod
¶Creates ObjectAnnotation from coco bbox [minx, miny, width, height]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
list[int]
|
List [minx, miny, width, height] |
required |
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
full_shape
¶ |
list[int] | None
|
List Size of the full image, should be in the form of [height, width] |
None
|
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_coco_segmentation(segmentation, full_shape, category_id=None, category_name=None, shift_amount=[0, 0])
classmethod
¶Creates ObjectAnnotation from coco segmentation: [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ]
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
required | |
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
full_shape
¶ |
list[int]
|
List Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
from_imantics_annotation(annotation, shift_amount=[0, 0], full_shape=None)
classmethod
¶Creates ObjectAnnotation from imantics.annotation.Annotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation
¶ |
imantics.annotation.Annotation |
required | |
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int] | None
|
List Size of the full image, should be in the form of [height, width] |
None
|
Source code in sahi/annotation.py
from_shapely_annotation(annotation, full_shape, category_id=None, category_name=None, shift_amount=[0, 0])
classmethod
¶Creates ObjectAnnotation from shapely_utils.ShapelyAnnotation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation
¶ |
ShapelyAnnotation
|
shapely_utils.ShapelyAnnotation |
required |
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
full_shape
¶ |
list[int]
|
List Size of the full image, should be in the form of [height, width] |
required |
shift_amount
¶ |
list[int] | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
Source code in sahi/annotation.py
to_coco_annotation()
¶Returns sahi.utils.coco.CocoAnnotation representation of ObjectAnnotation.
Source code in sahi/annotation.py
to_coco_prediction()
¶Returns sahi.utils.coco.CocoPrediction representation of ObjectAnnotation.
Source code in sahi/annotation.py
to_imantics_annotation()
¶Returns imantics.annotation.Annotation representation of ObjectAnnotation.
Source code in sahi/annotation.py
to_shapely_annotation()
¶Returns sahi.utils.shapely.ShapelyAnnotation representation of ObjectAnnotation.
Source code in sahi/annotation.py
Functions¶
auto_model
¶
Classes¶
AutoDetectionModel
¶
Source code in sahi/auto_model.py
from_pretrained(model_type, model_path=None, model=None, config_path=None, device=None, mask_threshold=0.5, confidence_threshold=0.3, category_mapping=None, category_remapping=None, load_at_init=True, image_size=None, **kwargs)
staticmethod
¶Loads a DetectionModel from given path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
¶ |
str
|
str Name of the detection framework (example: "ultralytics", "huggingface", "torchvision") |
required |
model_path
¶ |
str | None
|
str Path of the detection model (ex. 'model.pt') |
None
|
model
¶ |
Any | None
|
Any A pre-initialized model instance, if available |
None
|
config_path
¶ |
str | None
|
str Path of the config file (ex. 'mmdet/configs/cascade_rcnn_r50_fpn_1x.py') |
None
|
device
¶ |
str | None
|
str Device, "cpu" or "cuda:0" |
None
|
mask_threshold
¶ |
float
|
float Value to threshold mask pixels, should be between 0 and 1 |
0.5
|
confidence_threshold
¶ |
float
|
float All predictions with score < confidence_threshold will be discarded |
0.3
|
category_mapping
¶ |
dict | None
|
dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} |
None
|
load_at_init
¶ |
bool
|
bool If True, automatically loads the model at initialization |
True
|
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Returns:
| Type | Description |
|---|---|
DetectionModel
|
Returns an instance of a DetectionModel |
Raises:
| Type | Description |
|---|---|
ImportError
|
If given {model_type} framework is not installed |
Source code in sahi/auto_model.py
Functions¶
cli
¶
models
¶
Modules¶
base
¶
DetectionModel
¶Source code in sahi/models/base.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 | |
__init__(model_path=None, model=None, config_path=None, device=None, mask_threshold=0.5, confidence_threshold=0.3, category_mapping=None, category_remapping=None, load_at_init=True, image_size=None)
¶Init object detection/instance segmentation model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
¶ |
str | None
|
str Path for the instance segmentation model weight |
None
|
config_path
¶ |
str | None
|
str Path for the mmdetection instance segmentation model config file |
None
|
device
¶ |
str | None
|
Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. |
None
|
mask_threshold
¶ |
float
|
float Value to threshold mask pixels, should be between 0 and 1 |
0.5
|
confidence_threshold
¶ |
float
|
float All predictions with score < confidence_threshold will be discarded |
0.3
|
category_mapping
¶ |
dict | None
|
dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} |
None
|
load_at_init
¶ |
bool
|
bool If True, automatically loads the model at initialization |
True
|
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Source code in sahi/models/base.py
check_dependencies(packages=None)
¶Ensures required dependencies are installed.
If 'packages' is None, uses self.required_packages. Subclasses may still call with a custom list for dynamic needs.
Source code in sahi/models/base.py
convert_original_predictions(shift_amount=[[0, 0]], full_shape=None)
¶Converts original predictions of the detection model to a list of prediction.ObjectPrediction object.
Should be called after perform_inference(). Args: shift_amount: list To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] full_shape: list Size of the full image after shifting, should be in the form of [height, width]
Source code in sahi/models/base.py
load_model()
¶This function should be implemented in a way that detection model should be initialized and set to self.model.
(self.model_path, self.config_path, and self.device should be utilized)
perform_inference(image)
¶This function should be implemented in a way that prediction should be performed using self.model and the prediction result should be set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. |
required |
Source code in sahi/models/base.py
set_device(device=None)
¶Sets the device pytorch should use for the model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
¶ |
str | None
|
Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. |
None
|
set_model(model, **kwargs)
¶This function should be implemented to instantiate a DetectionModel out of an already loaded model Args: model: Any Loaded model
detectron2
¶
Detectron2DetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/detectron2.py
11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 | |
num_categories
property
¶Returns number of categories.
perform_inference(image)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
Source code in sahi/models/detectron2.py
huggingface
¶
HuggingfaceDetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/huggingface.py
15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 | |
num_categories
property
¶Returns number of categories.
get_valid_predictions(logits, pred_boxes)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
logits
¶ |
torch.Tensor |
required | |
pred_boxes
¶ |
torch.Tensor |
required |
Returns: scores: torch.Tensor cat_ids: torch.Tensor boxes: torch.Tensor
Source code in sahi/models/huggingface.py
perform_inference(image)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
list | ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
Source code in sahi/models/huggingface.py
mmdet
¶
DetInferencerWrapper
¶
Bases: DetInferencer
Source code in sahi/models/mmdet.py
__call__(images, batch_size=1)
¶Emulate DetInferencer(images) without progressbar Args: images: list of np.ndarray A list of numpy array that contains the image to be predicted. 3 channel image should be in RGB order. batch_size: int Inference batch size. Defaults to 1.
Source code in sahi/models/mmdet.py
MmdetDetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/mmdet.py
82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 | |
has_mask
property
¶Returns if model output contains segmentation mask.
Considers both single dataset and ConcatDataset scenarios.
num_categories
property
¶Returns number of categories.
load_model()
¶Detection model is initialized and set to self.model.
Source code in sahi/models/mmdet.py
perform_inference(image)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
Source code in sahi/models/mmdet.py
set_model(model)
¶Sets the underlying MMDetection model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
¶ |
Any
|
Any A MMDetection model |
required |
Source code in sahi/models/mmdet.py
roboflow
¶
RoboflowDetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/roboflow.py
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 | |
__init__(model=None, model_path=None, config_path=None, device=None, mask_threshold=0.5, confidence_threshold=0.3, category_mapping=None, category_remapping=None, load_at_init=True, image_size=None, api_key=None)
¶Initialize the RoboflowDetectionModel with the given parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_path
¶ |
str | None
|
str Path for the instance segmentation model weight |
None
|
config_path
¶ |
str | None
|
str Path for the mmdetection instance segmentation model config file |
None
|
device
¶ |
str | None
|
Torch device, "cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. |
None
|
mask_threshold
¶ |
float
|
float Value to threshold mask pixels, should be between 0 and 1 |
0.5
|
confidence_threshold
¶ |
float
|
float All predictions with score < confidence_threshold will be discarded |
0.3
|
category_mapping
¶ |
dict | None
|
dict: str to str Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids based on category names, after performing inference e.g. {"car": 3} |
None
|
load_at_init
¶ |
bool
|
bool If True, automatically loads the model at initialization |
True
|
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Source code in sahi/models/roboflow.py
load_model()
¶This function should be implemented in a way that detection model should be initialized and set to self.model.
(self.model_path, self.config_path, and self.device should be utilized)
Source code in sahi/models/roboflow.py
perform_inference(image)
¶This function should be implemented in a way that prediction should be performed using self.model and the prediction result should be set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. |
required |
Source code in sahi/models/roboflow.py
set_model(model, **kwargs)
¶This function should be implemented to instantiate a DetectionModel out of an already loaded model Args: model: Any Loaded model
rtdetr
¶
RTDetrDetectionModel
¶
Bases: UltralyticsDetectionModel
Source code in sahi/models/rtdetr.py
load_model()
¶Detection model is initialized and set to self.model.
Source code in sahi/models/rtdetr.py
torchvision
¶
TorchVisionDetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/torchvision.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 | |
has_mask
property
¶Returns if model output contains segmentation mask.
num_categories
property
¶Returns number of categories.
perform_inference(image, image_size=None)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
image_size
¶ |
int | None
|
int Inference input size. |
None
|
Source code in sahi/models/torchvision.py
set_model(model)
¶Sets the underlying TorchVision model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
¶ |
Any
|
Any A TorchVision model |
required |
Source code in sahi/models/torchvision.py
ultralytics
¶
UltralyticsDetectionModel
¶
Bases: DetectionModel
Detection model for Ultralytics YOLO models.
Supports both PyTorch (.pt) and ONNX (.onnx) models.
Source code in sahi/models/ultralytics.py
16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 | |
has_mask
property
¶Returns if model output contains segmentation mask.
is_obb
property
¶Returns if model output contains oriented bounding boxes.
num_categories
property
¶Returns number of categories.
load_model()
¶Detection model is initialized and set to self.model.
Supports both PyTorch (.pt) and ONNX (.onnx) models.
Source code in sahi/models/ultralytics.py
perform_inference(image)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
Source code in sahi/models/ultralytics.py
set_model(model, **kwargs)
¶Sets the underlying Ultralytics model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
¶ |
Any
|
Any A Ultralytics model |
required |
Source code in sahi/models/ultralytics.py
yolo-world
¶
YOLOWorldDetectionModel
¶
Bases: UltralyticsDetectionModel
Source code in sahi/models/yolo-world.py
load_model()
¶Detection model is initialized and set to self.model.
Source code in sahi/models/yolo-world.py
yoloe
¶
YOLOEDetectionModel
¶
Bases: UltralyticsDetectionModel
YOLOE Detection Model for open-vocabulary detection and segmentation.
YOLOE (Real-Time Seeing Anything) is a zero-shot, promptable YOLO model designed for open-vocabulary detection and segmentation. It supports text prompts, visual prompts, and prompt-free detection with internal vocabulary (1200+ categories).
Key Features
- Open-vocabulary detection: Detect any object class via text prompts
- Visual prompting: One-shot detection using reference images
- Instance segmentation: Built-in segmentation for detected objects
- Real-time performance: Maintains YOLO speed with no inference overhead
- Prompt-free mode: Uses internal vocabulary for open-set recognition
Available Models
Text/Visual Prompt models: - yoloe-11s-seg.pt, yoloe-11m-seg.pt, yoloe-11l-seg.pt - yoloe-v8s-seg.pt, yoloe-v8m-seg.pt, yoloe-v8l-seg.pt
Prompt-free models: - yoloe-11s-seg-pf.pt, yoloe-11m-seg-pf.pt, yoloe-11l-seg-pf.pt - yoloe-v8s-seg-pf.pt, yoloe-v8m-seg-pf.pt, yoloe-v8l-seg-pf.pt
Usage Text Prompts
from sahi import AutoDetectionModel
# Load YOLOE model
detection_model = AutoDetectionModel.from_pretrained(
model_type="yoloe",
model_path="yoloe-11l-seg.pt",
confidence_threshold=0.3,
device="cuda:0"
)
# Set text prompts for specific classes
detection_model.model.set_classes(
["person", "car", "traffic light"],
detection_model.model.get_text_pe(["person", "car", "traffic light"])
)
# Perform prediction
from sahi.predict import get_prediction
result = get_prediction("image.jpg", detection_model)
Usage for standard detection (no prompts)
from sahi import AutoDetectionModel
# Load YOLOE model (works like standard YOLO)
detection_model = AutoDetectionModel.from_pretrained(
model_type="yoloe",
model_path="yoloe-11l-seg.pt",
confidence_threshold=0.3,
device="cuda:0"
)
# Perform prediction without prompts (uses internal vocabulary)
from sahi.predict import get_sliced_prediction
result = get_sliced_prediction(
"image.jpg",
detection_model,
slice_height=512,
slice_width=512,
overlap_height_ratio=0.2,
overlap_width_ratio=0.2
)
Note
- YOLOE models perform instance segmentation by default
- When used without prompts, YOLOE performs like standard YOLO11 with identical speed
- For visual prompting, see Ultralytics YOLOE documentation
- YOLOE achieves +3.5 AP over YOLO-Worldv2 on LVIS with 1.4x faster inference
References
- Paper: https://arxiv.org/abs/2503.07465
- Docs: https://docs.ultralytics.com/models/yoloe/
- GitHub: https://github.com/THU-MIG/yoloe
Source code in sahi/models/yoloe.py
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 | |
load_model()
¶Loads the YOLOE detection model from the specified path.
Initializes the YOLOE model with the given model path or uses the default 'yoloe-11s-seg.pt' if no path is provided. The model is then moved to the specified device (CPU/GPU).
By default, YOLOE works in prompt-free mode using its internal vocabulary of 1200+ categories. To use text prompts for specific classes, call model.set_classes() after loading:
model.set_classes(["person", "car"], model.get_text_pe(["person", "car"]))
Raises:
| Type | Description |
|---|---|
TypeError
|
If the model_path is not a valid YOLOE model path or if the ultralytics package with YOLOE support is not installed. |
Source code in sahi/models/yoloe.py
yolov5
¶
Yolov5DetectionModel
¶
Bases: DetectionModel
Source code in sahi/models/yolov5.py
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
has_mask
property
¶Returns if model output contains segmentation mask.
num_categories
property
¶Returns number of categories.
load_model()
¶Detection model is initialized and set to self.model.
Source code in sahi/models/yolov5.py
perform_inference(image)
¶Prediction is performed using self.model and the prediction result is set to self._original_predictions.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
np.ndarray A numpy array that contains the image to be predicted. 3 channel image should be in RGB order. |
required |
Source code in sahi/models/yolov5.py
set_model(model)
¶Sets the underlying YOLOv5 model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model
¶ |
Any
|
Any A YOLOv5 model |
required |
Source code in sahi/models/yolov5.py
postprocess
¶
Modules¶
combine
¶
PostprocessPredictions
¶Utilities for calculating IOU/IOS based match for given ObjectPredictions.
Source code in sahi/postprocess/combine.py
batched_greedy_nmm(object_predictions_as_tensor, match_metric='IOU', match_threshold=0.5)
¶Apply greedy version of non-maximum merging per category to avoid detecting too many overlapping bounding boxes for a given object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_predictions_as_tensor
¶ |
tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns: keep_to_merge_list: (Dict[int:List[int]]) mapping from prediction indices to keep to a list of prediction indices to be merged.
Source code in sahi/postprocess/combine.py
batched_nmm(object_predictions_as_tensor, match_metric='IOU', match_threshold=0.5)
¶Apply non-maximum merging per category to avoid detecting too many overlapping bounding boxes for a given object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_predictions_as_tensor
¶ |
Tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns: keep_to_merge_list: (Dict[int:List[int]]) mapping from prediction indices to keep to a list of prediction indices to be merged.
Source code in sahi/postprocess/combine.py
batched_nms(predictions, match_metric='IOU', match_threshold=0.5)
¶Apply non-maximum suppression to avoid detecting too many overlapping bounding boxes for a given object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
¶ |
tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns: A list of filtered indexes, Shape: [ ,]
Source code in sahi/postprocess/combine.py
greedy_nmm(object_predictions_as_tensor, match_metric='IOU', match_threshold=0.5)
¶Optimized greedy non-maximum merging for axis-aligned bounding boxes using STRTree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_predictions_as_tensor
¶ |
Tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns: keep_to_merge_list: (dict[int, list[int]]) mapping from prediction indices to keep to a list of prediction indices to be merged.
Source code in sahi/postprocess/combine.py
178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 | |
nmm(object_predictions_as_tensor, match_metric='IOU', match_threshold=0.5)
¶Apply non-maximum merging to avoid detecting too many overlapping bounding boxes for a given object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_predictions_as_tensor
¶ |
Tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns: keep_to_merge_list: (Dict[int:List[int]]) mapping from prediction indices to keep to a list of prediction indices to be merged.
Source code in sahi/postprocess/combine.py
319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 | |
nms(predictions, match_metric='IOU', match_threshold=0.5)
¶Optimized non-maximum suppression for axis-aligned bounding boxes using STRTree.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
predictions
¶ |
Tensor
|
(tensor) The location preds for the image along with the class predscores, Shape: [num_boxes,5]. |
required |
match_metric
¶ |
str
|
(str) IOU or IOS |
'IOU'
|
match_threshold
¶ |
float
|
(float) The overlap thresh for match metric. |
0.5
|
Returns:
| Type | Description |
|---|---|
|
A list of filtered indexes, Shape: [ ,] |
Source code in sahi/postprocess/combine.py
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 | |
legacy
¶
combine
¶ PostprocessPredictions
¶Utilities for calculating IOU/IOS based match for given ObjectPredictions.
Source code in sahi/postprocess/legacy/combine.py
calculate_bbox_ios(pred1, pred2)
staticmethod
¶Returns the ratio of intersection area to the smaller box's area.
Source code in sahi/postprocess/legacy/combine.py
calculate_bbox_iou(pred1, pred2)
staticmethod
¶Returns the ratio of intersection area to the union.
Source code in sahi/postprocess/legacy/combine.py
utils
¶
calculate_area(box)
¶ calculate_bbox_ios(pred1, pred2)
¶Returns the ratio of intersection area to the smaller box's area.
Source code in sahi/postprocess/utils.py
calculate_bbox_iou(pred1, pred2)
¶Returns the ratio of intersection area to the union.
Source code in sahi/postprocess/utils.py
calculate_box_union(box1, box2)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box1
¶ |
List[int]
|
[x1, y1, x2, y2] |
required |
box2
¶ |
List[int]
|
[x1, y1, x2, y2] |
required |
Source code in sahi/postprocess/utils.py
calculate_intersection_area(box1, box2)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
box1
¶ |
ndarray
|
np.array([x1, y1, x2, y2]) |
required |
box2
¶ |
ndarray
|
np.array([x1, y1, x2, y2]) |
required |
Source code in sahi/postprocess/utils.py
coco_segmentation_to_shapely(segmentation)
¶Fix segment data in COCO format :param segmentation: segment data in COCO format :return:
Source code in sahi/postprocess/utils.py
object_prediction_list_to_numpy(object_prediction_list)
¶Returns:
| Type | Description |
|---|---|
ndarray
|
np.ndarray of size N x [x1, y1, x2, y2, score, category_id] |
Source code in sahi/postprocess/utils.py
object_prediction_list_to_torch(object_prediction_list)
¶Returns:
| Type | Description |
|---|---|
tensor
|
torch.tensor of size N x [x1, y1, x2, y2, score, category_id] |
Source code in sahi/postprocess/utils.py
repair_multipolygon(shapely_multipolygon)
¶Fix invalid MultiPolygon objects :param shapely_multipolygon: Imported shapely MultiPolygon object :return:
Source code in sahi/postprocess/utils.py
repair_polygon(shapely_polygon)
¶Fix polygons :param shapely_polygon: Shapely polygon object :return:
Source code in sahi/postprocess/utils.py
predict
¶
Classes¶
Functions¶
bbox_sort(a, b, thresh)
¶
a, b - function receives two bounding bboxes
thresh - the threshold takes into account how far two bounding bboxes differ in Y where thresh is the threshold we set for the minimum allowable difference in height between adjacent bboxes and sorts them by the X coordinate
Source code in sahi/predict.py
get_prediction(image, detection_model, shift_amount=None, full_shape=None, postprocess=None, verbose=0, exclude_classes_by_name=None, exclude_classes_by_id=None)
¶
Function for performing prediction for given image using given detection_model.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
str or np.ndarray Location of image or numpy image matrix to slice |
required | |
detection_model
¶ |
model.DetectionMode |
required | |
shift_amount
¶ |
list | None
|
List To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
None
|
full_shape
¶ |
List Size of the full image, should be in the form of [height, width] |
None
|
|
postprocess
¶ |
PostprocessPredictions | None
|
sahi.postprocess.combine.PostprocessPredictions |
None
|
verbose
¶ |
int
|
int 0: no print (default) 1: print prediction duration |
0
|
exclude_classes_by_name
¶ |
list[str] | None
|
Optional[List[str]] None: if no classes are excluded List[str]: set of classes to exclude using its/their class label name/s |
None
|
exclude_classes_by_id
¶ |
list[int] | None
|
Optional[List[int]] None: if no classes are excluded List[int]: set of classes to exclude using one or more IDs |
None
|
Returns: A dict with fields: object_prediction_list: a list of ObjectPrediction durations_in_seconds: a dict containing elapsed times for profiling
Source code in sahi/predict.py
get_sliced_prediction(image, detection_model=None, slice_height=None, slice_width=None, overlap_height_ratio=0.2, overlap_width_ratio=0.2, perform_standard_pred=True, postprocess_type='GREEDYNMM', postprocess_match_metric='IOS', postprocess_match_threshold=0.5, postprocess_class_agnostic=False, verbose=1, merge_buffer_length=None, auto_slice_resolution=True, slice_export_prefix=None, slice_dir=None, exclude_classes_by_name=None, exclude_classes_by_id=None, progress_bar=False, progress_callback=None)
¶
Function for slice image + get predicion for each slice + combine predictions in full image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
str or np.ndarray Location of image or numpy image matrix to slice |
required | |
detection_model
¶ |
model.DetectionModel |
None
|
|
slice_height
¶ |
int | None
|
int
Height of each slice. Defaults to |
None
|
slice_width
¶ |
int | None
|
int
Width of each slice. Defaults to |
None
|
overlap_height_ratio
¶ |
float
|
float
Fractional overlap in height of each window (e.g. an overlap of 0.2 for a window
of size 512 yields an overlap of 102 pixels).
Default to |
0.2
|
overlap_width_ratio
¶ |
float
|
float
Fractional overlap in width of each window (e.g. an overlap of 0.2 for a window
of size 512 yields an overlap of 102 pixels).
Default to |
0.2
|
perform_standard_pred
¶ |
bool
|
bool Perform a standard prediction on top of sliced predictions to increase large object detection accuracy. Default: True. |
True
|
postprocess_type
¶ |
str
|
str Type of the postprocess to be used after sliced inference while merging/eliminating predictions. Options are 'NMM', 'GREEDYNMM' or 'NMS'. Default is 'GREEDYNMM'. |
'GREEDYNMM'
|
postprocess_match_metric
¶ |
str
|
str Metric to be used during object prediction matching after sliced prediction. 'IOU' for intersection over union, 'IOS' for intersection over smaller area. |
'IOS'
|
postprocess_match_threshold
¶ |
float
|
float Sliced predictions having higher iou than postprocess_match_threshold will be postprocessed after sliced prediction. |
0.5
|
postprocess_class_agnostic
¶ |
bool
|
bool If True, postprocess will ignore category ids. |
False
|
verbose
¶ |
int
|
int 0: no print 1: print number of slices (default) 2: print number of slices and slice/prediction durations |
1
|
merge_buffer_length
¶ |
int | None
|
int The length of buffer for slices to be used during sliced prediction, which is suitable for low memory. It may affect the AP if it is specified. The higher the amount, the closer results to the non-buffered. scenario. See the discussion. |
None
|
auto_slice_resolution
¶ |
bool
|
bool if slice parameters (slice_height, slice_width) are not given, it enables automatically calculate these params from image resolution and orientation. |
True
|
slice_export_prefix
¶ |
str | None
|
str Prefix for the exported slices. Defaults to None. |
None
|
slice_dir
¶ |
str | None
|
str Directory to save the slices. Defaults to None. |
None
|
exclude_classes_by_name
¶ |
list[str] | None
|
Optional[List[str]] None: if no classes are excluded List[str]: set of classes to exclude using its/their class label name/s |
None
|
exclude_classes_by_id
¶ |
list[int] | None
|
Optional[List[int]] None: if no classes are excluded List[int]: set of classes to exclude using one or more IDs |
None
|
progress_bar
¶ |
bool
|
bool Whether to show progress bar for slice processing. Default: False. |
False
|
progress_callback
¶ |
callable A callback function that will be called after each slice is processed. The function should accept two arguments: (current_slice, total_slices) |
None
|
Returns: A Dict with fields: object_prediction_list: a list of sahi.prediction.ObjectPrediction durations_in_seconds: a dict containing elapsed times for profiling
Source code in sahi/predict.py
138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 | |
predict(detection_model=None, model_type='ultralytics', model_path=None, model_config_path=None, model_confidence_threshold=0.25, model_device=None, model_category_mapping=None, model_category_remapping=None, source=None, no_standard_prediction=False, no_sliced_prediction=False, image_size=None, slice_height=512, slice_width=512, overlap_height_ratio=0.2, overlap_width_ratio=0.2, postprocess_type='GREEDYNMM', postprocess_match_metric='IOS', postprocess_match_threshold=0.5, postprocess_class_agnostic=False, novisual=False, view_video=False, frame_skip_interval=0, export_pickle=False, export_crop=False, dataset_json_path=None, project='runs/predict', name='exp', visual_bbox_thickness=None, visual_text_size=None, visual_text_thickness=None, visual_hide_labels=False, visual_hide_conf=False, visual_export_format='png', verbose=1, return_dict=False, force_postprocess_type=False, exclude_classes_by_name=None, exclude_classes_by_id=None, progress_bar=False, **kwargs)
¶
Performs prediction for all present images in given folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
detection_model
¶ |
DetectionModel | None
|
sahi.model.DetectionModel Optionally provide custom DetectionModel to be used for inference. When provided, model_type, model_path, config_path, model_device, model_category_mapping, image_size params will be ignored |
None
|
model_type
¶ |
str
|
str mmdet for 'MmdetDetectionModel', 'yolov5' for 'Yolov5DetectionModel'. |
'ultralytics'
|
model_path
¶ |
str | None
|
str Path for the model weight |
None
|
model_config_path
¶ |
str | None
|
str Path for the detection model config file |
None
|
model_confidence_threshold
¶ |
float
|
float All predictions with score < model_confidence_threshold will be discarded. |
0.25
|
model_device
¶ |
str | None
|
str Torch device, "cpu" or "cuda" |
None
|
model_category_mapping
¶ |
dict | None
|
dict Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
model_category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids after performing inference |
None
|
source
¶ |
str | None
|
str Folder directory that contains images or path of the image to be predicted. Also video to be predicted. |
None
|
no_standard_prediction
¶ |
bool
|
bool Dont perform standard prediction. Default: False. |
False
|
no_sliced_prediction
¶ |
bool
|
bool Dont perform sliced prediction. Default: False. |
False
|
image_size
¶ |
int | None
|
int Input image size for each inference (image is scaled by preserving asp. rat.). |
None
|
slice_height
¶ |
int
|
int
Height of each slice. Defaults to |
512
|
slice_width
¶ |
int
|
int
Width of each slice. Defaults to |
512
|
overlap_height_ratio
¶ |
float
|
float
Fractional overlap in height of each window (e.g. an overlap of 0.2 for a window
of size 512 yields an overlap of 102 pixels).
Default to |
0.2
|
overlap_width_ratio
¶ |
float
|
float
Fractional overlap in width of each window (e.g. an overlap of 0.2 for a window
of size 512 yields an overlap of 102 pixels).
Default to |
0.2
|
postprocess_type
¶ |
str
|
str Type of the postprocess to be used after sliced inference while merging/eliminating predictions. Options are 'NMM', 'GREEDYNMM', 'LSNMS' or 'NMS'. Default is 'GREEDYNMM'. |
'GREEDYNMM'
|
postprocess_match_metric
¶ |
str
|
str Metric to be used during object prediction matching after sliced prediction. 'IOU' for intersection over union, 'IOS' for intersection over smaller area. |
'IOS'
|
postprocess_match_threshold
¶ |
float
|
float Sliced predictions having higher iou than postprocess_match_threshold will be postprocessed after sliced prediction. |
0.5
|
postprocess_class_agnostic
¶ |
bool
|
bool If True, postprocess will ignore category ids. |
False
|
novisual
¶ |
bool
|
bool Dont export predicted video/image visuals. |
False
|
view_video
¶ |
bool
|
bool View result of prediction during video inference. |
False
|
frame_skip_interval
¶ |
int
|
int If view_video or export_visual is slow, you can process one frames of 3(for exp: --frame_skip_interval=3). |
0
|
export_pickle
¶ |
bool
|
bool Export predictions as .pickle |
False
|
export_crop
¶ |
bool
|
bool Export predictions as cropped images. |
False
|
dataset_json_path
¶ |
str | None
|
str If coco file path is provided, detection results will be exported in coco json format. |
None
|
project
¶ |
str
|
str Save results to project/name. |
'runs/predict'
|
name
¶ |
str
|
str Save results to project/name. |
'exp'
|
visual_bbox_thickness
¶ |
int | None
|
int, optional Line thickness (in pixels) for bounding boxes in exported visualizations. If None, a default thickness is chosen based on image size. |
None
|
visual_text_size
¶ |
float | None
|
float, optional Font scale/size for label text in exported visualizations. If None, a sensible default is used. |
None
|
visual_text_thickness
¶ |
int | None
|
int, optional Thickness of text labels. If None, a sensible default is used. |
None
|
visual_hide_labels
¶ |
bool
|
bool, optional If True, class label names won't be shown on the exported visuals. |
False
|
visual_hide_conf
¶ |
bool
|
bool, optional If True, confidence scores won't be shown on the exported visuals. |
False
|
visual_export_format
¶ |
str
|
str, optional
Output image format to use when exporting visuals. Supported values are
'png' (default) and 'jpg'. Note that 'jpg' uses lossy compression and may
produce smaller files. This parameter is ignored when |
'png'
|
verbose
¶ |
int
|
int 0: no print 1: print slice/prediction durations, number of slices 2: print model loading/file exporting durations |
1
|
return_dict
¶ |
bool
|
bool If True, returns a dict with 'export_dir' field. |
False
|
force_postprocess_type
¶ |
bool
|
bool If True, auto postprocess check will e disabled |
False
|
exclude_classes_by_name
¶ |
list[str] | None
|
Optional[List[str]] None: if no classes are excluded List[str]: set of classes to exclude using its/their class label name/s |
None
|
exclude_classes_by_id
¶ |
list[int] | None
|
Optional[List[int]] None: if no classes are excluded List[int]: set of classes to exclude using one or more IDs |
None
|
progress_bar
¶ |
bool
|
bool Whether to show a progress bar. Default is False. |
False
|
Source code in sahi/predict.py
397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 | |
predict_fiftyone(model_type='mmdet', model_path=None, model_config_path=None, model_confidence_threshold=0.25, model_device=None, model_category_mapping=None, model_category_remapping=None, dataset_json_path='', image_dir='', no_standard_prediction=False, no_sliced_prediction=False, image_size=None, slice_height=256, slice_width=256, overlap_height_ratio=0.2, overlap_width_ratio=0.2, postprocess_type='GREEDYNMM', postprocess_match_metric='IOS', postprocess_match_threshold=0.5, postprocess_class_agnostic=False, verbose=1, exclude_classes_by_name=None, exclude_classes_by_id=None, progress_bar=False)
¶
Performs prediction for all present images in given folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
¶ |
str
|
str mmdet for 'MmdetDetectionModel', 'yolov5' for 'Yolov5DetectionModel'. |
'mmdet'
|
model_path
¶ |
str | None
|
str Path for the model weight |
None
|
model_config_path
¶ |
str | None
|
str Path for the detection model config file |
None
|
model_confidence_threshold
¶ |
float
|
float All predictions with score < model_confidence_threshold will be discarded. |
0.25
|
model_device
¶ |
str | None
|
str Torch device, "cpu" or "cuda" |
None
|
model_category_mapping
¶ |
dict | None
|
dict Mapping from category id (str) to category name (str) e.g. {"1": "pedestrian"} |
None
|
model_category_remapping
¶ |
dict | None
|
dict: str to int Remap category ids after performing inference |
None
|
dataset_json_path
¶ |
str
|
str If coco file path is provided, detection results will be exported in coco json format. |
''
|
image_dir
¶ |
str
|
str Folder directory that contains images or path of the image to be predicted. |
''
|
no_standard_prediction
¶ |
bool
|
bool Dont perform standard prediction. Default: False. |
False
|
no_sliced_prediction
¶ |
bool
|
bool Dont perform sliced prediction. Default: False. |
False
|
image_size
¶ |
int | None
|
int Input image size for each inference (image is scaled by preserving asp. rat.). |
None
|
slice_height
¶ |
int
|
int
Height of each slice. Defaults to |
256
|
slice_width
¶ |
int
|
int
Width of each slice. Defaults to |
256
|
overlap_height_ratio
¶ |
float
|
float
Fractional overlap in height of each window (e.g. an overlap of 0.2 for a window
of size 256 yields an overlap of 51 pixels).
Default to |
0.2
|
overlap_width_ratio
¶ |
float
|
float
Fractional overlap in width of each window (e.g. an overlap of 0.2 for a window
of size 256 yields an overlap of 51 pixels).
Default to |
0.2
|
postprocess_type
¶ |
str
|
str Type of the postprocess to be used after sliced inference while merging/eliminating predictions. Options are 'NMM', 'GREEDYNMM' or 'NMS'. Default is 'GREEDYNMM'. |
'GREEDYNMM'
|
postprocess_match_metric
¶ |
str
|
str Metric to be used during object prediction matching after sliced prediction. 'IOU' for intersection over union, 'IOS' for intersection over smaller area. |
'IOS'
|
postprocess_match_metric
¶ |
str
|
str Metric to be used during object prediction matching after sliced prediction. 'IOU' for intersection over union, 'IOS' for intersection over smaller area. |
'IOS'
|
postprocess_match_threshold
¶ |
float
|
float Sliced predictions having higher iou than postprocess_match_threshold will be postprocessed after sliced prediction. |
0.5
|
postprocess_class_agnostic
¶ |
bool
|
bool If True, postprocess will ignore category ids. |
False
|
verbose
¶ |
int
|
int 0: no print 1: print slice/prediction durations, number of slices, model loading/file exporting durations |
1
|
exclude_classes_by_name
¶ |
list[str] | None
|
Optional[List[str]] None: if no classes are excluded List[str]: set of classes to exclude using its/their class label name/s |
None
|
exclude_classes_by_id
¶ |
list[int] | None
|
Optional[List[int]] None: if no classes are excluded List[int]: set of classes to exclude using one or more IDs |
None
|
progress_bar
¶ |
bool
|
bool Whether to show progress bar for slice processing. Default: False. |
False
|
Source code in sahi/predict.py
814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 | |
prediction
¶
Classes¶
ObjectPrediction
¶
Bases: ObjectAnnotation
Class for handling detection model predictions.
Source code in sahi/prediction.py
44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 | |
__init__(bbox=None, category_id=None, category_name=None, segmentation=None, score=0.0, shift_amount=[0, 0], full_shape=None)
¶Creates ObjectPrediction from bbox, score, category_id, category_name, segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
list[int] | None
|
list [minx, miny, maxx, maxy] |
None
|
score
¶ |
float
|
float Prediction score between 0 and 1 |
0.0
|
category_id
¶ |
int | None
|
int ID of the object category |
None
|
category_name
¶ |
str | None
|
str Name of the object category |
None
|
segmentation
¶ |
list[list[float]] | None
|
List[List] [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ] |
None
|
shift_amount
¶ |
list[int] | None
|
list To shift the box and mask predictions from sliced image to full sized image, should be in the form of [shift_x, shift_y] |
[0, 0]
|
full_shape
¶ |
list[int] | None
|
list Size of the full image after shifting, should be in the form of [height, width] |
None
|
Source code in sahi/prediction.py
get_shifted_object_prediction()
¶Returns shifted version ObjectPrediction.
Shifts bbox and mask coords. Used for mapping sliced predictions over full image.
Source code in sahi/prediction.py
to_coco_prediction(image_id=None)
¶Returns sahi.utils.coco.CocoPrediction representation of ObjectAnnotation.
Source code in sahi/prediction.py
to_fiftyone_detection(image_height, image_width)
¶Returns fiftyone.Detection representation of ObjectPrediction.
Source code in sahi/prediction.py
PredictionResult
¶
Source code in sahi/prediction.py
158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 | |
export_visuals(export_dir, text_size=None, rect_th=None, hide_labels=False, hide_conf=False, file_name='prediction_visual')
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
export_dir
¶ |
str
|
directory for resulting visualization to be exported |
required |
text_size
¶ |
float | None
|
size of the category name over box |
None
|
rect_th
¶ |
int | None
|
rectangle thickness |
None
|
hide_labels
¶ |
bool
|
hide labels |
False
|
hide_conf
¶ |
bool
|
hide confidence |
False
|
file_name
¶ |
str
|
saving name |
'prediction_visual'
|
Returns:
Source code in sahi/prediction.py
PredictionScore
¶
Source code in sahi/prediction.py
Functions¶
scripts
¶
Modules¶
coco2fiftyone
¶
main(image_dir, dataset_json_path, *result_json_paths, iou_thresh=0.5)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_dir
¶ |
str
|
directory for coco images |
required |
dataset_json_path
¶ |
str
|
file path for the coco dataset json file |
required |
result_json_paths
¶ |
str
|
one or more paths for the coco result json file |
()
|
iou_thresh
¶ |
float
|
iou threshold for coco evaluation |
0.5
|
Source code in sahi/scripts/coco2fiftyone.py
coco2yolo
¶
main(image_dir, dataset_json_path, train_split=0.9, project='runs/coco2yolo', name='exp', seed=1, disable_symlink=False)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
images_dir
¶ |
str
|
directory for coco images |
required |
dataset_json_path
¶ |
str
|
file path for the coco json file to be converted |
required |
train_split
¶ |
float or int
|
set the training split ratio |
0.9
|
project
¶ |
str
|
save results to project/name |
'runs/coco2yolo'
|
name
¶ |
str
|
save results to project/name" |
'exp'
|
seed
¶ |
int
|
fix the seed for reproducibility |
1
|
disable_symlink
¶ |
bool
|
required in google colab env |
False
|
Source code in sahi/scripts/coco2yolo.py
coco_error_analysis
¶
analyse(dataset_json_path, result_json_path, out_dir=None, type='bbox', no_extraplots=False, areas=[1024, 9216, 10000000000], max_detections=500, return_dict=False)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_json_path
¶ |
str
|
file path for the coco dataset json file |
required |
result_json_paths
¶ |
str
|
file path for the coco result json file |
required |
out_dir
¶ |
str
|
dir to save analyse result images |
None
|
no_extraplots
¶ |
bool
|
dont export export extra bar/stat plots |
False
|
type
¶ |
str
|
'bbox' or 'mask' |
'bbox'
|
areas
¶ |
List[int]
|
area regions for coco evaluation calculations |
[1024, 9216, 10000000000]
|
max_detections
¶ |
int
|
Maximum number of detections to consider for AP alculation. Default: 500 |
500
|
return_dict
¶ |
bool
|
If True, returns a dict export paths. |
False
|
Source code in sahi/scripts/coco_error_analysis.py
coco_evaluation
¶
evaluate(dataset_json_path, result_json_path, out_dir=None, type='bbox', classwise=False, max_detections=500, iou_thrs=None, areas=[1024, 9216, 10000000000], return_dict=False)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_json_path
¶ |
str
|
file path for the coco dataset json file |
required |
result_json_path
¶ |
str
|
file path for the coco result json file |
required |
out_dir
¶ |
str
|
dir to save eval result |
None
|
type
¶ |
bool
|
'bbox' or 'segm' |
'bbox'
|
classwise
¶ |
bool
|
whether to evaluate the AP for each class |
False
|
max_detections
¶ |
int
|
Maximum number of detections to consider for AP alculation. Default: 500 |
500
|
iou_thrs
¶ |
float
|
IoU threshold used for evaluating recalls/mAPs |
None
|
areas
¶ |
List[int]
|
area regions for coco evaluation calculations |
[1024, 9216, 10000000000]
|
return_dict
¶ |
bool
|
If True, returns a dict with 'eval_results' 'export_path' fields. |
False
|
Source code in sahi/scripts/coco_evaluation.py
evaluate_core(dataset_path, result_path, COCO, COCOeval, metric='bbox', classwise=False, max_detections=500, iou_thrs=None, metric_items=None, out_dir=None, areas=[1024, 9216, 10000000000])
¶Evaluation in COCO protocol.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
dataset_path
¶ |
str
|
COCO dataset json path. |
required |
result_path
¶ |
str
|
COCO result json path. |
required |
COCO, COCOeval
¶ |
Pass COCO and COCOeval class after safely imported |
required | |
metric
¶ |
str | list[str]
|
Metrics to be evaluated. Options are 'bbox', 'segm', 'proposal'. |
'bbox'
|
classwise
¶ |
bool
|
Whether to evaluating the AP for each class. |
False
|
max_detections
¶ |
int
|
Maximum number of detections to consider for AP calculation. Default: 500 |
500
|
iou_thrs
¶ |
List[float]
|
IoU threshold used for evaluating recalls/mAPs. If set to a list, the average of all IoUs will also be computed. If not specified, [0.50, 0.55, 0.60, 0.65, 0.70, 0.75, 0.80, 0.85, 0.90, 0.95] will be used. Default: None. |
None
|
metric_items
¶ |
list[str] | str
|
Metric items that will
be returned. If not specified, |
None
|
out_dir
¶ |
str
|
Directory to save evaluation result json. |
None
|
areas
¶ |
List[int]
|
area regions for coco evaluation calculations |
[1024, 9216, 10000000000]
|
Returns: dict: eval_results (dict[str, float]): COCO style evaluation metric. export_path (str): Path for the exported eval result json.
Source code in sahi/scripts/coco_evaluation.py
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 | |
slice_coco
¶
slicer(image_dir, dataset_json_path, slice_size=512, overlap_ratio=0.2, ignore_negative_samples=False, output_dir='runs/slice_coco', min_area_ratio=0.1)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_dir
¶ |
str
|
directory for coco images |
required |
dataset_json_path
¶ |
str
|
file path for the coco dataset json file |
required |
overlap_ratio
¶ |
float
|
slice overlap ratio |
0.2
|
ignore_negative_samples
¶ |
bool
|
ignore images without annotation |
False
|
output_dir
¶ |
str
|
output export dir |
'runs/slice_coco'
|
min_area_ratio
¶ |
float
|
If the cropped annotation area to original annotation ratio is smaller than this value, the annotation is filtered out. Default 0.1. |
0.1
|
Source code in sahi/scripts/slice_coco.py
slicing
¶
Classes¶
SliceImageResult
¶
Source code in sahi/slicing.py
164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 | |
coco_images
property
¶Returns CocoImage representation of SliceImageResult.
Returns:
| Name | Type | Description |
|---|---|---|
coco_images |
list[CocoImage]
|
a list of CocoImage |
filenames
property
¶Returns a list of filenames for each slice.
Returns:
| Name | Type | Description |
|---|---|---|
filenames |
list[int]
|
a list of filenames as str |
images
property
¶Returns sliced images.
Returns:
| Name | Type | Description |
|---|---|---|
images |
a list of np.array |
starting_pixels
property
¶Returns a list of starting pixels for each slice.
Returns:
| Name | Type | Description |
|---|---|---|
starting_pixels |
list[int]
|
a list of starting pixel coords [x,y] |
__init__(original_image_size, image_dir=None)
¶str
Directory of the sliced image exports.
original_image_size: list of int Size of the unsliced original image in [height, width]
Source code in sahi/slicing.py
SlicedImage
¶
Source code in sahi/slicing.py
__init__(image, coco_image, starting_pixel)
¶np.array
Sliced image.
coco_image: CocoImage Coco styled image object that belong to sliced image. starting_pixel: list of list of int Starting pixel coordinates of the sliced image.
Source code in sahi/slicing.py
Functions¶
annotation_inside_slice(annotation, slice_bbox)
¶
Check whether annotation coordinates lie inside slice coordinates.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
annotation
¶ |
dict
|
Single annotation entry in COCO format. |
required |
slice_bbox
¶ |
List[int]
|
Generated from |
required |
Returns:
| Type | Description |
|---|---|
bool
|
True if any annotation coordinate lies inside slice. |
Source code in sahi/slicing.py
calc_aspect_ratio_orientation(width, height)
¶
calc_ratio_and_slice(orientation, slide=1, ratio=0.1)
¶
According to image resolution calculation overlap params Args: orientation: image capture angle slide: sliding window ratio: buffer value
Returns:
| Type | Description |
|---|---|
|
overlap params |
Source code in sahi/slicing.py
calc_resolution_factor(resolution)
¶
According to image resolution calculate power(2,n) and return the closest smaller n.
Args:
resolution: the width and height of the image multiplied. such as 1024x720 = 737280
Returns:
Source code in sahi/slicing.py
calc_slice_and_overlap_params(resolution, height, width, orientation)
¶
This function calculate according to image resolution slice and overlap params. Args: resolution: str height: int width: int orientation: str
Returns:
| Type | Description |
|---|---|
tuple[int, int, int, int]
|
x_overlap, y_overlap, slice_width, slice_height |
Source code in sahi/slicing.py
get_auto_slice_params(height, width)
¶
According to Image HxW calculate overlap sliding window and buffer params factor is the power value of 2 closest to the image resolution. factor <= 18: low resolution image such as 300x300, 640x640 18 < factor <= 21: medium resolution image such as 1024x1024, 1336x960 21 < factor <= 24: high resolution image such as 2048x2048, 2048x4096, 4096x4096 factor > 24: ultra-high resolution image such as 6380x6380, 4096x8192 Args: height: width:
Returns:
| Type | Description |
|---|---|
tuple[int, int, int, int]
|
slicing overlap params x_overlap, y_overlap, slice_width, slice_height |
Source code in sahi/slicing.py
get_resolution_selector(res, height, width)
¶
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
res
¶ |
str
|
resolution of image such as low, medium |
required |
height
¶ |
int
|
|
required |
width
¶ |
int
|
|
required |
Returns:
| Type | Description |
|---|---|
tuple[int, int, int, int]
|
trigger slicing params function and return overlap params |
Source code in sahi/slicing.py
get_slice_bboxes(image_height, image_width, slice_height=None, slice_width=None, auto_slice_resolution=True, overlap_height_ratio=0.2, overlap_width_ratio=0.2)
¶
Generate bounding boxes for slicing an image into crops.
The function calculates the coordinates for each slice based on the provided image dimensions, slice size, and overlap ratios. If slice size is not provided and auto_slice_resolution is True, the function will automatically determine appropriate slice parameters.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_height
¶ |
int
|
Height of the original image. |
required |
image_width
¶ |
int
|
Width of the original image. |
required |
slice_height
¶ |
int
|
Height of each slice. Default None. |
None
|
slice_width
¶ |
int
|
Width of each slice. Default None. |
None
|
overlap_height_ratio
¶ |
float
|
Fractional overlap in height of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
overlap_width_ratio
¶ |
float
|
Fractional overlap in width of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
auto_slice_resolution
¶ |
bool
|
if not set slice parameters such as slice_height and slice_width, it enables automatically calculate these parameters from image resolution and orientation. |
True
|
Returns:
| Type | Description |
|---|---|
list[list[int]]
|
List[List[int]]: List of 4 corner coordinates for each N slices. [ [slice_0_left, slice_0_top, slice_0_right, slice_0_bottom], ... [slice_N_left, slice_N_top, slice_N_right, slice_N_bottom] ] |
Source code in sahi/slicing.py
process_coco_annotations(coco_annotation_list, slice_bbox, min_area_ratio)
¶
Slices and filters given list of CocoAnnotation objects with given 'slice_bbox' and 'min_area_ratio'.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
slice_bbox
¶ |
List[int]
|
Generated from |
required |
min_area_ratio
¶ |
float
|
If the cropped annotation area to original annotation ratio is smaller than this value, the annotation is filtered out. Default 0.1. |
required |
Returns:
| Type | Description |
|---|---|
List[CocoAnnotation]
|
Sliced annotations. |
Source code in sahi/slicing.py
shift_bboxes(bboxes, offset)
¶
Shift bboxes w.r.t offset.
Suppo
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bboxes
¶ |
(Tensor, ndarray, list)
|
The bboxes need to be translated. Its shape can be (n, 4), which means (x, y, x, y). |
required |
offset
¶ |
Sequence[int]
|
The translation offsets with shape of (2, ). |
required |
Returns: Tensor, np.ndarray, list: Shifted bboxes.
Source code in sahi/slicing.py
shift_masks(masks, offset, full_shape)
¶
Shift masks to the original image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
masks
¶ |
ndarray
|
masks that need to be shifted. |
required |
offset
¶ |
Sequence[int]
|
The offset to translate with shape of (2, ). |
required |
full_shape
¶ |
Sequence[int]
|
A (height, width) tuple of the huge image's shape. |
required |
Returns: np.ndarray: Shifted masks.
Source code in sahi/slicing.py
slice_coco(coco_annotation_file_path, image_dir, output_coco_annotation_file_name, output_dir=None, ignore_negative_samples=False, slice_height=512, slice_width=512, overlap_height_ratio=0.2, overlap_width_ratio=0.2, min_area_ratio=0.1, out_ext=None, verbose=False, exif_fix=True)
¶
Slice large images given in a directory, into smaller windows. If output_dir is given, export sliced images and coco file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_annotation_file_path
¶ |
str
|
Location of the coco annotation file |
required |
image_dir
¶ |
str
|
Base directory for the images |
required |
output_coco_annotation_file_name
¶ |
str
|
File name of the exported coco dataset json. |
required |
output_dir
¶ |
str
|
Output directory |
None
|
ignore_negative_samples
¶ |
bool
|
If True, images without annotations are ignored. Defaults to False. |
False
|
slice_height
¶ |
int
|
Height of each slice. Default 512. |
512
|
slice_width
¶ |
int
|
Width of each slice. Default 512. |
512
|
overlap_height_ratio
¶ |
float
|
Fractional overlap in height of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
overlap_width_ratio
¶ |
float
|
Fractional overlap in width of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
min_area_ratio
¶ |
float
|
If the cropped annotation area to original annotation ratio is smaller than this value, the annotation is filtered out. Default 0.1. |
0.1
|
out_ext
¶ |
str
|
Extension of saved images. Default is the original suffix. |
None
|
verbose
¶ |
bool
|
Switch to print relevant values to screen. |
False
|
exif_fix
¶ |
bool
|
Whether to apply an EXIF fix to the image. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
coco_dict |
list[dict | str]
|
dict COCO dict for sliced images and annotations |
save_path |
list[dict | str]
|
str Path to the saved coco file |
Source code in sahi/slicing.py
418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 | |
slice_image(image, coco_annotation_list=None, output_file_name=None, output_dir=None, slice_height=None, slice_width=None, overlap_height_ratio=0.2, overlap_width_ratio=0.2, auto_slice_resolution=True, min_area_ratio=0.1, out_ext=None, verbose=False, exif_fix=True)
¶
Slice a large image into smaller windows. If output_file_name and output_dir is given, export sliced images.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
str or Image
|
File path of image or Pillow Image to be sliced. |
required |
coco_annotation_list
¶ |
List[CocoAnnotation]
|
List of CocoAnnotation objects. |
None
|
output_file_name
¶ |
str
|
Root name of output files (coordinates will be appended to this) |
None
|
output_dir
¶ |
str
|
Output directory |
None
|
slice_height
¶ |
int
|
Height of each slice. Default None. |
None
|
slice_width
¶ |
int
|
Width of each slice. Default None. |
None
|
overlap_height_ratio
¶ |
float
|
Fractional overlap in height of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
overlap_width_ratio
¶ |
float
|
Fractional overlap in width of each slice (e.g. an overlap of 0.2 for a slice of size 100 yields an overlap of 20 pixels). Default 0.2. |
0.2
|
auto_slice_resolution
¶ |
bool
|
if not set slice parameters such as slice_height and slice_width, it enables automatically calculate these params from image resolution and orientation. |
True
|
min_area_ratio
¶ |
float
|
If the cropped annotation area to original annotation ratio is smaller than this value, the annotation is filtered out. Default 0.1. |
0.1
|
out_ext
¶ |
str
|
Extension of saved images. Default is the original suffix for lossless image formats and png for lossy formats ('.jpg','.jpeg'). |
None
|
verbose
¶ |
bool
|
Switch to print relevant values to screen. Default 'False'. |
False
|
exif_fix
¶ |
bool
|
Whether to apply an EXIF fix to the image. |
True
|
Returns:
| Name | Type | Description |
|---|---|---|
sliced_image_result |
SliceImageResult
|
SliceImageResult: sliced_image_list: list of SlicedImage image_dir: str Directory of the sliced image exports. original_image_size: list of int Size of the unsliced original image in [height, width] |
Source code in sahi/slicing.py
263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 | |
utils
¶
Modules¶
coco
¶
Coco
¶Source code in sahi/utils/coco.py
761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 | |
__init__(name=None, image_dir=None, remapping_dict=None, ignore_negative_samples=False, clip_bboxes_to_img_dims=False, image_id_setting='auto')
¶Creates Coco object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
¶ |
str | None
|
str Name of the Coco dataset, it determines exported json name. |
None
|
image_dir
¶ |
str | None
|
str Base file directory that contains dataset images. Required for dataset merging. |
None
|
remapping_dict
¶ |
dict[int, int] | None
|
dict {1:0, 2:1} maps category id 1 to 0 and category id 2 to 1 |
None
|
ignore_negative_samples
¶ |
bool
|
bool If True ignores images without annotations in all operations. |
False
|
image_id_setting
¶ |
Literal['auto', 'manual']
|
str
how to assign image ids while exporting can be
auto -> will assign id from scratch ( |
'auto'
|
Source code in sahi/utils/coco.py
add_categories_from_coco_category_list(coco_category_list)
¶Creates CocoCategory object using coco category list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_category_list
¶ |
List[Dict] [ {"supercategory": "person", "id": 1, "name": "person"}, {"supercategory": "vehicle", "id": 2, "name": "bicycle"} ] |
required |
Source code in sahi/utils/coco.py
add_category(category)
¶Adds category to this Coco instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
¶ |
CocoCategory |
required |
Source code in sahi/utils/coco.py
add_image(image)
¶Adds image to this Coco instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
CocoImage |
required |
Source code in sahi/utils/coco.py
calculate_stats()
¶Iterates over all annotations and calculates total number of.
Source code in sahi/utils/coco.py
1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 | |
export_as_yolo(output_dir, train_split_rate=1.0, numpy_seed=0, mp=False, disable_symlink=False)
¶Exports current COCO dataset in ultralytics/yolo format. Creates train val folders with image symlinks and txt files and a data yaml file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
¶ |
str | Path
|
str Export directory. |
required |
train_split_rate
¶ |
float
|
float If given 1, will be exported as train split. If given 0, will be exported as val split. If in between 0-1, both train/val splits will be calculated and exported. |
1.0
|
numpy_seed
¶ |
int
|
int To fix the numpy seed. |
0
|
mp
¶ |
bool
|
bool If True, multiprocess mode is on. Should be called in 'if name == main:' block. |
False
|
disable_symlink
¶ |
bool
|
bool If True, symlinks will not be created. Instead, images will be copied. |
False
|
Source code in sahi/utils/coco.py
1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 | |
export_as_yolov5(output_dir, train_split_rate=1.0, numpy_seed=0, mp=False, disable_symlink=False)
¶Deprecated.
Please use export_as_yolo instead. Calls export_as_yolo with the same arguments.
Source code in sahi/utils/coco.py
from_coco_dict_or_path(coco_dict_or_path, image_dir=None, remapping_dict=None, ignore_negative_samples=False, clip_bboxes_to_img_dims=False, use_threads=False, num_threads=10)
classmethod
¶Creates coco object from COCO formatted dict or COCO dataset file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_dict_or_path
¶ |
dict | str
|
dict/str or List[dict/str] COCO formatted dict or COCO dataset file path List of COCO formatted dict or COCO dataset file path |
required |
image_dir
¶ |
str | None
|
str Base file directory that contains dataset images. Required for merging and yolov5 conversion. |
None
|
remapping_dict
¶ |
dict | None
|
dict {1:0, 2:1} maps category id 1 to 0 and category id 2 to 1 |
None
|
ignore_negative_samples
¶ |
bool
|
bool If True ignores images without annotations in all operations. |
False
|
clip_bboxes_to_img_dims
¶ |
bool
|
bool = False Limits bounding boxes to image dimensions. |
False
|
use_threads
¶ |
bool
|
bool = False Use threads when processing the json image list, defaults to False |
False
|
num_threads
¶ |
int
|
int = 10 Slice the image list to given number of chunks, defaults to 10 |
10
|
Properties
images: list of CocoImage category_mapping: dict
Source code in sahi/utils/coco.py
951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 | |
get_area_filtered_coco(min=0, max_val=float('inf'), intervals_per_category=None)
¶Filters annotation areas with given min and max values and returns remaining images as sahi.utils.coco.Coco object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
min
¶ |
int minimum allowed area |
0
|
|
max_val
¶ |
int maximum allowed area |
float('inf')
|
|
intervals_per_category
¶ |
dict of dicts { "human": {"min": 20, "max": 10000}, "vehicle": {"min": 50, "max": 15000}, } |
None
|
Returns: area_filtered_coco: sahi.utils.coco.Coco
Source code in sahi/utils/coco.py
get_coco_with_clipped_bboxes()
¶Limits overflowing bounding boxes to image dimensions.
Source code in sahi/utils/coco.py
get_subsampled_coco(subsample_ratio=2, category_id=None)
¶Subsamples images with subsample_ratio and returns as sahi.utils.coco.Coco object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
subsample_ratio
¶ |
int
|
int 10 means take every 10th image with its annotations |
2
|
category_id
¶ |
int | None
|
int subsample only images containing given category_id, if -1 then subsamples negative samples |
None
|
Returns: subsampled_coco: sahi.utils.coco.Coco
Source code in sahi/utils/coco.py
1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 | |
get_upsampled_coco(upsample_ratio=2, category_id=None)
¶Upsamples images with upsample_ratio and returns as sahi.utils.coco.Coco object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
upsample_ratio
¶ |
int
|
int 10 means copy each sample 10 times |
2
|
category_id
¶ |
int | None
|
int upsample only images containing given category_id, if -1 then upsamples negative samples |
None
|
Returns: upsampled_coco: sahi.utils.coco.Coco
Source code in sahi/utils/coco.py
merge(coco, desired_name2id=None, verbose=1)
¶Combines the images/annotations/categories of given coco object with current one.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco
¶ |
sahi.utils.coco.Coco instance A COCO dataset object |
required | |
desired_name2id
¶ |
dict |
required | |
verbose
¶ |
bool If True, merging info is printed |
1
|
Source code in sahi/utils/coco.py
split_coco_as_train_val(train_split_rate=0.9, numpy_seed=0)
¶Split images into train-val and returns them as sahi.utils.coco.Coco objects.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
train_split_rate
¶ |
float |
0.9
|
|
numpy_seed
¶ |
int random seed. Actually, this doesn't use numpy, but the random package from the standard library, but it is called numpy for compatibility. |
0
|
Returns:
| Name | Type | Description |
|---|---|---|
result |
dict { "train_coco": "", "val_coco": "", } |
Source code in sahi/utils/coco.py
update_categories(desired_name2id, update_image_filenames=False)
¶Rearranges category mapping of given COCO object based on given desired_name2id. Can also be used to filter some of the categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
desired_name2id
¶ |
dict[str, int]
|
dict |
required |
update_image_filenames
¶ |
bool
|
bool If True, updates coco image file_names with absolute file paths. |
False
|
Source code in sahi/utils/coco.py
CocoAnnotation
¶COCO formatted annotation.
Source code in sahi/utils/coco.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 | |
area
property
¶Returns area of annotation polygon (or bbox if no polygon available)
bbox
property
¶Returns coco formatted bbox of the annotation as [xmin, ymin, width, height]
category_id
property
writable
¶Returns category id of the annotation as int.
category_name
property
writable
¶Returns category name of the annotation as str.
image_id
property
writable
¶Returns image id of the annotation as int.
iscrowd
property
¶Returns iscrowd info of the annotation.
segmentation
property
¶Returns coco formatted segmentation of the annotation as [[1, 1, 325, 125, 250, 200, 5, 200]]
__init__(category_id, category_name=None, segmentation=None, bbox=None, image_id=None, iscrowd=0)
¶Creates coco annotation object using bbox or segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List][[1, 1, 325, 125, 250, 200, 5, 200]] |
None
|
|
bbox
¶ |
list[int] | None
|
List [xmin, ymin, width, height] |
None
|
category_id
¶ |
int
|
int Category id of the annotation |
required |
category_name
¶ |
str | None
|
str Category name of the annotation |
None
|
image_id
¶ |
int Image ID of the annotation |
None
|
|
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
from_coco_annotation_dict(annotation_dict, category_name=None)
classmethod
¶Creates CocoAnnotation object from category name and COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_name
¶ |
str | None
|
str Category name of the annotation |
None
|
annotation_dict
¶ |
dict
|
dict COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id") |
required |
Source code in sahi/utils/coco.py
from_coco_bbox(bbox, category_id, category_name, iscrowd=0)
classmethod
¶Creates CocoAnnotation object using coco bbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
List [xmin, ymin, width, height] |
required | |
category_id
¶ |
int Category id of the annotation |
required | |
category_name
¶ |
str Category name of the annotation |
required | |
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
from_coco_segmentation(segmentation, category_id, category_name, iscrowd=0)
classmethod
¶Creates CocoAnnotation object using coco segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List][[1, 1, 325, 125, 250, 200, 5, 200]] |
required | |
category_id
¶ |
int Category id of the annotation |
required | |
category_name
¶ |
str Category name of the annotation |
required | |
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
from_shapely_annotation(shapely_annotation, category_id, category_name, iscrowd)
classmethod
¶Creates CocoAnnotation object from ShapelyAnnotation object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_id
¶ |
int
|
Category id of the annotation |
required |
category_name
¶ |
str
|
Category name of the annotation |
required |
iscrowd
¶ |
int
|
0 or 1 |
required |
Source code in sahi/utils/coco.py
CocoCategory
¶COCO formatted category.
Source code in sahi/utils/coco.py
from_coco_category(category)
classmethod
¶Creates CocoCategory object using coco category.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
¶ |
Dict {"supercategory": "person", "id": 1, "name": "person"}, |
required |
Source code in sahi/utils/coco.py
CocoImage
¶Source code in sahi/utils/coco.py
__init__(file_name, height, width, id=None)
¶Creates CocoImage object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
¶ |
int Image id |
required | |
file_name
¶ |
str Image path |
required | |
height
¶ |
int Image height in pixels |
required | |
width
¶ |
int Image width in pixels |
required |
Source code in sahi/utils/coco.py
add_annotation(annotation)
¶Adds annotation to this CocoImage instance.
annotation : CocoAnnotation
Source code in sahi/utils/coco.py
add_prediction(prediction)
¶Adds prediction to this CocoImage instance.
prediction : CocoPrediction
Source code in sahi/utils/coco.py
from_coco_image_dict(image_dict)
classmethod
¶Creates CocoImage object from COCO formatted image dict (with fields "id", "file_name", "height" and "weight").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_dict
¶ |
dict COCO formatted image dict (with fields "id", "file_name", "height" and "weight") |
required |
Source code in sahi/utils/coco.py
CocoPrediction
¶
Bases: CocoAnnotation
Class for handling predictions in coco format.
Source code in sahi/utils/coco.py
303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 | |
__init__(segmentation=None, bbox=None, category_id=0, category_name='', image_id=None, score=None, iscrowd=0)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List][[1, 1, 325, 125, 250, 200, 5, 200]] |
None
|
|
bbox
¶ |
List [xmin, ymin, width, height] |
None
|
|
category_id
¶ |
int
|
int Category id of the annotation |
0
|
category_name
¶ |
str
|
str Category name of the annotation |
''
|
image_id
¶ |
int Image ID of the annotation |
None
|
|
score
¶ |
float Prediction score between 0 and 1 |
None
|
|
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
from_coco_annotation_dict(category_name, annotation_dict, score, image_id=None)
classmethod
¶Creates CocoAnnotation object from category name and COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id").
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category_name
¶ |
str Category name of the annotation |
required | |
annotation_dict
¶ |
dict COCO formatted annotation dict (with fields "bbox", "segmentation", "category_id") |
required | |
score
¶ |
float Prediction score between 0 and 1 |
required |
Source code in sahi/utils/coco.py
from_coco_bbox(bbox, category_id, category_name, score, iscrowd=0, image_id=None)
classmethod
¶Creates CocoAnnotation object using coco bbox.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
List [xmin, ymin, width, height] |
required | |
category_id
¶ |
int Category id of the annotation |
required | |
category_name
¶ |
str Category name of the annotation |
required | |
score
¶ |
float Prediction score between 0 and 1 |
required | |
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
from_coco_segmentation(segmentation, category_id, category_name, score, iscrowd=0, image_id=None)
classmethod
¶Creates CocoAnnotation object using coco segmentation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
segmentation
¶ |
List[List][[1, 1, 325, 125, 250, 200, 5, 200]] |
required | |
category_id
¶ |
int Category id of the annotation |
required | |
category_name
¶ |
str Category name of the annotation |
required | |
score
¶ |
float Prediction score between 0 and 1 |
required | |
iscrowd
¶ |
int 0 or 1 |
0
|
Source code in sahi/utils/coco.py
CocoVid
¶Source code in sahi/utils/coco.py
2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 | |
__init__(name=None, remapping_dict=None)
¶Creates CocoVid object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
¶ |
str Name of the CocoVid dataset, it determines exported json name. |
None
|
|
remapping_dict
¶ |
dict {1:0, 2:1} maps category id 1 to 0 and category id 2 to 1 |
None
|
Source code in sahi/utils/coco.py
add_categories_from_coco_category_list(coco_category_list)
¶Creates CocoCategory object using coco category list.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_category_list
¶ |
List[Dict] [ {"supercategory": "person", "id": 1, "name": "person"}, {"supercategory": "vehicle", "id": 2, "name": "bicycle"} ] |
required |
Source code in sahi/utils/coco.py
add_category(category)
¶Adds category to this CocoVid instance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
category
¶ |
CocoCategory
|
CocoCategory |
required |
Source code in sahi/utils/coco.py
CocoVidAnnotation
¶
Bases: CocoAnnotation
COCOVid formatted annotation.
https://github.com/open-mmlab/mmtracking/blob/master/docs/tutorials/customize_dataset.md#the-cocovid-annotation-file
Source code in sahi/utils/coco.py
__init__(category_id, category_name, bbox, image_id=None, instance_id=None, iscrowd=0, id=None)
¶Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bbox
¶ |
list[int]
|
List [xmin, ymin, width, height] |
required |
category_id
¶ |
int
|
int Category id of the annotation |
required |
category_name
¶ |
str
|
str Category name of the annotation |
required |
image_id
¶ |
int Image ID of the annotation |
None
|
|
instance_id
¶ |
int Used for tracking |
None
|
|
iscrowd
¶ |
int 0 or 1 |
0
|
|
id
¶ |
int Annotation id |
None
|
Source code in sahi/utils/coco.py
CocoVidImage
¶
Bases: CocoImage
COCOVid formatted image.
https://github.com/open-mmlab/mmtracking/blob/master/docs/tutorials/customize_dataset.md#the-cocovid-annotation-file
Source code in sahi/utils/coco.py
597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 | |
__init__(file_name, height, width, video_id=None, frame_id=None, id=None)
¶Creates CocoVidImage object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
id
¶ |
int Image id |
None
|
|
file_name
¶ |
str Image path |
required | |
height
¶ |
int Image height in pixels |
required | |
width
¶ |
int Image width in pixels |
required | |
frame_id
¶ |
int 0-indexed frame id |
None
|
|
video_id
¶ |
int Video id |
None
|
Source code in sahi/utils/coco.py
add_annotation(annotation)
¶Adds annotation to this CocoImage instance annotation : CocoVidAnnotation
Source code in sahi/utils/coco.py
from_coco_image(coco_image, video_id=None, frame_id=None)
classmethod
¶Creates CocoVidImage object using CocoImage object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_image
¶ |
CocoImage |
required | |
frame_id
¶ |
int 0-indexed frame id |
None
|
|
video_id
¶ |
int Video id |
None
|
Source code in sahi/utils/coco.py
CocoVideo
¶COCO formatted video.
https://github.com/open-mmlab/mmtracking/blob/master/docs/tutorials/customize_dataset.md#the-cocovid-annotation-file
Source code in sahi/utils/coco.py
__init__(name, id=None, fps=None, height=None, width=None)
¶Creates CocoVideo object.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
name
¶ |
str
|
str Video name |
required |
id
¶ |
int | None
|
int Video id |
None
|
fps
¶ |
float | None
|
float Video fps |
None
|
height
¶ |
int | None
|
int Video height in pixels |
None
|
width
¶ |
int | None
|
int Video width in pixels |
None
|
Source code in sahi/utils/coco.py
add_cocovidimage(cocovidimage)
¶Adds CocoVidImage to this CocoVideo instance Args: cocovidimage: CocoVidImage
Source code in sahi/utils/coco.py
add_image(image)
¶Adds image to this CocoVideo instance Args: image: CocoImage
Source code in sahi/utils/coco.py
DatasetClassCounts
dataclass
¶Stores the number of images that include each category in a dataset.
Source code in sahi/utils/coco.py
add_bbox_and_area_to_coco(source_coco_path='', target_coco_path='', add_bbox=True, add_area=True)
¶Takes single coco dataset file path, calculates and fills bbox and area fields of the annotations and exports the updated coco dict.
coco_dict : dict Updated coco dict
Source code in sahi/utils/coco.py
count_images_with_category(coco_file_path)
¶Reads a coco dataset file and returns an DatasetClassCounts object that stores the number of images that include each category in a dataset Returns: DatasetClassCounts object coco_file_path : str path to coco dataset file
Source code in sahi/utils/coco.py
create_coco_dict(images, categories, ignore_negative_samples=False, image_id_setting='auto')
¶Creates COCO dict with fields "images", "annotations", "categories".
Args
images : List of CocoImage containing a list of CocoAnnotation
categories : List of Dict
COCO categories
ignore_negative_samples : Bool
If True, images without annotations are ignored
image_id_setting: str
how to assign image ids while exporting can be
auto --> will assign id from scratch (<CocoImage>.id will be ignored)
manual --> you will need to provide image ids in <CocoImage> instances (<CocoImage>.id can not be None)
Returns
coco_dict : Dict
COCO dict with fields "images", "annotations", "categories"
Source code in sahi/utils/coco.py
1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 | |
create_coco_prediction_array(images, ignore_negative_samples=False, image_id_setting='auto')
¶Creates COCO prediction array which is list of predictions.
Args
images : List of CocoImage containing a list of CocoAnnotation
ignore_negative_samples : Bool
If True, images without predictions are ignored
image_id_setting: str
how to assign image ids while exporting can be
auto --> will assign id from scratch (<CocoImage>.id will be ignored)
manual --> you will need to provide image ids in <CocoImage> instances (<CocoImage>.id can not be None)
Returns
coco_prediction_array : List
COCO predictions array
Source code in sahi/utils/coco.py
1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 | |
export_coco_as_yolo(output_dir, train_coco=None, val_coco=None, train_split_rate=0.9, numpy_seed=0, disable_symlink=False)
¶Exports current COCO dataset in ultralytics/YOLO format. Creates train val folders with image symlinks and txt files and a data yaml file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
¶ |
str
|
str Export directory. |
required |
train_coco
¶ |
Coco | None
|
Coco coco object for training |
None
|
val_coco
¶ |
Coco | None
|
Coco coco object for val |
None
|
train_split_rate
¶ |
float
|
float train split rate between 0 and 1. will be used when val_coco is None. |
0.9
|
numpy_seed
¶ |
int To fix the numpy seed. |
0
|
|
disable_symlink
¶ |
bool If True, copy images instead of creating symlinks. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
yaml_path |
str Path for the exported YOLO data.yml |
Source code in sahi/utils/coco.py
2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 | |
export_coco_as_yolo_via_yml(yml_path, output_dir, train_split_rate=0.9, numpy_seed=0, disable_symlink=False)
¶Exports current COCO dataset in ultralytics/YOLO format. Creates train val folders with image symlinks and txt files and a data yaml file. Uses a yml file as input.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
yml_path
¶ |
str
|
str file should contain these fields: train_json_path: str train_image_dir: str val_json_path: str val_image_dir: str |
required |
output_dir
¶ |
str
|
str Export directory. |
required |
train_split_rate
¶ |
float
|
float train split rate between 0 and 1. will be used when val_json_path is None. |
0.9
|
numpy_seed
¶ |
int To fix the numpy seed. |
0
|
|
disable_symlink
¶ |
bool If True, copy images instead of creating symlinks. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
yaml_path |
str Path for the exported YOLO data.yml |
Source code in sahi/utils/coco.py
export_coco_as_yolov5(output_dir, train_coco=None, val_coco=None, train_split_rate=0.9, numpy_seed=0, disable_symlink=False)
¶Deprecated.
Please use export_coco_as_yolo instead. Calls export_coco_as_yolo with the same arguments.
Source code in sahi/utils/coco.py
export_coco_as_yolov5_via_yml(yml_path, output_dir, train_split_rate=0.9, numpy_seed=0, disable_symlink=False)
¶Deprecated.
Please use export_coco_as_yolo_via_yml instead. Calls export_coco_as_yolo_via_yml with the same arguments.
Source code in sahi/utils/coco.py
export_single_yolo_image_and_corresponding_txt(coco_image, coco_image_dir, output_dir, ignore_negative_samples=False, disable_symlink=False)
¶Generates YOLO formatted image symlink and annotation txt file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_image
¶ |
sahi.utils.coco.CocoImage |
required | |
coco_image_dir
¶ |
str |
required | |
output_dir
¶ |
str Export directory. |
required | |
ignore_negative_samples
¶ |
bool If True ignores images without annotations in all operations. |
False
|
Source code in sahi/utils/coco.py
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 | |
export_yolo_images_and_txts_from_coco_object(output_dir, coco, ignore_negative_samples=False, mp=False, disable_symlink=False)
¶Creates image symlinks and annotation txts in yolo format from coco dataset.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
output_dir
¶ |
str Export directory. |
required | |
coco
¶ |
sahi.utils.coco.Coco Initialized Coco object that contains images and categories. |
required | |
ignore_negative_samples
¶ |
bool If True ignores images without annotations in all operations. |
False
|
|
mp
¶ |
bool If True, multiprocess mode is on. Should be called in 'if name == main:' block. |
False
|
|
disable_symlink
¶ |
bool If True, symlinks are not created. Instead images are copied. |
False
|
Source code in sahi/utils/coco.py
get_imageid2annotationlist_mapping(coco_dict)
¶Get image_id to annotationlist mapping for faster indexing.
Args
coco_dict : dict
coco dict with fields "images", "annotations", "categories"
Returns
image_id_to_annotation_list : dict
{
1: [CocoAnnotation, CocoAnnotation, CocoAnnotation],
2: [CocoAnnotation]
}
where
CocoAnnotation = {
'area': 2795520,
'bbox': [491.0, 1035.0, 153.0, 182.0],
'category_id': 1,
'id': 1,
'image_id': 1,
'iscrowd': 0,
'segmentation': [[491.0, 1035.0, 644.0, 1035.0, 644.0, 1217.0, 491.0, 1217.0]]
}
Source code in sahi/utils/coco.py
merge(coco_dict1, coco_dict2, desired_name2id=None)
¶Combines 2 coco formatted annotations dicts, and returns the combined coco dict.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
coco_dict1
¶ |
dict First coco dictionary. |
required | |
coco_dict2
¶ |
dict Second coco dictionary. |
required | |
desired_name2id
¶ |
dict |
required |
Returns: merged_coco_dict : dict Merged COCO dict.
Source code in sahi/utils/coco.py
merge_from_file(coco_path1, coco_path2, save_path)
¶Combines 2 coco formatted annotations files given their paths, and saves the combined file to save_path.
Args:
coco_path1 : str
Path for the first coco file.
coco_path2 : str
Path for the second coco file.
save_path : str
"dirname/coco.json"
Source code in sahi/utils/coco.py
merge_from_list(coco_dict_list, desired_name2id=None, verbose=1)
¶Combines a list of coco formatted annotations dicts, and returns the combined coco dict.
Args:
coco_dict_list: list of dict
A list of coco dicts
desired_name2id: dict
{"human": 1, "car": 2, "big_vehicle": 3}
verbose: bool
If True, merging info is printed
Returns:
merged_coco_dict: dict
Merged COCO dict.
Source code in sahi/utils/coco.py
remove_invalid_coco_results(result_list_or_path, dataset_dict_or_path=None)
¶Removes invalid predictions from coco result such as
- negative bbox value
- extreme bbox value
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
result_list_or_path
¶ |
list | str
|
path or list for coco result json |
required |
dataset_dict_or_path
¶ |
optional
|
path or dict for coco dataset json |
None
|
Source code in sahi/utils/coco.py
update_categories(desired_name2id, coco_dict)
¶Rearranges category mapping of given COCO dictionary based on given category_mapping. Can also be used to filter some of the categories.
Args:
desired_name2id : dict
{"big_vehicle": 1, "car": 2, "human": 3}
coco_dict : dict
COCO formatted dictionary.
Returns:
| Name | Type | Description |
|---|---|---|
coco_target |
dict
|
dict COCO dict with updated/filtered categories. |
Source code in sahi/utils/coco.py
update_categories_from_file(desired_name2id, coco_path, save_path)
¶Rearranges category mapping of a COCO dictionary in coco_path based on given category_mapping. Can also be used to filter some of the categories.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
desired_name2id
¶ |
dict |
required | |
coco_path
¶ |
str "dirname/coco.json" |
required |
Source code in sahi/utils/coco.py
cv
¶
Colors
¶Source code in sahi/utils/cv.py
__call__(ind, bgr=False)
¶Convert an index to a color code.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ind
¶ |
int
|
The index to convert. |
required |
bgr
¶ |
bool
|
Whether to return the color code in BGR format. Defaults to False. |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
The color code in RGB or BGR format, depending on the value of |
Source code in sahi/utils/cv.py
hex_to_rgb(hex_code)
staticmethod
¶Converts a hexadecimal color code to RGB format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
hex_code
¶ |
str
|
The hexadecimal color code to convert. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
A tuple representing the RGB values in the order (R, G, B). |
Source code in sahi/utils/cv.py
apply_color_mask(image, color)
¶Applies color mask to given input image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
The input image to apply the color mask to. |
required |
color
¶ |
tuple
|
The RGB color tuple to use for the mask. |
required |
Returns:
| Type | Description |
|---|---|
|
np.ndarray: The resulting image with the applied color mask. |
Source code in sahi/utils/cv.py
convert_image_to(read_path, extension='jpg', grayscale=False)
¶Reads an image from the given path and saves it with the specified extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
read_path
¶ |
str
|
The path to the image file. |
required |
extension
¶ |
str
|
The desired file extension for the saved image. Defaults to "jpg". |
'jpg'
|
grayscale
¶ |
bool
|
Whether to convert the image to grayscale. Defaults to False. |
False
|
Source code in sahi/utils/cv.py
crop_object_predictions(image, object_prediction_list, output_dir='', file_name='prediction_visual', export_format='png')
¶Crops bounding boxes over the source image and exports it to the output folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
The source image to crop bounding boxes from. |
required |
object_prediction_list
¶ |
A list of object predictions. |
required | |
output_dir
¶ |
str
|
The directory where the resulting visualizations will be exported. Defaults to an empty string. |
''
|
file_name
¶ |
str
|
The name of the exported file. The exported file will be saved as |
'prediction_visual'
|
export_format
¶ |
str
|
The format of the exported file. Can be specified as 'jpg' or 'png'. Defaults to "png". |
'png'
|
Source code in sahi/utils/cv.py
get_bbox_from_bool_mask(bool_mask)
¶Generate VOC bounding box [xmin, ymin, xmax, ymax] from given boolean mask.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
bool_mask
¶ |
ndarray
|
2D boolean mask. |
required |
Returns:
| Type | Description |
|---|---|
list[int] | None
|
Optional[List[int]]: VOC bounding box [xmin, ymin, xmax, ymax] or None if no bounding box is found. |
Source code in sahi/utils/cv.py
get_bbox_from_coco_segmentation(coco_segmentation)
¶Generate voc box ([xmin, ymin, xmax, ymax]) from given coco segmentation.
Source code in sahi/utils/cv.py
get_bool_mask_from_coco_segmentation(coco_segmentation, width, height)
¶Convert coco segmentation to 2D boolean mask of given height and width.
Parameters: - coco_segmentation: list of points representing the coco segmentation - width: width of the boolean mask - height: height of the boolean mask
Returns: - bool_mask: 2D boolean mask of size (height, width)
Source code in sahi/utils/cv.py
get_coco_segmentation_from_bool_mask(bool_mask)
¶Convert boolean mask to coco segmentation format [ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ]
Source code in sahi/utils/cv.py
get_coco_segmentation_from_obb_points(obb_points)
¶Convert OBB (Oriented Bounding Box) points to COCO polygon format.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
obb_points
¶ |
ndarray
|
np.ndarray OBB points tensor from ultralytics.engine.results.OBB Shape: (4, 2) containing 4 points with (x,y) coordinates each |
required |
Returns:
| Type | Description |
|---|---|
list[list[float]]
|
List[List[float]]: Polygon points in COCO format [[x1, y1, x2, y2, x3, y3, x4, y4], [...], ...] |
Source code in sahi/utils/cv.py
get_video_reader(source, save_dir, frame_skip_interval, export_visual=False, view_visual=False)
¶Creates OpenCV video capture object from given video file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
source
¶ |
str
|
Video file path |
required |
save_dir
¶ |
str
|
Video export directory |
required |
frame_skip_interval
¶ |
int
|
Frame skip interval |
required |
export_visual
¶ |
bool
|
Set True if you want to export visuals |
False
|
view_visual
¶ |
bool
|
Set True if you want to render visual |
False
|
Returns:
| Name | Type | Description |
|---|---|---|
iterator |
Generator[Image]
|
Pillow Image |
video_writer |
VideoWriter | None
|
cv2.VideoWriter |
video_file_name |
str
|
video name with extension |
Source code in sahi/utils/cv.py
260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 | |
ipython_display(image)
¶Displays numpy image in notebook.
If input image is in range 0..1, please first multiply img by 255 Assumes image is ndarray of shape [height, width, channels] where channels can be 1, 3 or 4
Source code in sahi/utils/cv.py
normalize_numpy_image(image)
¶ read_image(image_path)
¶Loads image as a numpy array from the given path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
¶ |
str
|
The path to the image file. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
numpy.ndarray: The loaded image as a numpy array. |
Source code in sahi/utils/cv.py
read_image_as_pil(image, exif_fix=True)
¶Loads an image as PIL.Image.Image.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
Union[Image, str, ndarray]
|
The image to be loaded. It can be an image path or URL (str), a numpy image (np.ndarray), or a PIL.Image object. |
required |
exif_fix
¶ |
bool
|
Whether to apply an EXIF fix to the image. Defaults to False. |
True
|
Returns:
| Type | Description |
|---|---|
Image
|
PIL.Image.Image: The loaded image as a PIL.Image object. |
Source code in sahi/utils/cv.py
read_large_image(image_path)
¶Reads a large image from the specified image path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image_path
¶ |
str
|
The path to the image file. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
tuple |
A tuple containing the image data and a flag indicating whether cv2 was used to read the image. The image data is a numpy array representing the image in RGB format. The flag is True if cv2 was used, False otherwise. |
Source code in sahi/utils/cv.py
select_random_color()
¶Selects a random color from a predefined list of colors.
Returns:
| Name | Type | Description |
|---|---|---|
list |
A list representing the RGB values of the selected color. |
Source code in sahi/utils/cv.py
visualize_object_predictions(image, object_prediction_list, rect_th=None, text_size=None, text_th=None, color=None, hide_labels=False, hide_conf=False, output_dir=None, file_name='prediction_visual', export_format='png')
¶Visualizes prediction category names, bounding boxes over the source image and exports it to output folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
object_prediction_list
¶ |
a list of prediction.ObjectPrediction |
required | |
rect_th
¶ |
int | None
|
rectangle thickness |
None
|
text_size
¶ |
float | None
|
size of the category name over box |
None
|
text_th
¶ |
int | None
|
text thickness |
None
|
color
¶ |
tuple | None
|
annotation color in the form: (0, 255, 0) |
None
|
hide_labels
¶ |
bool
|
hide labels |
False
|
hide_conf
¶ |
bool
|
hide confidence |
False
|
output_dir
¶ |
str | None
|
directory for resulting visualization to be exported |
None
|
file_name
¶ |
str | None
|
exported file will be saved as: output_dir+file_name+".png" |
'prediction_visual'
|
export_format
¶ |
str | None
|
can be specified as 'jpg' or 'png' |
'png'
|
Source code in sahi/utils/cv.py
473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 | |
visualize_prediction(image, boxes, classes, masks=None, rect_th=None, text_size=None, text_th=None, color=None, hide_labels=False, output_dir=None, file_name='prediction_visual')
¶Visualizes prediction classes, bounding boxes over the source image and exports it to output folder.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
image
¶ |
ndarray
|
The source image. |
required |
boxes
¶ |
List[List]
|
List of bounding boxes coordinates. |
required |
classes
¶ |
List[str]
|
List of class labels corresponding to each bounding box. |
required |
masks
¶ |
Optional[List[ndarray]]
|
List of masks corresponding to each bounding box. Defaults to None. |
None
|
rect_th
¶ |
int
|
Thickness of the bounding box rectangle. Defaults to None. |
None
|
text_size
¶ |
float
|
Size of the text for class labels. Defaults to None. |
None
|
text_th
¶ |
int
|
Thickness of the text for class labels. Defaults to None. |
None
|
color
¶ |
tuple
|
Color of the bounding box and text. Defaults to None. |
None
|
hide_labels
¶ |
bool
|
Whether to hide the class labels. Defaults to False. |
False
|
output_dir
¶ |
Optional[str]
|
Output directory to save the visualization. Defaults to None. |
None
|
file_name
¶ |
Optional[str]
|
File name for the saved visualization. Defaults to "prediction_visual". |
'prediction_visual'
|
Returns:
| Name | Type | Description |
|---|---|---|
dict |
A dictionary containing the visualized image and the elapsed time for the visualization process. |
Source code in sahi/utils/cv.py
359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 | |
detectron2
¶
export_cfg_as_yaml(cfg, export_path='config.yaml')
¶Exports Detectron2 config object in yaml format so that it can be used later.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
cfg
¶ |
CfgNode
|
Detectron2 config object. |
required |
export_path
¶ |
str
|
Path to export the Detectron2 config. |
'config.yaml'
|
Related Detectron2 doc: https://detectron2.readthedocs.io/en/stable/modules/config.html#detectron2.config.CfgNode.dump
Source code in sahi/utils/detectron2.py
file
¶
download_from_url(from_url, to_path)
¶Downloads a file from the given URL and saves it to the specified path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
from_url
¶ |
str
|
The URL of the file to download. |
required |
to_path
¶ |
str
|
The path where the downloaded file should be saved. |
required |
Returns:
| Type | Description |
|---|---|
|
None |
Source code in sahi/utils/file.py
get_base_filename(path)
¶Takes a file path, returns (base_filename_with_extension, base_filename_without_extension)
Source code in sahi/utils/file.py
get_file_extension(path)
¶Get the file extension from a given file path.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
¶ |
str
|
The file path. |
required |
Returns:
| Name | Type | Description |
|---|---|---|
str |
The file extension. |
import_model_class(model_type, class_name)
¶Imports a predefined detection class by class name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_type
¶ |
str "yolov5", "detectron2", "mmdet", "huggingface" etc |
required | |
model_name
¶ |
str Name of the detection model class (example: "MmdetDetectionModel") |
required |
Returns: class_: class with given path
Source code in sahi/utils/file.py
increment_path(path, exist_ok=True, sep='')
¶Increment path, i.e. runs/exp --> runs/exp{sep}0, runs/exp{sep}1 etc.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
path
¶ |
str | Path
|
str The base path to increment. |
required |
exist_ok
¶ |
bool
|
bool If True, return the path as is if it already exists. If False, increment the path. |
True
|
sep
¶ |
str
|
str The separator to use between the base path and the increment number. |
''
|
Returns:
| Name | Type | Description |
|---|---|---|
str |
str
|
The incremented path. |
Example
increment_path("runs/exp", sep="") 'runs/exp_0' increment_path("runs/exp_0", sep="") 'runs/exp_1'
Source code in sahi/utils/file.py
is_colab()
¶Check if the current environment is a Google Colab instance.
Returns:
| Name | Type | Description |
|---|---|---|
bool |
True if the environment is a Google Colab instance, False otherwise. |
list_files(directory, contains=['.json'], verbose=1)
¶Walk given directory and return a list of file path with desired extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
¶ |
str
|
str "data/coco/" |
required |
contains
¶ |
list
|
list A list of strings to check if the target file contains them, example: ["coco.png", ".jpg", "jpeg"] |
['.json']
|
verbose
¶ |
int
|
int 0: no print 1: print number of files |
1
|
Returns:
| Name | Type | Description |
|---|---|---|
filepath_list |
list[str]
|
list List of file paths |
Source code in sahi/utils/file.py
list_files_recursively(directory, contains=['.json'], verbose=True)
¶Walk given directory recursively and return a list of file path with desired extension.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
directory
¶ |
str "data/coco/" |
required | |
contains
¶ |
list A list of strings to check if the target file contains them, example: ["coco.png", ".jpg", "jpeg"] |
required | |
verbose
¶ |
bool If true, prints some results |
required |
Returns:
| Name | Type | Description |
|---|---|---|
relative_filepath_list |
list
|
list List of file paths relative to given directory |
abs_filepath_list |
list
|
list List of absolute file paths |
Source code in sahi/utils/file.py
load_json(load_path, encoding='utf-8')
¶Loads json formatted data (given as "data") from load_path Encoding type can be specified with 'encoding' argument.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_path
¶ |
str
|
str "dirname/coco.json" |
required |
encoding
¶ |
str
|
str Encoding type, default is 'utf-8' |
'utf-8'
|
Example inputs
load_path: "dirname/coco.json"
Source code in sahi/utils/file.py
load_pickle(load_path)
¶Loads pickle formatted data (given as "data") from load_path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
load_path
¶ |
str "dirname/coco.pickle" |
required |
Example inputs
load_path: "dirname/coco.pickle"
Source code in sahi/utils/file.py
save_json(data, save_path, indent=None)
¶Saves json formatted data (given as "data") as save_path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
¶ |
dict Data to be saved as json |
required | |
save_path
¶ |
str "dirname/coco.json" |
required | |
indent
¶ |
int | None
|
int or None Indentation level for pretty-printing the JSON data. If None, the most compact representation will be used. If an integer is provided, it specifies the number of spaces to use for indentation. Example: indent=4 will format the JSON data with an indentation of 4 spaces per level. |
None
|
Example inputs
data: {"image_id": 5} save_path: "dirname/coco.json" indent: Train json files with indent=None, val json files with indent=4
Source code in sahi/utils/file.py
save_pickle(data, save_path)
¶Saves pickle formatted data (given as "data") as save_path
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
data
¶ |
dict Data to be saved as pickle |
required | |
save_path
¶ |
str "dirname/coco.pickle" |
required |
Example inputs
data: {"image_id": 5} save_path: "dirname/coco.pickle"
Source code in sahi/utils/file.py
unzip(file_path, dest_dir)
¶Unzips compressed .zip file.
Example inputs
file_path: 'data/01_alb_id.zip' dest_dir: 'data/'
import_utils
¶
check_package_minimum_version(package_name, minimum_version, verbose=False)
¶Raise error if module version is not compatible.
Source code in sahi/utils/import_utils.py
check_requirements(package_names)
¶Raise error if module is not installed.
Source code in sahi/utils/import_utils.py
ensure_package_minimum_version(package_name, minimum_version, verbose=False)
¶Raise error if module version is not compatible.
Source code in sahi/utils/import_utils.py
get_package_info(package_name, verbose=True)
¶Returns the package version as a string and the package name as a string.
Source code in sahi/utils/import_utils.py
mmdet
¶
download_mmdet_config(model_name='cascade_rcnn', config_file_name='cascade_mask_rcnn_r50_fpn_1x_coco.py', verbose=True)
¶Merges config files starting from given main config file name. Saves as single file.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
model_name
¶ |
str
|
mmdet model name. check https://github.com/open-mmlab/mmdetection/tree/master/configs. |
'cascade_rcnn'
|
config_file_name
¶ |
str
|
mdmet config file name. |
'cascade_mask_rcnn_r50_fpn_1x_coco.py'
|
verbose
¶ |
bool
|
if True, print save path. |
True
|
Returns:
| Type | Description |
|---|---|
str
|
(str) abs path of the downloaded config file. |
Source code in sahi/utils/mmdet.py
61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 | |
shapely
¶
ShapelyAnnotation
¶Creates ShapelyAnnotation (as shapely MultiPolygon).
Can convert this instance annotation to various formats.
Source code in sahi/utils/shapely.py
70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 | |
from_coco_bbox(bbox, slice_bbox=None)
classmethod
¶Init ShapelyAnnotation from coco bbox.
bbox (List[int]): [xmin, ymin, width, height] slice_bbox (List[int]): [x_min, y_min, x_max, y_max] Is used to calculate sliced coco coordinates.
Source code in sahi/utils/shapely.py
from_coco_segmentation(segmentation, slice_bbox=None)
classmethod
¶Init ShapelyAnnotation from coco segmentation.
List[List]
[[1, 1, 325, 125, 250, 200, 5, 200]]
slice_bbox (List[int]): [xmin, ymin, width, height] Should have the same format as the output of the get_bbox_from_shapely function. Is used to calculate sliced coco coordinates.
Source code in sahi/utils/shapely.py
get_buffered_shapely_annotation(distance=3, resolution=16, quadsegs=None, cap_style=CAP_STYLE.round, join_style=JOIN_STYLE.round, mitre_limit=5.0, single_sided=False)
¶Approximates the present polygon to have a valid polygon shape.
For more, check: https://shapely.readthedocs.io/en/stable/manual.html#object.buffer
Source code in sahi/utils/shapely.py
get_intersection(polygon)
¶Accepts shapely polygon object and returns the intersection in ShapelyAnnotation format.
Source code in sahi/utils/shapely.py
to_coco_bbox()
¶ to_coco_segmentation()
¶[ [x1, y1, x2, y2, x3, y3, ...], [x1, y1, x2, y2, x3, y3, ...], ... ]
Source code in sahi/utils/shapely.py
to_list()
¶[ [(x1, y1), (x2, y2), (x3, y3), ...], [(x1, y1), (x2, y2), (x3, y3), ...], ... ]
Source code in sahi/utils/shapely.py
to_opencv_contours()
¶[ [[[1, 1]], [[325, 125]], [[250, 200]], [[5, 200]]], [[[1, 1]], [[325, 125]], [[250, 200]], [[5, 200]]] ]
Source code in sahi/utils/shapely.py
to_voc_bbox()
¶ to_xywh()
¶[xmin, ymin, width, height]
Source code in sahi/utils/shapely.py
to_xyxy()
¶[xmin, ymin, xmax, ymax]
Source code in sahi/utils/shapely.py
get_bbox_from_shapely(shapely_object)
¶Accepts shapely box/poly object and returns its bounding box in coco and voc formats.
Source code in sahi/utils/shapely.py
get_shapely_box(x, y, width, height)
¶Accepts coco style bbox coords and converts it to shapely box object.
Source code in sahi/utils/shapely.py
get_shapely_multipolygon(coco_segmentation)
¶Accepts coco style polygon coords and converts it to valid shapely multipolygon object.
Source code in sahi/utils/shapely.py
torch_utils
¶
select_device(device=None)
¶Selects torch device.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
device
¶ |
str | None
|
"cpu", "mps", "cuda", "cuda:0", "cuda:1", etc. When no device string is given, the order of preference to try is: cuda:0 > mps > cpu |
None
|
Returns:
| Type | Description |
|---|---|
device
|
torch.device |
Inspired by https://github.com/ultralytics/yolov5/blob/6371de8879e7ad7ec5283e8b95cc6dd85d6a5e72/utils/torch_utils.py#L107
Source code in sahi/utils/torch_utils.py
to_float_tensor(img)
¶Converts a PIL.Image (RGB) or numpy.ndarray (H x W x C) in the range [0, 255] to a torch.FloatTensor of shape (C x H x W).
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
img
¶ |
ndarray | Image
|
PIL.Image or numpy array |
required |
Returns: torch.tensor