diff --git a/03_segmentation.py b/03_segmentation.py new file mode 100644 index 0000000..fbd3c4d --- /dev/null +++ b/03_segmentation.py @@ -0,0 +1,126 @@ +""" +============================================================ + BASIC YOLO TASK 3 : INSTANCE SEGMENTATION +============================================================ +WHAT THIS FILE DOES: + - Detects objects like 01_detection.py + - PLUS: instead of just a rectangular box, it finds the + exact pixel-by-pixel outline (mask) of each object and + fills it with a semi-transparent color + +WHEN TO USE THIS: + Use segmentation when a box isn't precise enough — e.g. + - measuring the exact area/shape of an object + - separating an object cleanly from its background + (background blur/removal, "green screen" style) + - cases where objects overlap a lot and boxes alone + are ambiguous about which pixels belong to which object + +NOTE: Segmentation is heavier than plain detection (more compute +per frame), so expect lower FPS on the same hardware. + +Install deps: + pip install ultralytics opencv-python numpy +============================================================ +""" + +import cv2 +import time +import numpy as np +from ultralytics import YOLO + +# ------------------------------------------------------------ +# SETTINGS +# ------------------------------------------------------------ +CAMERA_INDEX = 0 +FRAME_W = 1280 +FRAME_H = 720 +CONF_THRESHOLD = 0.45 +MODEL_WEIGHTS = 'yolo26n-seg.pt' # '-seg' = segmentation variant of YOLO26n +MASK_ALPHA = 0.4 # 0 = invisible mask, 1 = solid fill + +# one random-ish fixed color per class id, so each class is consistent +import random +random.seed(42) +CLASS_COLORS = {i: tuple(random.randint(60, 255) for _ in range(3)) for i in range(80)} + + +def load_model(): + print("Loading YOLO26n-seg segmentation model...") + model = YOLO(MODEL_WEIGHTS) + return model + + +def draw_segmentation(frame, results): + """Overlay each object's pixel mask + box + label on the frame.""" + result = results[0] + names = result.names + + if result.masks is None: + return frame # nothing detected this frame + + overlay = frame.copy() + + for mask_xy, box in zip(result.masks.xy, result.boxes): + cls_id = int(box.cls[0]) + conf = float(box.conf[0]) + color = CLASS_COLORS[cls_id] + + # mask_xy is a polygon (list of x,y points) outlining the object — + # fill that polygon on the overlay layer + pts = np.array(mask_xy, dtype=np.int32) + cv2.fillPoly(overlay, [pts], color) + + x1, y1, x2, y2 = map(int, box.xyxy[0]) + label = f"{names[cls_id]} {conf:.2f}" + cv2.putText(frame, label, (x1, y1 - 6), + cv2.FONT_HERSHEY_SIMPLEX, 0.6, color, 2) + + # blend the filled overlay with the original frame for a + # semi-transparent "highlight" look instead of solid blocks + frame = cv2.addWeighted(overlay, MASK_ALPHA, frame, 1 - MASK_ALPHA, 0) + 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 segmentation — press Q to quit") + prev_t = time.time() + + while True: + ok, frame = cap.read() + if not ok: + continue + + # ---- Core segmentation call ------------------------------ + # Because MODEL_WEIGHTS points at a '-seg' checkpoint, the + # model output now includes .masks (pixel outlines) in + # addition to the usual .boxes + results = model(frame, conf=CONF_THRESHOLD, verbose=False) + + frame = draw_segmentation(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, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.8, (0, 255, 255), 2) + + cv2.imshow("YOLO - Segmentation", frame) + if cv2.waitKey(1) & 0xFF in (ord('q'), ord('Q')): + break + + cap.release() + cv2.destroyAllWindows() + + +if __name__ == '__main__': + run()