Click the Open in Colab
button to run the cookbook on Google Colab.
Before you start¶
Let's make sure that we have access to GPU. We can use nvidia-smi
command to do that. In case of any problems navigate to Edit
-> Notebook settings
-> Hardware accelerator
, set it to GPU
, and then click Save
.
!nvidia-smi
Mon Feb 12 13:03:38 2024 +---------------------------------------------------------------------------------------+ | NVIDIA-SMI 535.104.05 Driver Version: 535.104.05 CUDA Version: 12.2 | |-----------------------------------------+----------------------+----------------------+ | GPU Name Persistence-M | Bus-Id Disp.A | Volatile Uncorr. ECC | | Fan Temp Perf Pwr:Usage/Cap | Memory-Usage | GPU-Util Compute M. | | | | MIG M. | |=========================================+======================+======================| | 0 Tesla T4 Off | 00000000:00:04.0 Off | 0 | | N/A 48C P8 10W / 70W | 0MiB / 15360MiB | 0% Default | | | | N/A | +-----------------------------------------+----------------------+----------------------+ +---------------------------------------------------------------------------------------+ | Processes: | | GPU GI CI PID Type Process name GPU Memory | | ID ID Usage | |=======================================================================================| | No running processes found | +---------------------------------------------------------------------------------------+
NOTE: To make it easier for us to manage datasets, images and models we create a HOME
constant.
import os
HOME = os.getcwd()
print(HOME)
/content
Install required packages¶
In this cookbook, we'll leverage two Python packages - ultralytics
for running object detection, and supervision
for tracking, visualizing detections, and crucially, counting objects that cross a line.
!pip install -q ultralytics supervision==0.18.0
Imports¶
import numpy as np
import supervision as sv
from ultralytics import YOLO
from supervision.assets import download_assets, VideoAssets
Download video¶
As an example input video, we will use one of the videos available in supervision.assets
. Supervision offers an assets download utility that allows you to download video files that you can use in your demos.
download_assets(VideoAssets.VEHICLES)
NOTE: If you want to run the cookbook using your own file as input, simply upload video to Google Colab and replace SOURCE_VIDEO_PATH
with the path to your file.
SOURCE_VIDEO_PATH = f"{HOME}/vehicles.mp4"
As a result of executing the above commands, you will download a video file and save it at the SOURCE_VIDEO_PATH
. Keep in mind that the video preview below works only in the web version of the cookbooks and not in Google Colab.
Read single frame from video¶
The get_video_frames_generator
enables us to easily iterate over video frames. Let's create a video generator for our sample input file and display its first frame on the screen.
generator = sv.get_video_frames_generator(SOURCE_VIDEO_PATH)
frame = next(generator)
sv.plot_image(frame, (12, 12))