After implementing a basic object detection model, it's time to move towards a more advanced and real-world application. In this section, we will build a real-time object detection system using YOLOv8 (You Only Look Once), a state-of-the-art deep learning model known for its efficiency and speed.
In this project, we will:
Before proceeding, ensure you have the following:
ultralytics
, opencv-python
, torch
, numpy
, matplotlib
Install the required dependencies:
pip install ultralytics opencv-python torch torchvision torchaudio numpy matplotlib
First, we load the YOLOv8 model and apply it to a test image:
from ultralytics import YOLO
import cv2
# Load YOLOv8 model (pre-trained)
model = YOLO("yolov8n.pt")
# Load an image
image_path = "sample.jpg"
results = model(image_path)
# Display results
results.show()
To run object detection on a webcam, modify the script as follows:
import cv2
# Open webcam
cap = cv2.VideoCapture(0)
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
# Run YOLOv8 inference
results = model(frame)
# Display results
for result in results:
frame = result.plot()
cv2.imshow("YOLOv8 Live Detection", frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
(Source : Internet)
For more specific applications, you can fine-tune YOLOv8 on your dataset:
images/
, labels/
with .txt
files).data.yaml
):train: /path/to/train/images
val: /path/to/val/images
nc: 2 # Number of classes
names: ["class1", "class2"]
Run the following command to train YOLOv8 on your dataset:
yolo task=detect mode=train model=yolov8n.pt data=data.yaml epochs=50 imgsz=640
Once trained, use the model for inference:
model = YOLO("runs/detect/train/weights/best.pt")
results = model("test_image.jpg")
results.show()
With this project, you have built a fully functional object detection system, moving from basic implementation to real-world application. The next step could involve edge deployment on Jetson Nano or optimizing the model for mobile devices which would be discussed in future in the Edge Deployment Codelabs