Files
image-classification/05_classification.py
T
2026-10-14 04:16:27 +00:00

111 lines
3.6 KiB
Python

"""
============================================================
BASIC YOLO TASK 5 : IMAGE CLASSIFICATION
============================================================
WHAT THIS FILE DOES:
- Looks at the WHOLE frame (not individual objects inside it)
and predicts a single "what is this image mostly of" label,
e.g. "coffee mug", "laptop", "golden retriever"
- Shows the top-5 most likely classes with confidence bars
WHEN TO USE THIS:
Use classification (instead of detection) when:
- there is only ever ONE main subject filling the frame
(e.g. a product on a conveyor belt, a single scanned item)
- you don't need box locations, just "what is it"
- it's the fastest/lightest of all 5 tasks — good when
compute is very limited
Do NOT use this if the frame can contain multiple different
objects at once and you need to know where each one is —
use 01_detection.py or 02_tracking.py for that instead.
Install deps:
pip install ultralytics opencv-python
============================================================
"""
import cv2
import time
from ultralytics import YOLO
# ------------------------------------------------------------
# SETTINGS
# ------------------------------------------------------------
CAMERA_INDEX = 0
FRAME_W = 1280
FRAME_H = 720
TOP_K = 5 # how many top predictions to show
MODEL_WEIGHTS = 'yolo26n-cls.pt' # '-cls' = classification variant of YOLO26n
def load_model():
print("Loading YOLO26n-cls classification model...")
model = YOLO(MODEL_WEIGHTS)
return model
def draw_classification(frame, results):
result = results[0]
probs = result.probs # class probabilities for the whole frame
names = result.names
top_indices = probs.top5[:TOP_K] # indices of the top-K classes
top_confs = probs.top5conf.tolist()[:TOP_K]
y = 40
for idx, conf in zip(top_indices, top_confs):
label = f"{names[idx]}: {conf * 100:.1f}%"
cv2.putText(frame, label, (10, y),
cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 0), 2)
# simple confidence bar next to the text
bar_len = int(conf * 200)
cv2.rectangle(frame, (350, y - 18), (350 + bar_len, y - 2), (0, 255, 0), -1)
y += 34
return frame
def run():
model = load_model()
cap = cv2.VideoCapture(CAMERA_INDEX)
cap.set(cv2.CAP_PROP_FRAME_WIDTH, FRAME_W)
cap.set(cv2.CAP_PROP_FRAME_HEIGHT, FRAME_H)
if not cap.isOpened():
print(f"ERROR: could not open camera {CAMERA_INDEX}")
return
print("Running classification — press Q to quit")
prev_t = time.time()
while True:
ok, frame = cap.read()
if not ok:
continue
# ---- Core classification call ------------------------------
# Because MODEL_WEIGHTS points at a '-cls' checkpoint, output
# is a single probability distribution over classes for the
# WHOLE frame (result.probs), with no .boxes at all.
results = model(frame, verbose=False)
frame = draw_classification(frame, results)
now = time.time()
fps = 1.0 / (now - prev_t) if now != prev_t else 0.0
prev_t = now
cv2.putText(frame, f"FPS: {fps:.1f}",
(10, frame.shape[0] - 20), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2)
cv2.imshow("YOLO - Classification", frame)
if cv2.waitKey(1) & 0xFF in (ord('q'), ord('Q')):
break
cap.release()
cv2.destroyAllWindows()
if __name__ == '__main__':
run()