Skip to content

🐍 Geometric Computer Vision Library for Spatial AI

Remove examples in favor of `kornia/tutorials` repo (#2366)

João Gustavo A. Amorim428e461baf81
diff --git a/Makefile b/Makefile
index a93cd9358..a62945cfe 100644
--- a/Makefile
+++ b/Makefile
@@ -39,7 +39,7 @@ mypy: FORCE
mypy
yapf: FORCE
- yapf --in-place --parallel --recursive kornia/ test/ examples/
+ yapf --in-place --parallel --recursive kornia/ test/
doctest:
pytest -v --doctest-modules kornia/
diff --git a/docs/Makefile b/docs/Makefile
index d85a34c26..4786ee858 100644
--- a/docs/Makefile
+++ b/docs/Makefile
@@ -24,4 +24,4 @@ clean:
@rm -rf $(BUILDDIR)/html/ $(BUILDDIR)/doctrees
images:
- python3 generate_example_images.py
+ python3 generate_examples.py
diff --git a/docs/generate_example_images.py b/docs/generate_examples.py
similarity index 95%
rename from docs/generate_example_images.py
rename to docs/generate_examples.py
index e8b06d35b..23b9e2182 100644
--- a/docs/generate_example_images.py
+++ b/docs/generate_examples.py
@@ -1,13 +1,12 @@
-import matplotlib
+from __future__ import annotations
-matplotlib.use("Agg")
import importlib
import math
import os
from pathlib import Path
-from typing import Optional, Tuple
import cv2
+import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import requests
@@ -17,8 +16,22 @@ from kornia_moons.feature import visualize_LAF
import kornia as K
from kornia.core import Tensor
+matplotlib.use("Agg")
+
+
+def download_tutorials_examples(download_infos: dict[str, str], directory: Path):
+ URL_BASE = 'https://raw.githubusercontent.com/kornia/tutorials/master/'
+ for filename, path in download_infos.items():
+ url = URL_BASE + path
+ # perform request
+ response = requests.get(url, timeout=60).content
-def read_img_from_url(url: str, resize_to: Optional[Tuple[int, int]] = None) -> torch.Tensor:
+ path = directory / filename
+ with open(path, 'wb') as fp:
+ fp.write(response)
+
+
+def read_img_from_url(url: str, resize_to: tuple[int, int] | None = None) -> torch.Tensor:
# perform request
response = requests.get(url, timeout=60).content
# convert to array of ints
@@ -35,7 +48,7 @@ def read_img_from_url(url: str, resize_to: Optional[Tuple[int, int]] = None) ->
return img_t
-def transparent_pad(src: Tensor, shape: Tuple[int, int]) -> Tensor:
+def transparent_pad(src: Tensor, shape: tuple[int, int]) -> Tensor:
"""Apply a transparent pad to src (centerized) to match with shape (h, w)"""
w_pad = abs(int(src.shape[-1] - shape[-1]) // 2)
h_pad = abs(int(src.shape[-2] - shape[-2]) // 2)
@@ -64,6 +77,19 @@ def draw_bbox_kpts(imgs, bboxes, keypoints):
def main():
+ # Download the tutorial examples for the main docs
+ URLS_TUTORIALS_EXAMPLES = {
+ 'image_classifier.py': 'scripts/training/image_classifier/main.py',
+ 'object_detection.py': 'scripts/training/object_detection/main.py',
+ 'semantic_segmentation.py': 'scripts/training/semantic_segmentation/main.py',
+ }
+
+ OUTPUT_PATH_SCRIPTS = Path(__file__).absolute().parent / "source/_static/scripts/"
+
+ os.makedirs(OUTPUT_PATH_SCRIPTS, exist_ok=True)
+ print(f"Downloading script examples from kornia/tutorials. Saving into the path {OUTPUT_PATH_SCRIPTS}.")
+ download_tutorials_examples(URLS_TUTORIALS_EXAMPLES, OUTPUT_PATH_SCRIPTS)
+
# load the images
BASE_IMAGE_URL1: str = "https://raw.githubusercontent.com/kornia/data/main/panda.jpg" # augmentation
BASE_IMAGE_URL2: str = "https://raw.githubusercontent.com/kornia/data/main/simba.png" # color
diff --git a/docs/source/applications/face_detection.rst b/docs/source/applications/face_detection.rst
index 49a85a1f6..0bc858a90 100644
--- a/docs/source/applications/face_detection.rst
+++ b/docs/source/applications/face_detection.rst
@@ -15,20 +15,27 @@ Learn more: `https://paperswithcode.com/task/face-detection <https://paperswithc
Using our API you easily detect faces in images as shown below:
-.. literalinclude:: ../../../examples/face_detection/main.py
- :language: python
- :lines: 36-54
+.. code-block:: python
-Check the full example `here <https://github.com/kornia/kornia/tree/master/examples/face_detection/main.py>`_
-or run a real-time application using the camera with this `example <https://github.com/kornia/kornia/tree/master/examples/face_detection/main_video.py>`_.
+ # select the device
+ device = torch.device('cpu')
+ if args.cuda and torch.cuda.is_available():
+ device = torch.device('cuda:0')
-The Kornia AI Game
-------------------
+ # load the image and scale
+ img_raw = cv2.imread(args.image_file, cv2.IMREAD_COLOR)
+ img_raw = scale_image(img_raw, args.image_size)
- .. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/face_detection_7_1.png
- :width: 49 %
- .. image:: https://kornia-tutorials.readthedocs.io/en/latest/_images/face_detection_13_1.png
- :width: 49 %
+ # preprocess
+ img = K.image_to_tensor(img_raw, keepdim=False).to(device)
+ img = K.color.bgr_to_rgb(img.float())
-.. tip::
- Play yourself with the detector and generate new images with this `tutorial <https://kornia-tutorials.readthedocs.io/en/latest/face_detection.html>`_.
+ # create the detector and find the faces !
+ face_detection = FaceDetector().to(device)
+
+ with torch.no_grad():
+ dets = face_detection(img)
+ dets = [FaceDetectorResult(o) for o in dets[0]]
+
+
+Play yourself with the detector and generate new images with this `tutorial <https://kornia-tutorials.readthedocs.io/en/latest/_nbs/face_detection.html>`_.
diff --git a/docs/source/applications/image_classification.rst b/docs/source/applications/image_classification.rst
index 621652a73..be8b6c72f 100644
--- a/docs/source/applications/image_classification.rst
+++ b/docs/source/applications/image_classification.rst
@@ -47,21 +47,29 @@ image classification problems. However, one can leverage this is API using the m
use existing libraries from the PyTorch ecosystem such as `torchvision <https://pytorch.org/vision/stable/models.html>`_
or `timm <https://rwightman.github.io/pytorch-image-models/>`_.
-.. literalinclude:: ../../../examples/train/image_classifier/main.py
+Create the dataloaders:
+
+.. literalinclude:: ../_static/scripts/image_classifier.py
+ :language: python
+ :lines: 20-36
+
+Define your model, losses, optimizers and schedulers:
+
+.. literalinclude:: ../_static/scripts/image_classifier.py
:language: python
- :lines: 20-46
+ :lines: 37-48
-Define your augmentations and callbacks:
+Define your augmentations:
-.. literalinclude:: ../../../examples/train/image_classifier/main.py
+.. literalinclude:: ../_static/scripts/image_classifier.py
:language: python
- :lines: 49-66
+ :lines: 50-65
Finally, instantiate the :py:class:`~kornia.x.ImageClassifierTrainer` and execute your training pipeline.
-.. literalinclude:: ../../../examples/train/image_classifier/main.py
+.. literalinclude:: ../_static/scripts/image_classifier.py
:language: python
- :lines: 68-74
+ :lines: 66-78
.. seealso::
- Play with the full example `here <https://github.com/kornia/kornia/tree/master/examples/train/image_classifier>`_
+ Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier>`_
diff --git a/docs/source/applications/object_detection.rst b/docs/source/applications/object_detection.rst
new file mode 100644
index 000000000..ea3fa81b4
--- /dev/null
+++ b/docs/source/applications/object_detection.rst
@@ -0,0 +1,54 @@
+Object detection
+================
+
+.. image:: https://production-media.paperswithcode.com/thumbnails/task/task-0000000004-7757802e.jpg
+ :align: right
+ :width: 40%
+
+Object detection consists in detecting objects belonging to a certain category from an image,
+determining the absolute location and also assigning each detected instance a predefined category.
+In the last few years, several models have emerged based on deep learning. Being the state of the art
+models being based on two stages. First, regions with higher recall values are located, so that all
+objects in the image adhere to the proposed regions. The second stage consists of classification models,
+usually CNNs, used to determine the category of each proposed region (instances).
+
+Learn more: `https://paperswithcode.com/task/object-detection <https://paperswithcode.com/task/object-detection>`_
+
+Finetuning
+----------
+
+In order to customize your model with your own data you can use our :ref:`training_api` to perform the
+`fine-tuning <https://paperswithcode.com/methods/category/fine-tuning>`_ of your model.
+
+We provide :py:class:`~kornia.x.ObjectDetectionTrainer`
+with a default training structure to train object detection problems. However, one can leverage this is
+API using the models provided by Kornia or use existing libraries from the PyTorch ecosystem such
+as `torchvision <https://pytorch.org/vision/stable/models.html>`_.
+
+Create the dataloaders and transforms:
+
+.. literalinclude:: ../_static/scripts/object_detection.py
+ :language: python
+ :lines: 17-39
+
+Define your model, losses, optimizers and schedulers:
+
+.. literalinclude:: ../_static/scripts/object_detection.py
+ :language: python
+ :lines: 40-50
+
+Create your preprocessing and augmentations pipeline:
+
+.. literalinclude:: ../_static/scripts/object_detection.py
+ :language: python
+ :lines: 50-90
+
+Finally, instantiate the :py:class:`~kornia.x.ObjectDetectionTrainer`
+and execute your training pipeline.
+
+.. literalinclude:: ../_static/scripts/object_detection.py
+ :language: python
+ :lines: 90-111
+
+.. seealso::
+ Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/object_detection>`_
diff --git a/docs/source/applications/semantic_segmentation.rst b/docs/source/applications/semantic_segmentation.rst
index 8b7858ab1..014619669 100644
--- a/docs/source/applications/semantic_segmentation.rst
+++ b/docs/source/applications/semantic_segmentation.rst
@@ -24,27 +24,27 @@ use existing libraries from the PyTorch ecosystem such as `torchvision <https://
Create the dataloaders and transforms:
-.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py
+.. literalinclude:: ../_static/scripts/semantic_segmentation.py
:language: python
:lines: 17-50
Define your model, losses, optimizers and schedulers:
-.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py
+.. literalinclude:: ../_static/scripts/semantic_segmentation.py
:language: python
:lines: 52-60
Create your preprocessing and augmentations pipeline:
-.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py
+.. literalinclude:: ../_static/scripts/semantic_segmentation.py
:language: python
:lines: 62-81
Finally, instantiate the :py:class:`~kornia.x.SemanticSegmentationTrainer` and execute your training pipeline.
-.. literalinclude:: ../../../examples/train/semantic_segmentation/main.py
+.. literalinclude:: ../_static/scripts/semantic_segmentation.py
:language: python
:lines: 83-91
.. seealso::
- Play with the full example `here <https://github.com/kornia/kornia/tree/master/examples/train/semantic_segmentation>`_
+ Play with the full example `here <https://github.com/kornia/tutorials/tree/master/scripts/training/semantic_segmentation>`_
diff --git a/docs/source/conf.py b/docs/source/conf.py
index 8058cd5e1..4847ab0b3 100644
--- a/docs/source/conf.py
+++ b/docs/source/conf.py
@@ -6,12 +6,12 @@ import sys
# by cloning the git repo. Thus, any on-the-fly operation will not effect
# on the resulting documentation. We therefore need to import and run the
# corresponding code here.
-spec = importlib.util.spec_from_file_location("generate_example_images", "../generate_example_images.py")
-generate_example_images = importlib.util.module_from_spec(spec)
-spec.loader.exec_module(generate_example_images)
+spec = importlib.util.spec_from_file_location("generate_examples", "../generate_examples.py")
+generate_examples = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(generate_examples)
# Pre-generate the example images
-generate_example_images.main()
+generate_examples.main()
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
diff --git a/docs/source/get-started/training.rst b/docs/source/get-started/training.rst
index c240dc0f5..f7a7063a7 100644
--- a/docs/source/get-started/training.rst
+++ b/docs/source/get-started/training.rst
@@ -225,7 +225,7 @@ Use `hydra <https://hydra.cc>`_ to implement an easy search strategy for your hy
.. note::
- Checkout the toy example in `here <https://github.com/kornia/kornia/tree/master/examples/train/image_classifier>`__
+ Checkout the toy example in `here <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier>`__
.. code:: python
diff --git a/docs/source/index.rst b/docs/source/index.rst
index 380f4a701..ad88ad482 100644
--- a/docs/source/index.rst
+++ b/docs/source/index.rst
@@ -84,6 +84,7 @@ Join the community
applications/image_registration
applications/image_denoising
applications/semantic_segmentation
+ applications/object_detection
.. toctree::
:caption: KORNIA MODELS
diff --git a/kornia/x/trainers.py b/kornia/x/trainers.py
index a7b10e588..af753b208 100644
--- a/kornia/x/trainers.py
+++ b/kornia/x/trainers.py
@@ -19,7 +19,7 @@ class ImageClassifierTrainer(Trainer):
.. seealso::
Learn how to use this class in the following
- `example <https://github.com/kornia/kornia/blob/master/examples/train/image_classifier/>`__.
+ `example <https://github.com/kornia/tutorials/tree/master/scripts/training/image_classifier/>`__.
"""
def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
@@ -38,7 +38,7 @@ class SemanticSegmentationTrainer(Trainer):
.. seealso::
Learn how to use this class in the following
- `example <https://github.com/kornia/kornia/blob/master/examples/train/semantic_segmentation/>`__.
+ `example <https://github.com/kornia/tutorials/tree/master/scripts/training/semantic_segmentation/>`__.
"""
def compute_metrics(self, *args: Tensor) -> Dict[str, float]:
@@ -57,7 +57,7 @@ class ObjectDetectionTrainer(Trainer):
.. seealso::
Learn how to use this class in the following
- `example <https://github.com/kornia/kornia/blob/master/examples/train/object_detection/>`__.
+ `example <https://github.com/kornia/tutorials/tree/master/scripts/training/object_detection/>`__.
"""
def __init__(
diff --git a/pyproject.toml b/pyproject.toml
index d47c42d4a..40e34f63d 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -164,8 +164,7 @@ max-statements = 258
[tool.ruff.per-file-ignores]
"*/__init__.py" = ["F401"]
"docs/*" = ["S101", "S113"]
-"docs/generate_example_images.py" = ["C901", "PLR0912", "PLR0915"]
-"examples/train/object_detection/main.py" = ["E741"]
+"docs/generate_examples.py" = ["C901", "PLR0912", "PLR0915"]
"kornia/__init__.py" = ["I001"]
"kornia/augmentation/container/base.py" = ["PLC1901"]
"kornia/color/hls.py" = ["E741"]