diff --git a/06_roi_detection.py b/06_roi_detection.py new file mode 100644 index 0000000..575fc78 --- /dev/null +++ b/06_roi_detection.py @@ -0,0 +1,211 @@ +""" +============================================================ + YOLO + ROI (REGION OF INTEREST) DETECTION +============================================================ +WHAT THIS FILE DOES: + - Lets you DRAW a custom zone (polygon) on the live camera + feed using your mouse, before detection starts + - Once the zone is drawn, YOLO runs detection on the WHOLE + frame as usual, but only KEEPS/COUNTS objects whose center + point falls INSIDE that zone — objects outside the zone + are ignored (not boxed, not counted) + +WHEN TO USE THIS: + Any time you only care about one part of the frame instead of + the whole picture, e.g.: + - only count vehicles on the road, ignore the sidewalk + - only detect people in a restricted/no-entry area + - only trigger an alert when something enters a specific + shelf/zone/lane + This is the same idea used in your ANPR project — restricting + detection/speed checks to the road lane instead of the full + camera view. + +HOW TO USE (controls): + 1. On start, the video feed is paused on the first frame. + 2. LEFT-CLICK to add each corner point of your zone (as many + points as you want — a triangle, rectangle, or any polygon). + 3. Press 'C' to CLOSE the polygon and start detection. + 4. Press 'R' to RESET and draw the zone again. + 5. Once detection is running: + Q = quit + R = reset ROI and draw a new one (video pauses again) + +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.pt' +WIN_NAME = "YOLO - ROI Detection" + +# ------------------------------------------------------------ +# ROI STATE +# ------------------------------------------------------------ +# roi_points: the corner points of the zone the user is drawing/has drawn +# drawing_mode: True while the user is still clicking points (video paused) +roi_points = [] +drawing_mode = True + + +def mouse_callback(event, x, y, flags, param): + """Runs whenever the user clicks on the video window. + While in drawing_mode, every left-click adds one corner + point of the ROI polygon.""" + global roi_points, drawing_mode + if not drawing_mode: + return + if event == cv2.EVENT_LBUTTONDOWN: + roi_points.append((x, y)) + print(f" Point added: ({x}, {y}) | total points: {len(roi_points)}") + + +def point_in_roi(cx, cy, polygon): + """Check whether a single (x, y) point (an object's box center) + lies inside the ROI polygon. Returns True/False. + cv2.pointPolygonTest returns >0 inside, 0 on edge, <0 outside.""" + if len(polygon) < 3: + return False + pts = np.array(polygon, dtype=np.int32) + result = cv2.pointPolygonTest(pts, (cx, cy), False) + return result >= 0 + + +def draw_roi_overlay(frame, polygon, closed): + """Draw the ROI points/lines while the user is still drawing, + or the finished shaded zone once it's closed.""" + if len(polygon) == 0: + return frame + + pts = np.array(polygon, dtype=np.int32) + + if closed and len(polygon) >= 3: + # finished zone -> outline only, no color fill + cv2.polylines(frame, [pts], isClosed=True, color=(0, 255, 0), thickness=2) + else: + # still drawing -> show points + connecting lines only + for p in polygon: + cv2.circle(frame, p, 5, (0, 0, 255), -1) + if len(polygon) > 1: + cv2.polylines(frame, [pts], isClosed=False, color=(0, 0, 255), thickness=2) + + return frame + + +def run(): + global roi_points, drawing_mode + + print("Loading YOLO26n model...") + model = YOLO(MODEL_WEIGHTS) + + 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 + + cv2.namedWindow(WIN_NAME) + cv2.setMouseCallback(WIN_NAME, mouse_callback) + + print("\n Left-click to add ROI points, then press C to close the zone.") + print(" Press R at any time to reset and redraw.\n") + + # grab one still frame to draw the ROI on top of + ok, first_frame = cap.read() + if not ok: + print("ERROR: could not read from camera") + return + + roi_closed = False + prev_t = time.time() + + while True: + if drawing_mode: + # ---- ROI drawing phase: video is paused on first_frame ---- + display = first_frame.copy() + display = draw_roi_overlay(display, roi_points, closed=False) + cv2.putText(display, "Click to add points | C = close zone | R = reset", + (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 0, 255), 2) + cv2.imshow(WIN_NAME, display) + + key = cv2.waitKey(1) & 0xFF + if key in (ord('c'), ord('C')) and len(roi_points) >= 3: + drawing_mode = False + roi_closed = True + print(f" ROI closed with {len(roi_points)} points. Starting detection...") + elif key in (ord('r'), ord('R')): + roi_points = [] + print(" ROI reset.") + elif key in (ord('q'), ord('Q')): + break + continue + + # ---- Detection phase: ROI is set, run YOLO on live frames ---- + ok, frame = cap.read() + if not ok: + continue + + results = model(frame, conf=CONF_THRESHOLD, verbose=False) + boxes = results[0].boxes + names = results[0].names + + in_roi_count = 0 + for box in boxes: + x1, y1, x2, y2 = map(int, box.xyxy[0]) + cx, cy = (x1 + x2) // 2, (y1 + y2) // 2 # box center point + + # ---- THE CORE ROI CHECK ------------------------------- + # Only keep/draw this detection if its center point is + # inside the polygon the user drew. Everything outside + # the zone is simply skipped. + if not point_in_roi(cx, cy, roi_points): + continue + + in_roi_count += 1 + cls_id = int(box.cls[0]) + conf = float(box.conf[0]) + label = f"{names[cls_id]} {conf:.2f}" + + cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 0), 2) + cv2.circle(frame, (cx, cy), 4, (0, 255, 255), -1) # mark the center used for the check + cv2.putText(frame, label, (x1, y1 - 6), + cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 0), 2) + + frame = draw_roi_overlay(frame, roi_points, closed=True) + + 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} In ROI: {in_roi_count} | R = redraw zone", + (10, frame.shape[0] - 15), cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 255), 2) + + cv2.imshow(WIN_NAME, frame) + key = cv2.waitKey(1) & 0xFF + if key in (ord('q'), ord('Q')): + break + elif key in (ord('r'), ord('R')): + roi_points = [] + drawing_mode = True + roi_closed = False + first_frame = frame.copy() # redraw ROI on the current view + + cap.release() + cv2.destroyAllWindows() + + +if __name__ == '__main__': + run()