{
  "nbformat": 4,
  "nbformat_minor": 0,
  "metadata": {
    "colab": {
      "provenance": [],
      "gpuType": "T4"
    },
    "kernelspec": {
      "name": "python3",
      "display_name": "Python 3"
    },
    "language_info": {
      "name": "python"
    },
    "accelerator": "GPU"
  },
  "cells": [
    {
      "cell_type": "markdown",
      "source": [
        "<div align=\"center\">\n",
        "\n",
        "  <a href=\"https://ultralytics.com/yolov8\" target=\"_blank\">\n",
        "    <img width=\"1024\", src=\"https://raw.githubusercontent.com/ultralytics/assets/main/yolov8/banner-yolov8.png\"></a>\n",
        "\n",
        "  [中文](https://docs.ultralytics.com/zh/) | [한국어](https://docs.ultralytics.com/ko/) | [日本語](https://docs.ultralytics.com/ja/) | [Русский](https://docs.ultralytics.com/ru/) | [Deutsch](https://docs.ultralytics.com/de/) | [Français](https://docs.ultralytics.com/fr/) | [Español](https://docs.ultralytics.com/es/) | [Português](https://docs.ultralytics.com/pt/) | [हिन्दी](https://docs.ultralytics.com/hi/) | [العربية](https://docs.ultralytics.com/ar/)\n",
        "\n",
        "  <a href=\"https://colab.research.google.com/github/ultralytics/ultralytics/blob/main/examples/object_tracking.ipynb\"><img src=\"https://colab.research.google.com/assets/colab-badge.svg\" alt=\"Open In Colab\"></a>\n",
        "\n",
        "Welcome to the Ultralytics YOLOv8 🚀 notebook! <a href=\"https://github.com/ultralytics/ultralytics\">YOLOv8</a> is the latest version of the YOLO (You Only Look Once) AI models developed by <a href=\"https://ultralytics.com\">Ultralytics</a>. This notebook serves as the starting point for exploring the <a href=\"https://docs.ultralytics.com/modes/track/\">Object Tracking</a> and understand its features and capabilities.\n",
        "\n",
        "YOLOv8 models are fast, accurate, and easy to use, making them ideal for various object detection and image segmentation tasks. They can be trained on large datasets and run on diverse hardware platforms, from CPUs to GPUs.\n",
        "\n",
        "We hope that the resources in this notebook will help you get the most out of <a href=\"https://docs.ultralytics.com/modes/track/\">Ultralytics Object Tracking</a>. Please browse the YOLOv8 <a href=\"https://docs.ultralytics.com/\">Docs</a> for details, raise an issue on <a href=\"https://github.com/ultralytics/ultralytics\">GitHub</a> for support, and join our <a href=\"https://ultralytics.com/discord\">Discord</a> community for questions and discussions!\n",
        "\n",
        "</div>"
      ],
      "metadata": {
        "id": "PN1cAxdvd61e"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Setup\n",
        "\n",
        "Pip install `ultralytics` and [dependencies](https://github.com/ultralytics/ultralytics/blob/main/pyproject.toml) and check software and hardware."
      ],
      "metadata": {
        "id": "o68Sg1oOeZm2"
      }
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "9dSwz_uOReMI"
      },
      "outputs": [],
      "source": [
        "!pip install ultralytics"
      ]
    },
    {
      "cell_type": "markdown",
      "source": [
        "# Ultralytics Object Tracking\n",
        "\n",
        "Within the domain of video analytics, object tracking stands out as a crucial undertaking. It goes beyond merely identifying the location and class of objects within the frame; it also involves assigning a unique ID to each detected object as the video unfolds. The applications of this technology are vast, spanning from surveillance and security to real-time sports analytics."
      ],
      "metadata": {
        "id": "m7VkxQ2aeg7k"
      }
    },
    {
      "cell_type": "markdown",
      "source": [
        "## CLI"
      ],
      "metadata": {
        "id": "-ZF9DM6e6gz0"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "!yolo track source=\"/path/to/video/file.mp4\" save=True"
      ],
      "metadata": {
        "id": "-XJqhOwo6iqT"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "## Python\n",
        "\n",
        "- Draw Object tracking trails"
      ],
      "metadata": {
        "id": "XRcw0vIE6oNb"
      }
    },
    {
      "cell_type": "code",
      "source": [
        "import cv2\n",
        "import numpy as np\n",
        "from ultralytics import YOLO\n",
        "\n",
        "from ultralytics.utils.checks import check_imshow\n",
        "from ultralytics.utils.plotting import Annotator, colors\n",
        "\n",
        "from collections import defaultdict\n",
        "\n",
        "track_history = defaultdict(lambda: [])\n",
        "model = YOLO(\"yolov8n.pt\")\n",
        "names = model.model.names\n",
        "\n",
        "video_path = \"/path/to/video/file.mp4\"\n",
        "cap = cv2.VideoCapture(video_path)\n",
        "assert cap.isOpened(), \"Error reading video file\"\n",
        "\n",
        "w, h, fps = (int(cap.get(x)) for x in (cv2.CAP_PROP_FRAME_WIDTH, cv2.CAP_PROP_FRAME_HEIGHT, cv2.CAP_PROP_FPS))\n",
        "\n",
        "result = cv2.VideoWriter(\"object_tracking.avi\",\n",
        "                       cv2.VideoWriter_fourcc(*'mp4v'),\n",
        "                       fps,\n",
        "                       (w, h))\n",
        "\n",
        "while cap.isOpened():\n",
        "    success, frame = cap.read()\n",
        "    if success:\n",
        "        results = model.track(frame, persist=True, verbose=False)\n",
        "        boxes = results[0].boxes.xyxy.cpu()\n",
        "\n",
        "        if results[0].boxes.id is not None:\n",
        "\n",
        "            # Extract prediction results\n",
        "            clss = results[0].boxes.cls.cpu().tolist()\n",
        "            track_ids = results[0].boxes.id.int().cpu().tolist()\n",
        "            confs = results[0].boxes.conf.float().cpu().tolist()\n",
        "\n",
        "            # Annotator Init\n",
        "            annotator = Annotator(frame, line_width=2)\n",
        "\n",
        "            for box, cls, track_id in zip(boxes, clss, track_ids):\n",
        "                annotator.box_label(box, color=colors(int(cls), True), label=names[int(cls)])\n",
        "\n",
        "                # Store tracking history\n",
        "                track = track_history[track_id]\n",
        "                track.append((int((box[0] + box[2]) / 2), int((box[1] + box[3]) / 2)))\n",
        "                if len(track) > 30:\n",
        "                    track.pop(0)\n",
        "\n",
        "                # Plot tracks\n",
        "                points = np.array(track, dtype=np.int32).reshape((-1, 1, 2))\n",
        "                cv2.circle(frame, (track[-1]), 7, colors(int(cls), True), -1)\n",
        "                cv2.polylines(frame, [points], isClosed=False, color=colors(int(cls), True), thickness=2)\n",
        "\n",
        "        result.write(frame)\n",
        "        if cv2.waitKey(1) & 0xFF == ord(\"q\"):\n",
        "            break\n",
        "    else:\n",
        "        break\n",
        "\n",
        "result.release()\n",
        "cap.release()\n",
        "cv2.destroyAllWindows()"
      ],
      "metadata": {
        "id": "Cx-u59HQdu2o"
      },
      "execution_count": null,
      "outputs": []
    },
    {
      "cell_type": "markdown",
      "source": [
        "#Community Support\n",
        "\n",
        "For more information, you can explore <a href=\"https://docs.ultralytics.com/modes/track/\">Ultralytics Object Tracking Docs</a>\n",
        "\n",
        "Ultralytics ⚡ resources\n",
        "- About Us – https://ultralytics.com/about\n",
        "- Join Our Team – https://ultralytics.com/work\n",
        "- Contact Us – https://ultralytics.com/contact\n",
        "- Discord – https://ultralytics.com/discord\n",
        "- Ultralytics License – https://ultralytics.com/license\n",
        "\n",
        "YOLOv8 🚀 resources\n",
        "- GitHub – https://github.com/ultralytics/ultralytics\n",
        "- Docs – https://docs.ultralytics.com/"
      ],
      "metadata": {
        "id": "QrlKg-y3fEyD"
      }
    }
  ]
}
