Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[Docs] Tutorial on Small Object Detection with SAHI #4263

Merged
merged 5 commits into from Apr 13, 2024

Conversation

jacobmarks
Copy link
Contributor

@jacobmarks jacobmarks commented Apr 12, 2024

Slicing Aided Hyper Inference (SAHI) works in conjunction with object detection models to improve detection quality for small objects/large images.

This tutorial covers generating predictions with SAHI, and evaluating these predictions.

SAHI already integrated with FiftyOne, which made this very straightforward. The tutorial also leverages our Hugging Face Hub and Ultralytics integrations.

Static PDF Here:
Detecting Small Objects with SAHI — FiftyOne 0.24.0 documentation.pdf

What changes are proposed in this pull request?

(Please fill in changes proposed in this fix)

How is this patch tested? If it is not, please explain why.

(Details)

Release Notes

Is this a user-facing change that should be mentioned in the release notes?

  • No. You can skip the rest of this section.
  • Yes. Give a description of this change to be included in the release
    notes for FiftyOne users.

(Details in 1-2 sentences. You can just refer to another PR with a description
if this PR is part of a larger change.)

What areas of FiftyOne does this PR affect?

  • App: FiftyOne application changes
  • Build: Build and test infrastructure changes
  • Core: Core fiftyone Python library changes
  • Documentation: FiftyOne documentation changes
  • Other

Summary by CodeRabbit

  • Documentation
    • Enhanced the tutorials index page with a new tutorial card for "Small Object Detection with SAHI" featuring a description, link, image, and tags.
    • Included a link to the "Detecting small objects" tutorial in the list of tutorials.

Copy link
Contributor

coderabbitai bot commented Apr 12, 2024

Walkthrough

The recent update brings a new tutorial card for "Small Object Detection with SAHI" to the tutorials index page. This addition includes a detailed description, a direct link, an illustrative image, and relevant tags. Furthermore, a link to the "Detecting small objects" tutorial has been included in the list.

Changes

File Path Change Summary
docs/.../index.rst Added a tutorial card for "Small Object Detection with SAHI"

🐰✨📚
A hop, a skip, a jump so high,
In the docs, new tutorials lie.
Small objects, we now can detect,
With SAHI's help, perfect and correct!
Cheers to learning, page by page,
On this ever-growing digital stage! 🌟📖


Recent Review Details

Configuration used: .coderabbit.yaml

Commits Files that changed from the base of the PR and between cb657cf and 51cca80.
Files selected for processing (2)
  • docs/source/tutorials/index.rst (2 hunks)
  • docs/source/tutorials/small_object_detection.ipynb (1 hunks)
Files not summarized due to errors (1)
  • docs/source/tutorials/small_object_detection.ipynb: Error: Message exceeds token limit
Files skipped from review as they are similar to previous changes (1)
  • docs/source/tutorials/index.rst
Additional comments not posted (7)
docs/source/tutorials/small_object_detection.ipynb (7)

68-69: Consider pinning the versions of the libraries to ensure reproducibility.


116-116: Ensure that the dataset name and the maximum number of samples are configurable to enhance flexibility.


140-140: Consider handling potential exceptions when launching the FiftyOne app.


177-184: Ensure proper error handling when applying the model to the dataset.


266-282: Refactor the filtering function to improve readability and maintainability.


364-370: Consider adding error handling for model loading and setting a default device based on availability.


739-743: Add error handling for the predict_with_slicing function to manage exceptions during prediction.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

Share
Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (invoked as PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger a review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

Copy link
Contributor

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 7

Comment on lines +68 to +69
"pip install -U fiftyone sahi ultralytics huggingface_hub --quiet"
]
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider pinning the versions of the libraries to ensure reproducibility.

- pip install -U fiftyone sahi ultralytics huggingface_hub --quiet
+ pip install fiftyone==0.24.0 sahi==0.8.5 ultralytics==1.0.0 huggingface_hub==0.2.0 --quiet

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"pip install -U fiftyone sahi ultralytics huggingface_hub --quiet"
]
"pip install fiftyone==0.24.0 sahi==0.8.5 ultralytics==1.0.0 huggingface_hub==0.2.0 --quiet"
]

}
],
"source": [
"dataset = fouh.load_from_hub(\"jamarks/VisDrone2019-DET\", name=\"sahi-test\", max_samples=100, overwrite=True)"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure that the dataset name and the maximum number of samples are configurable to enhance flexibility.

- dataset = fouh.load_from_hub("jamarks/VisDrone2019-DET", name="sahi-test", max_samples=100, overwrite=True)
+ dataset_name = "jamarks/VisDrone2019-DET"
+ max_samples = 100  # Configurable number of samples
+ dataset = fouh.load_from_hub(dataset_name, name="sahi-test", max_samples=max_samples, overwrite=True)

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"dataset = fouh.load_from_hub(\"jamarks/VisDrone2019-DET\", name=\"sahi-test\", max_samples=100, overwrite=True)"
dataset_name = "jamarks/VisDrone2019-DET"
max_samples = 100 # Configurable number of samples
dataset = fouh.load_from_hub(dataset_name, name="sahi-test", max_samples=max_samples, overwrite=True)

}
],
"source": [
"session = fo.launch_app(dataset)"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider handling potential exceptions when launching the FiftyOne app.

- session = fo.launch_app(dataset)
+ try:
+     session = fo.launch_app(dataset)
+ except Exception as e:
+     print(f"Failed to launch FiftyOne app: {e}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"session = fo.launch_app(dataset)"
try:
session = fo.launch_app(dataset)
except Exception as e:
print(f"Failed to launch FiftyOne app: {e}")

Comment on lines +177 to +184
"source": [
"from ultralytics import YOLO\n",
"\n",
"ckpt_path = \"yolov8l.pt\"\n",
"model = YOLO(ckpt_path)\n",
"## fiftyone will work directly with the Ultralytics.YOLO model\n",
"\n",
"dataset.apply_model(model, label_field=\"base_model\")"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ensure proper error handling when applying the model to the dataset.

- dataset.apply_model(model, label_field="base_model")
+ try:
+     dataset.apply_model(model, label_field="base_model")
+ except Exception as e:
+     print(f"Error applying model: {e}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"source": [
"from ultralytics import YOLO\n",
"\n",
"ckpt_path = \"yolov8l.pt\"\n",
"model = YOLO(ckpt_path)\n",
"## fiftyone will work directly with the Ultralytics.YOLO model\n",
"\n",
"dataset.apply_model(model, label_field=\"base_model\")"
"source": [
"from ultralytics import YOLO\n",
"\n",
"ckpt_path = \"yolov8l.pt\"\n",
"model = YOLO(ckpt_path)\n",
"## fiftyone will work directly with the Ultralytics.YOLO model\n",
"\n",
"try:\n",
" dataset.apply_model(model, label_field=\"base_model\")\n",
"except Exception as e:\n",
" print(f\"Error applying model: {e}\")"

Comment on lines +266 to +282
"def get_label_fields(sample_collection):\n",
" \"\"\"Get the (detection) label fields of a Dataset or DatasetView.\"\"\"\n",
" label_fields = list(\n",
" sample_collection.get_field_schema(embedded_doc_type=fo.Detections).keys()\n",
" )\n",
" return label_fields\n",
"\n",
"def filter_all_labels(sample_collection):\n",
" label_fields = get_label_fields(sample_collection)\n",
"\n",
" filtered_view = sample_collection\n",
"\n",
" for lf in label_fields:\n",
" filtered_view = filtered_view.filter_labels(\n",
" lf, F(\"label\").is_in([\"person\", \"car\", \"truck\"]), only_matches=False\n",
" )\n",
" return filtered_view"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Refactor the filtering function to improve readability and maintainability.

- def filter_all_labels(sample_collection):
-     label_fields = get_label_fields(sample_collection)
-     filtered_view = sample_collection
-     for lf in label_fields:
-         filtered_view = filtered_view.filter_labels(
-             lf, F("label").is_in(["person", "car", "truck"]), only_matches=False
-         )
-     return filtered_view

+ def filter_labels_by_classes(sample_collection, classes):
+     """Filters labels in the sample collection to include only specified classes."""
+     label_fields = get_label_fields(sample_collection)
+     for lf in label_fields:
+         sample_collection = sample_collection.filter_labels(
+             lf, F("label").is_in(classes), only_matches=False
+         )
+     return sample_collection

+ # Usage
+ filtered_view = filter_labels_by_classes(dataset, ["person", "car", "truck"])

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"def get_label_fields(sample_collection):\n",
" \"\"\"Get the (detection) label fields of a Dataset or DatasetView.\"\"\"\n",
" label_fields = list(\n",
" sample_collection.get_field_schema(embedded_doc_type=fo.Detections).keys()\n",
" )\n",
" return label_fields\n",
"\n",
"def filter_all_labels(sample_collection):\n",
" label_fields = get_label_fields(sample_collection)\n",
"\n",
" filtered_view = sample_collection\n",
"\n",
" for lf in label_fields:\n",
" filtered_view = filtered_view.filter_labels(\n",
" lf, F(\"label\").is_in([\"person\", \"car\", \"truck\"]), only_matches=False\n",
" )\n",
" return filtered_view"
"def get_label_fields(sample_collection):\n",
" \"\"\"Get the (detection) label fields of a Dataset or DatasetView.\"\"\"\n",
" label_fields = list(\n",
" sample_collection.get_field_schema(embedded_doc_type=fo.Detections).keys()\n",
" )\n",
" return label_fields\n",
"\n",
"def filter_labels_by_classes(sample_collection, classes):\n",
" \"\"\"Filters labels in the sample collection to include only specified classes.\"\"\"\n",
" label_fields = get_label_fields(sample_collection)\n",
" for lf in label_fields:\n",
" sample_collection = sample_collection.filter_labels(\n",
" lf, F(\"label\").is_in(classes), only_matches=False\n",
" )\n",
" return sample_collection\n",
"\n",
"# Usage\n",
"filtered_view = filter_labels_by_classes(dataset, [\"person\", \"car\", \"truck\"])"

Comment on lines +364 to +370
"detection_model = AutoDetectionModel.from_pretrained(\n",
" model_type='yolov8',\n",
" model_path=ckpt_path,\n",
" confidence_threshold=0.25, ## same as the default value for our base model\n",
" image_size=640,\n",
" device=\"cpu\", # or 'cuda'\n",
")"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consider adding error handling for model loading and setting a default device based on availability.

- detection_model = AutoDetectionModel.from_pretrained(
-     model_type='yolov8',
-     model_path=ckpt_path,
-     confidence_threshold=0.25, ## same as the default value for our base model
-     image_size=640,
-     device="cpu", # or 'cuda'
- )

+ try:
+     device = "cuda" if torch.cuda.is_available() else "cpu"
+     detection_model = AutoDetectionModel.from_pretrained(
+         model_type='yolov8',
+         model_path=ckpt_path,
+         confidence_threshold=0.25,
+         image_size=640,
+         device=device
+     )
+ except Exception as e:
+     print(f"Failed to load model: {e}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"detection_model = AutoDetectionModel.from_pretrained(\n",
" model_type='yolov8',\n",
" model_path=ckpt_path,\n",
" confidence_threshold=0.25, ## same as the default value for our base model\n",
" image_size=640,\n",
" device=\"cpu\", # or 'cuda'\n",
")"
try:
device = "cuda" if torch.cuda.is_available() else "cpu"
detection_model = AutoDetectionModel.from_pretrained(
model_type='yolov8',
model_path=ckpt_path,
confidence_threshold=0.25,
image_size=640,
device=device
)
except Exception as e:
print(f"Failed to load model: {e}")

Comment on lines +739 to +743
"def predict_with_slicing(sample, label_field, **kwargs):\n",
" result = get_sliced_prediction(\n",
" sample.filepath, detection_model, verbose=0, **kwargs\n",
" )\n",
" sample[label_field] = fo.Detections(detections=result.to_fiftyone_detections())"
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Add error handling for the predict_with_slicing function to manage exceptions during prediction.

- def predict_with_slicing(sample, label_field, **kwargs):
-     result = get_sliced_prediction(
-         sample.filepath, detection_model, verbose=0, **kwargs
-     )
-     sample[label_field] = fo.Detections(detections=result.to_fiftyone_detections())

+ def predict_with_slicing(sample, label_field, **kwargs):
+     try:
+         result = get_sliced_prediction(
+             sample.filepath, detection_model, verbose=0, **kwargs
+         )
+         sample[label_field] = fo.Detections(detections=result.to_fiftyone_detections())
+     except Exception as e:
+         print(f"Error during slicing prediction: {e}")

Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation.

Suggested change
"def predict_with_slicing(sample, label_field, **kwargs):\n",
" result = get_sliced_prediction(\n",
" sample.filepath, detection_model, verbose=0, **kwargs\n",
" )\n",
" sample[label_field] = fo.Detections(detections=result.to_fiftyone_detections())"
def predict_with_slicing(sample, label_field, **kwargs):
try:
result = get_sliced_prediction(
sample.filepath, detection_model, verbose=0, **kwargs
)
sample[label_field] = fo.Detections(detections=result.to_fiftyone_detections())
except Exception as e:
print(f"Error during slicing prediction: {e}")

@fcakyon
Copy link

fcakyon commented Apr 13, 2024

Hey @jacobmarks, thanks for the great tutorial on our work SAHI!

It would be better if you could add a link to the original SAHI paper published in ICIP2022 in the first page of the blog.

@brimoor
Copy link
Contributor

brimoor commented Apr 13, 2024

@fcakyon link added! 51cca80

Copy link
Contributor

@brimoor brimoor left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM and will include in 0.23.8 docs release 🤗

@brimoor brimoor merged commit eacb00c into develop Apr 13, 2024
8 checks passed
@brimoor brimoor deleted the docs/sahi-tutorial branch April 13, 2024 15:18
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

None yet

3 participants