Deteksi Objek dengan YOLOv8: Real-Time Object Detection dari Setup sampai Inference

Lhuqita Fazry
Machine Learning Computer Vision YOLO
Deteksi Objek dengan YOLOv8: Real-Time Object Detection dari Setup sampai Inference

Memahami Arsitektur YOLOv8 dan Perbedaannya dengan Versi Sebelumnya

YOLOv8 merupakan iterasi terbaru dari seri You Only Look Once yang dikembangkan oleh Ultralytics. Arsitektur ini menggabungkan kecepatan inference yang tinggi dengan akurasi deteksi yang kompetitif. YOLOv8 memperkenalkan backbone network yang lebih efisien, anchor-free detection head, dan sistem loss function yang lebih robust dibandingkan YOLOv5 dan YOLOv7.

Perubahan utama terletak pada desain detection head yang sepenuhnya anchor-free. Versi sebelumnya memerlukan predefined anchor boxes untuk memprediksi lokasi objek. YOLOv8 menghilangkan ketergantungan ini dan secara langsung memprediksi center point dari setiap objek. Pendekatan ini menyederhanakan training pipeline dan meningkatkan generalisasi pada dataset dengan ukuran objek yang bervariasi. Arsitektur backbone YOLOv8 menggunakan C2f module yang menggantikan C3 module pada YOLOv5. Modul ini meningkatkan ekstraksi fitur gradient dengan struktur bottleneck yang lebih ringan. Model ini juga menyediakan berbagai varian ukuran, mulai dari nano untuk edge devices hingga extra large untuk skenario yang menuntut akurasi maksimal.

Menginstal Library Ultralytics dan Menyiapkan Environment

Ultralytics menyediakan package Python yang mengabstraksi kompleksitas implementasi YOLOv8. Kita dapat menginstal library ini melalui pip beserta dependensi utamanya. Environment yang direkomendasikan menggunakan Python 3.8 atau lebih baru dengan PyTorch yang sudah terinstal.

pythonpython
!pip install ultralytics opencv-python matplotlib

import cv2
import matplotlib.pyplot as plt
from ultralytics import YOLO

# Verifikasi instalasi
print("Ultralytics berhasil diinstal")

Instalasi ini mencakup CLI tool yang memungkinkan kita melakukan training, validation, dan export model langsung dari terminal. Package ini juga secara otomatis mengunduh weights pre-trained model saat pertama kali digunakan. Tidak diperlukan konfigurasi manual untuk dependensi seperti CUDA karena PyTorch akan mendeteksi GPU secara otomatis jika tersedia. Pastikan environment virtual aktif sebelum menjalankan perintah instalasi.

Melakukan Inference pada Gambar dengan Model Pre-trained

YOLOv8 menyediakan weights yang telah dilatih pada dataset COCO dengan 80 kelas objek umum. Kita dapat langsung memanfaatkan model ini untuk deteksi tanpa training tambahan. Proses inference dimulai dengan memuat model, kemudian meneruskan gambar input ke dalam pipeline prediksi.

pythonpython
# Load model YOLOv8n (nano) — varian tercepat
model = YOLO("yolov8n.pt")

# Jalankan inference pada gambar
results = model("path/to/image.jpg")

# Tampilkan hasil pertama
result = results[0]
result.show()

# Cetak jumlah objek yang terdeteksi
print(f"Jumlah deteksi: {len(result.boxes)}")

Method predict secara otomatis menangani preprocessing gambar, termasuk resize dan normalisasi pixel values. Output berupa list objek Results yang berisi koordinat bounding box, confidence scores, dan class labels. Varian nano berjalan sangat cepat bahkan pada CPU, sementara varian large memberikan akurasi superior dengan trade-off kecepatan yang signifikan.

Deep Learning Bootcamp
Machine Learning • Intermediate

Deep Learning Bootcamp

A beginner-friendly, highly interactive bootcamp designed to take you from found...

Project: GreenGuard: Intelligent Plant Disease Diagnosis Web App

Daftar

Memproses Output Deteksi dan Menampilkan Bounding Box

Output mentah dari model perlu diproses untuk aplikasi praktis. Setiap deteksi menyediakan tensor yang berisi koordinat bounding box, confidence score, dan class index. Kita dapat mengiterasi hasil deteksi untuk memfilter berdasarkan confidence threshold atau kelas tertentu.

pythonpython
import numpy as np

# Ambil hasil deteksi pertama
result = results[0]

# Akses bounding boxes, confidence, dan class IDs
boxes = result.boxes.xyxy.cpu().numpy().astype(int)
confidences = result.boxes.conf.cpu().numpy()
class_ids = result.boxes.cls.cpu().numpy().astype(int)

# Dapatkan nama kelas dari model
class_names = result.names

# Filter deteksi dengan confidence di atas 0.5
for box, conf, cls_id in zip(boxes, confidences, class_ids):
    if conf > 0.5:
        x1, y1, x2, y2 = box
        label = f"{class_names[cls_id]}: {conf:.2f}"
        print(f"Deteksi: {label} di koordinat ({x1}, {y1}) — ({x2}, {y2})")

Pipeline ini memungkinkan kita untuk mengimplementasikan logika kustom. Contohnya, kita dapat menghitung jumlah kendaraan yang melewati area tertentu atau menghitung jumlah orang dalam sebuah frame. Struktur data tensor yang dihasilkan kompatibel dengan library visualisasi seperti OpenCV dan Matplotlib. Untuk aplikasi production, pertimbangkan untuk menyimpan hasil deteksi ke file CSV atau database secara real-time.

Menerapkan Real-Time Object Detection pada Video Stream

Salah satu kekuatan utama YOLOv8 adalah kemampuannya untuk berjalan pada video stream dengan latency rendah. Kita dapat mengintegrasikan model dengan OpenCV VideoCapture untuk memproses feed dari webcam atau file video secara real-time.

pythonpython
# Inisialisasi video capture dari webcam (index 0)
cap = cv2.VideoCapture(0)

# Loop untuk membaca frame secara kontinu
while cap.isOpened():
    success, frame = cap.read()
    if not success:
        break

    # Jalankan inference pada setiap frame
    results = model(frame, verbose=False)

    # Render hasil deteksi langsung pada frame
    annotated_frame = results[0].plot()

    # Tampilkan frame yang sudah dianotasi
    cv2.imshow("YOLOv8 Real-Time Detection", annotated_frame)

    # Tekan 'q' untuk keluar
    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# Bersihkan resource
cap.release()
cv2.destroyAllWindows()

Parameter verbose=False menonaktifkan log output pada setiap frame untuk menjaga performa. Method plot() menggambar bounding box dan label secara otomatis pada frame. Pipeline ini mencapai frame rate yang playable pada hardware modern, terutama ketika GPU acceleration aktif melalui CUDA. Jika frame rate masih rendah, kita dapat menurunkan resolusi input atau mengimplementasikan frame skipping. Teknik frame skipping menjalankan inference hanya pada setiap N frame, sementara frame di antaranya menggunakan koordinat bounding box sebelumnya.

Mengoptimalkan Performa Inference untuk Production

Sebelum deployment, beberapa optimasi dapat meningkatkan throughput inference secara signifikan. Pertama, gunakan half precision (fp16) jika GPU mendukungnya. Mode ini mengurangi penggunaan memory bandwidth dan meningkatkan kecepatan tanpa kehilangan akurasi yang berarti.

Kedua, pertimbangkan untuk mengekspor model ke format ONNX atau TensorRT. Format ONNX memungkinkan deployment lintas platform, sementara TensorRT memberikan optimasi khusus untuk GPU NVIDIA melalui layer fusion dan precision calibration. Untuk deployment pada edge devices dengan resource terbatas, INT8 quantization dapat mengurangi ukuran model hingga 75% dengan penurunan akurasi yang minimal.

pythonpython
# Export model ke format ONNX
model.export(format="onnx", dynamic=True, simplify=True)

# Load model ONNX untuk inference
onnx_model = YOLO("yolov8n.onnx")

# Inference dengan model ONNX
results = onnx_model("path/to/image.jpg")

Export ONNX dengan dynamic=True mendukung input dengan ukuran batch yang bervariasi. Parameter simplify=True mengoptimasi graph computation untuk menghilangkan operator yang redundan. Model yang telah diekspor dapat di-deploy pada edge devices, mobile applications, atau cloud inference services.

Kesimpulan

YOLOv8 menawarkan solusi deteksi objek yang komprehensif dengan kurva belajar yang ringan. Kita dapat membangun pipeline inference lengkap pada gambar dan video dalam hitungan menit menggunakan library Ultralytics. Arsitektur anchor-free, berbagai varian model, dan dukungan export ke format production-ready menjadikan YOLOv8 pilihan yang solid untuk aplikasi computer vision modern.

Pemahaman tentang pemilihan varian model yang tepat, proses output tensor secara detail, dan teknik optimasi inference adalah fondasi yang kokoh untuk membangun sistem deteksi objek yang benar-benar efisien dan reliable. Teknik ini dapat dikembangkan lebih lanjut dengan fine-tune pada dataset custom untuk domain spesifik seperti manufacturing defect detection atau medical imaging analysis.

Ingin menguasai object detection dan computer vision dari dasar hingga production? Di Rumah Coding, kami menyediakan kurikulum Machine Learning Bootcamp yang mencakup YOLOv8, preprocessing pipeline, dan model deployment. Bergabunglah dengan komunitas kami untuk belajar langsung dari mentor berpengalaman.

Course Terkait

GreenGuard: Intelligent Plant Disease Diagnosis Web App
Premium Course
Premium Course Machine Learning

Deep Learning Bootcamp

A beginner-friendly, highly interactive bootcamp designed to take you from foundational concepts to deploying real-world Artificial Intelligence applications. Through a completely project-based approach, you will master the core of Deep Learning, Artificial Neural Networks, and Computer Vision using Python and TensorFlow, ultimately building a professional-grade AI web application for your portfolio.

Capstone Project

GreenGuard: Intelligent Plant Disease Diagnosis Web App

  • Interactive Image Upload UI: A clean, user-friendly interface built with Streamlit that supports drag-and-drop image uploads directly from a computer or mobile phone.
  • Real-Time AI Inference: Utilizes a lightweight, optimized CNN model (like MobileNetV2) to process the image and return a diagnosis in seconds without heavy server load.
  • Confidence Scoring Dashboard: Visually displays the model's prediction probability (e.g., "95% confident this is Tomato Late Blight") using interactive progress bars or charts.
7 Weeks Intermediate
Lihat Detail Course
Domain-Specific AI Knowledge Assistant
Premium Course
Premium Course Machine Learning

LLM Bootcamp

This project-based bootcamp is designed for beginners to dive practically into the world of Large Language Models (LLMs). Through hands-on building, you will learn how to interact with top-tier AI APIs, master prompt engineering, orchestrate complex workflows using LangChain, and implement Retrieval-Augmented Generation (RAG) to query your own documents. By the end of this course, you will have the skills to build, test, and deploy a fully functional, custom AI web application.

Capstone Project

Domain-Specific AI Knowledge Assistant

  • Dynamic Document Processing: A sidebar interface allowing users to upload new PDF or TXT files, which the app automatically chunks, embeds, and stores in the vector database.
  • Context-Aware Chat UI: A modern chat interface built with Streamlit that maintains conversation history, allowing users to ask follow-up questions naturally.
  • Strict Guardrails (Anti-Hallucination): System instructions designed so the AI politely declines to answer questions that fall outside the context of the uploaded documents.
7 Weeks Beginner
Lihat Detail Course
End-to-End Student Success Predictor
Premium Course
Premium Course Machine Learning

Machine Learning Bootcamp

A beginner-friendly, 7-week project-based bootcamp designed to take you from Python basics to deploying your first Machine Learning model. Through hands-on practice, you will master essential data manipulation, build predictive algorithms, and develop an end-to-end, industry-ready application to kickstart your career in data science.

Capstone Project

End-to-End Student Success Predictor

  • Automated Data Pipeline: A preprocessing script that automatically cleans missing values, encodes categorical data (like course type or student background), and scales numerical inputs.
  • Predictive Engine: A tuned machine learning classification model (e.g., Random Forest) specifically optimized for high Recall, ensuring that "at-risk" students are not missed.
  • Interactive Web Dashboard: A user-friendly Streamlit interface featuring a sidebar where instructors can manually input a student's study hours, quiz scores, and login frequency to get an instant pass/fail probability.
7 Weeks Intermediate
Lihat Detail Course

Artikel Terkait