diff --git a/docs/notebooks/index.ipynb b/docs/notebooks/index.ipynb
index e5d2c9d9..c612a04e 100644
--- a/docs/notebooks/index.ipynb
+++ b/docs/notebooks/index.ipynb
@@ -57,7 +57,8 @@
"| [**Image Features**](./image-features.ipynb) | Point/corner detection (SIFT, ORB, etc.). |\n",
"| [**Fiducial Markers**](./fiducials.ipynb) | Detecting ArUco markers and QR-like codes. |\n",
"| [**Image Motion**](./image-motion.ipynb) | Relationship between camera motion (3D) and image (2D). |\n",
- "| [**Visual Servoing**](./IBVS.ipynb) | Image-Based Visual Servoing (IBVS). |"
+ "| [**Visual Servoing**](./IBVS.ipynb) | Image-Based Visual Servoing (IBVS). |\n",
+ "| [**CNNs**](./torch.ipynb) | Semantic segmentation & object detection with CNNs. |"
]
},
{
diff --git a/docs/notebooks/torch.ipynb b/docs/notebooks/torch.ipynb
new file mode 100644
index 00000000..f17972fc
--- /dev/null
+++ b/docs/notebooks/torch.ipynb
@@ -0,0 +1,555 @@
+{
+ "cells": [
+ {
+ "cell_type": "markdown",
+ "id": "0f90fd53",
+ "metadata": {},
+ "source": [
+ "
\n",
+ " \n",
+ " Using Torch with Machine Vision Toolbox for Python | \n",
+ "  | \n",
+ "
\n",
+ "
\n",
+ "\n",
+ "A quick, runnable introduction to the toolbox. Works locally, on Google Colab, or entirely in your browser via [JupyterLite](https://jupyterlite.readthedocs.io) and [Pyodide](https://pyodide.org) -- no installation required either way. The cell below installs the toolbox the first time it is run (and will take a few seconds on Colab or in the browser)."
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "55ccabfc",
+ "metadata": {},
+ "source": [
+ "## Configuring the Jupyter environment\n",
+ "We need to import some packages to help us with linear algebra (`numpy`), graphics (`matplotlib`), and machine vision (`machinevisiontoolbox`). If you're running locally you need to have these packages installed.\n",
+ "\n",
+ "\n",
+ "If you're running on CoLab or in the browser we have to first install machinevisiontoolbox, which is not preinstalled, so the next cell will be slow.\n",
+ "\n",
+ "This notebook cannot be run in the browser. torch and torchvision are not pure Python packages and are not included in Pyodide's built-in packages.\n",
+ "
"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "mvtb-bootstrap-cell",
+ "metadata": {
+ "jupyter": {
+ "source_hidden": true
+ }
+ },
+ "outputs": [],
+ "source": [
+ "# MVTB_BOOTSTRAP_CELL: installs the package, which takes a short time, so wait for the line \"Running ...\" below. Generated by sync_bootstrap.py from _mvtb_nb_bootstrap.py, do not edit\n",
+ "\n",
+ "import subprocess\n",
+ "import sys\n",
+ "PACKAGE = 'machinevision-toolbox-python'\n",
+ "IMPORT_NAME = 'machinevisiontoolbox'\n",
+ "GIT_URL: str | None = 'https://github.com/petercorke/machinevision-toolbox-python'\n",
+ "JL_PACKAGES = ['numpy', 'scipy', 'matplotlib', 'ipympl', 'pillow', 'typing_extensions', 'opencv-python', 'ansitable', 'mvtb-data', 'tqdm', 'requests', 'ipywidgets', 'spatialmath-python', 'pgraph-python']\n",
+ "JL_NO_DEPS: list[str] = []\n",
+ "JL_PACKAGE_NO_DEPS = True\n",
+ "JL_EXTRAS: dict[str, list[str]] = {}\n",
+ "COLAB_PACKAGES: list[str] = []\n",
+ "\n",
+ "def _version_of(package: str, module) -> str:\n",
+ " import importlib.metadata\n",
+ " try:\n",
+ " return importlib.metadata.version(package)\n",
+ " except importlib.metadata.PackageNotFoundError:\n",
+ " return str(getattr(module, '__version__', 'unknown'))\n",
+ "\n",
+ "def _older(version: str, required: str) -> bool:\n",
+ " try:\n",
+ " from packaging.version import InvalidVersion, Version\n",
+ " return Version(version) < Version(required)\n",
+ " except (ImportError, InvalidVersion):\n",
+ " return False\n",
+ "\n",
+ "async def ensure_installed(extras: tuple[str, ...] | list[str]=(), packages: tuple[str, ...] | list[str]=(), min_version: str | None=None) -> bool:\n",
+ " if sys.platform == 'emscripten':\n",
+ " try:\n",
+ " import piplite\n",
+ " install = piplite.install\n",
+ " except ImportError:\n",
+ " import micropip\n",
+ " install = micropip.install\n",
+ " print(f'Installing {PACKAGE}, this takes a short time...', flush=True)\n",
+ " for name in JL_NO_DEPS:\n",
+ " await install(name, deps=False)\n",
+ " for name in JL_PACKAGES:\n",
+ " await install(name)\n",
+ " for extra in extras:\n",
+ " for name in JL_EXTRAS.get(extra, []):\n",
+ " await install(name)\n",
+ " for name in packages:\n",
+ " await install(name)\n",
+ " await install(PACKAGE, deps=not JL_PACKAGE_NO_DEPS)\n",
+ " where, colab = ('in browser', False)\n",
+ " else:\n",
+ " try:\n",
+ " import google.colab\n",
+ " except ImportError:\n",
+ " where, colab = ('locally', False)\n",
+ " else:\n",
+ " print(f'Installing {PACKAGE}, this takes a short time...', flush=True)\n",
+ " requirement = PACKAGE\n",
+ " if extras:\n",
+ " requirement += '[' + ','.join(extras) + ']'\n",
+ " subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', requirement] + list(packages) + COLAB_PACKAGES, check=True)\n",
+ " try:\n",
+ " from matplotlib.backends import backend_registry\n",
+ " except ImportError:\n",
+ " pass\n",
+ " else:\n",
+ " clear = getattr(backend_registry, '_clear', None)\n",
+ " if clear is not None:\n",
+ " clear()\n",
+ " from google.colab import output\n",
+ " output.enable_custom_widget_manager()\n",
+ " where, colab = ('on Colab', True)\n",
+ " import importlib\n",
+ " module = importlib.import_module(IMPORT_NAME)\n",
+ " version = _version_of(PACKAGE, module)\n",
+ " if colab and min_version is not None and _older(version, min_version) and GIT_URL:\n",
+ " print(f'{PACKAGE} {version} on PyPI is older than {min_version}, installing from GitHub...')\n",
+ " subprocess.run([sys.executable, '-m', 'pip', 'install', '-q', '--force-reinstall', '--no-deps', f'{PACKAGE} @ git+{GIT_URL}@main'], check=True)\n",
+ " importlib.invalidate_caches()\n",
+ " version = _version_of(PACKAGE, module)\n",
+ " where += ', development version from GitHub'\n",
+ " if not colab and where == 'locally':\n",
+ " import importlib.metadata\n",
+ " for name in packages:\n",
+ " try:\n",
+ " importlib.metadata.version(name)\n",
+ " except importlib.metadata.PackageNotFoundError:\n",
+ " print(f'This notebook needs {name}: pip install {name}')\n",
+ " if min_version is not None and where in ('locally', 'on Colab') and _older(version, min_version):\n",
+ " print(f'This notebook needs {PACKAGE} {min_version} or later: pip install -U {PACKAGE}')\n",
+ " print(f'Running {where} using {PACKAGE} v{version}')\n",
+ " return colab\n",
+ "\n",
+ "COLAB = await ensure_installed()\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "4bd104d5",
+ "metadata": {},
+ "source": [
+ "# Setting up\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "f7fe1ab4",
+ "metadata": {},
+ "source": [
+ "You must have TorchVision installed\n",
+ "\n",
+ "```shell\n",
+ "$ pip install torchvision\n",
+ "$ pip install torch\n",
+ "```\n",
+ "\n",
+ "or \n",
+ "\n",
+ "```shell\n",
+ "pip install machinevision-toolbox-python[torch]\n",
+ "```"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3f97ad48",
+ "metadata": {},
+ "source": [
+ "Next, we import the packages we will need: `machinevisiontoolbox`, `matplotlib`, and `torchvision`."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4fc8b259",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "%matplotlib ipympl\n",
+ "import matplotlib.pyplot as plt\n",
+ "plt.close(\"all\") # re-running the notebook from the top starts with no figures\n",
+ "\n",
+ "from machinevisiontoolbox import Image\n",
+ "import torchvision as tv"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "fe77ee73",
+ "metadata": {},
+ "source": [
+ "We will use the complex scene given as Fig 12.7 of Robotics, Vision & Control, 3rd edition, p. 492."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c342305d",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "scene = Image.Read(\"image3.jpg\")\n",
+ "scene.disp()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "26dd6966",
+ "metadata": {},
+ "source": [
+ "Each object comprises a range of pixel intensities and colors so simple pixel-level algorithms cannot work. Instead, we will use ResNet50, a 50-layer convolutional neural network for computer vision that uses residual \"skip connections\" to perform semantic segmentation.\n",
+ "\n",
+ "We use a pretrained ResNet50 model from torchvision which was trained on a subset of the [COCO 2017 dataset](https://huggingface.co/datasets/rafaelpadilla/coco2017) using only the 20 object categories that overlap with [Pascal VOC dataset](https://www.robots.ox.ac.uk/~vgg/projects/pascal/VOC/), plus a background class 21 classes in all."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6a6709de",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "model = tv.models.segmentation.fcn_resnet50(\n",
+ " weights=tv.models.segmentation.FCN_ResNet50_Weights.COCO_WITH_VOC_LABELS_V1\n",
+ ").eval()"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0f35971d",
+ "metadata": {},
+ "source": [
+ "A `machinevisiontoolbox` image must be transformed before it can be used by the ResNet50 model. It must first be converted to a \"tensor\" and then normalized so that its mean is zero and its standard deviation is one."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "33e3a43a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "in_tensor = scene.tensor(normalize=\"imagenet\")\n",
+ "print(\"Input tensor type:\", type(in_tensor))\n",
+ "print(\"Input tensor shape:\", in_tensor.shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "ce8cdb35",
+ "metadata": {},
+ "source": [
+ "The tensor is a C++ object that behaves somewhat like a NumPy array. The dimensions of this one are: number of images in the sequence, number of planes per image, image height, image width.\n",
+ "\n",
+ "The tensor is passed to the model and the result is a `dict`"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "deca560c",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "outputs = model(in_tensor)\n",
+ "print(\"type(outputs):\", type(outputs))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0d7fb524",
+ "metadata": {},
+ "source": [
+ "and the elements of that `dict` are tensors"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "ffb851c8",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "for item, value in outputs.items():\n",
+ " print(f\"Type of {item}: {type(value)}\")"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "b42b2a34",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Shape of outputs[\\\"out\\\"]:\", outputs[\"out\"].shape)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "603e50a4",
+ "metadata": {},
+ "source": [
+ "The inference result is essentially a 21-plane image with one plane per class. For every pixel the index of the plane with the highest value is the class label of that pixel.\n",
+ "\n",
+ "The `machinevisiontoolbox` can convert the inference result (a dict of tensors) into a class label image"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "4ee60948",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "seg = Image.Tensor(outputs, logits=True)\n",
+ "seg.disp();"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "2447c655",
+ "metadata": {},
+ "source": [
+ "We can see that different objects in the scene appear as different grey values. Exploring those values with the cursor we see that people correspond to a value of 15, and dogs to the value 12.\n",
+ "\n",
+ "These are the class labels that indicate the semantic meaning of each pixel. The network we used was trained on the Pascal VOC dataset which defines the following classes\n"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "fc7ea799",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "class_names = [\n",
+ " \"Background\",\n",
+ " \"Aeroplane\",\n",
+ " \"Bicycle\",\n",
+ " \"Bird\",\n",
+ " \"Boat\",\n",
+ " \"Bottle\",\n",
+ " \"Bus\",\n",
+ " \"Car\",\n",
+ " \"Cat\",\n",
+ " \"Chair\",\n",
+ " \"Cow\",\n",
+ " \"Dining Table\",\n",
+ " \"Dog\",\n",
+ " \"Horse\",\n",
+ " \"Motorbike\",\n",
+ " \"Person\",\n",
+ " \"Potted Plant\",\n",
+ " \"Sheep\",\n",
+ " \"Sofa\",\n",
+ " \"Train\",\n",
+ " \"TV/Monitor\",\n",
+ "]"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0dc60336",
+ "metadata": {},
+ "source": [
+ "Using this list we can map class labels to class names"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "17852b95",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(class_names[15])\n",
+ "print(class_names[12])"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "043d13c7",
+ "metadata": {},
+ "source": [
+ "With a bit more effort we can display this with class labels as colors, and a colorbar showing the mapping from class index to color"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "9fc8b95a",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "seg.disp(\n",
+ " colormap=\"viridis\",\n",
+ " ncolors=20,\n",
+ " colorbar=dict(xticks=[range(21), class_names]),\n",
+ ");\n"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0eb8ec07",
+ "metadata": {},
+ "source": [
+ "# YOLO bounding boxes\n",
+ "\n",
+ "This example demonstrates how to use a pretrained object detection model to\n",
+ "detect objects in an image and display the results with bounding boxes and class\n",
+ "labels. \n",
+ "\n",
+ "We will perform object detection using the well-known YOLO model, in particular we will use\n",
+ "the latest YOLO26 nano model from the ultralytics library. This model is very fast and\n",
+ "avoids using Non-Maximum Suppression (NMS) to reject overlapping boxes, instead it natively outputs a single box per object.\n",
+ "\n",
+ "We first need to install the ultralytics library which provides a PyTorch implementation of the YOLO object detection model\n",
+ "\n",
+ "\n",
+ "```shell\n",
+ "$ pip install ultralytics\n",
+ "```\n",
+ "or \n",
+ "\n",
+ "```shell\n",
+ "pip install machinevision-toolbox-python[ultralytics]\n",
+ "```\n",
+ "\n",
+ "We first import `YOLO`"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "6b53cd95",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from ultralytics import YOLO"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "d069a26e",
+ "metadata": {},
+ "source": [
+ "The model needs the neural weights and these are downloaded to your current folder."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "23fc8fd9",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "model = YOLO(\"yolo26n.pt\")"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "7a782d33",
+ "metadata": {},
+ "source": [
+ "and then run inference on the image as a Numpy array. We do not have to do the normalization or conversion to a tensor as we did with the ResNet50 model earlier."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "c89ad9a3",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "results = model(scene.array)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "3767ea03",
+ "metadata": {},
+ "source": [
+ "The return value `results` is a list of results (one per image, but we only have one image here), and the results are packed into a `Results` instance."
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "bbb7a785",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "print(\"Length of results:\", len(results))\n",
+ "print(\"Type of results[0]:\", type(results[0]))"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "0eb1d0af",
+ "metadata": {},
+ "source": [
+ "The results are still in GPU memory and we need to get the data back onto the CPU and convert to Numpy arrays so that we can work with them in Python"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "301f1260",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "boxes = results[0].boxes.xyxy.cpu().numpy() # [xmin, ymin, xmax, ymax]\n",
+ "classes = results[0].boxes.cls.cpu().numpy()\n",
+ "\n",
+ "print(boxes)\n",
+ "print(classes)"
+ ]
+ },
+ {
+ "cell_type": "markdown",
+ "id": "8af88560",
+ "metadata": {},
+ "source": [
+ "We see that `boxes` is a 2d-array with one row per box organized as `[xmin, ymin, xmax, ymax]`, and `classes` is a 1d-array with one class label per box.\n",
+ "\n",
+ "Now we will overlay the boxes and the class labels on the image"
+ ]
+ },
+ {
+ "cell_type": "code",
+ "execution_count": null,
+ "id": "e42bb7ec",
+ "metadata": {},
+ "outputs": [],
+ "source": [
+ "from machinevisiontoolbox.base import plot_labelbox\n",
+ "scene.disp()\n",
+ "for box, class_id in zip(boxes, classes):\n",
+ " plot_labelbox(f\"{model.names[class_id]}\", lbrt=box, color=\"red\")"
+ ]
+ }
+ ],
+ "metadata": {
+ "kernelspec": {
+ "display_name": "Python 3",
+ "language": "python",
+ "name": "python3"
+ },
+ "language_info": {
+ "name": "python"
+ }
+ },
+ "nbformat": 4,
+ "nbformat_minor": 5
+}
diff --git a/pyproject.toml b/pyproject.toml
index ab416dd5..83620a50 100644
--- a/pyproject.toml
+++ b/pyproject.toml
@@ -88,7 +88,9 @@ jupyter = ["ipywidgets", "ipympl"]
open3d = ["open3d"]
-torch = ["torch"]
+torch = ["torch", "torchvision"]
+
+ultralytics = ["torch", "torchvision", "ultralytics"]
ocr = ["pytesseract"]
@@ -97,6 +99,8 @@ all = [
"ipympl",
"open3d",
"torch",
+ "torchvision",
+ "ultralytics",
"pytesseract",
"rosbags",
"roslibpy",