1) 실시간 코드 만들기

cat > intrusion_live.py <<'EOF'
import cv2
from ultralytics import YOLO

MODEL_PATH ="yolov8n.pt"
CAM_INDEX = 0
ROI = (200, 120, 520, 420)
CONF_TH = 0.35

model = YOLO(MODEL_PATH)cap = cv2.VideoCapture(CAM_INDEX)if not cap.isOpened():
    raise SystemExit("❌ Camera not opened. Try CAM_INDEX=1 or 2")

w = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 640
h = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 480
fps = cap.get(cv2.CAP_PROP_FPS)
fps = fpsif fps and fps > 1else 30

out = cv2.VideoWriter("intrusion_live_out.mp4",
    cv2.VideoWriter_fourcc(*"mp4v"),
    fps,
    (w, h),
)

def point_in_roi(cx, cy, roi):
    x1, y1, x2, y2 = roireturn (x1 <= cx <= x2) and (y1 <= cy <= y2)

x1, y1, x2, y2 = ROIprint(f"ROI = {ROI}, output = intrusion_live_out.mp4")print("Press 'q' to quit.")while True:
    ret, frame = cap.read()if not ret:break

    intruded = False
    results = model.track(frame, persist=True, verbose=False, conf=CONF_TH, classes=[0])
    r = results[0]

    cv2.rectangle(frame, (x1, y1), (x2, y2), (0, 255, 255), 2)
    cv2.putText(frame,"RESTRICTED ZONE", (x1, max(20, y1 - 10)),
                cv2.FONT_HERSHEY_SIMPLEX, 0.6, (0, 255, 255), 2)if r.boxes is not None and len(r.boxes) > 0:for boxin r.boxes:
            b = box.xyxy[0].cpu().numpy()
            bx1, by1, bx2, by2 = map(int, b)
            cx = (bx1 + bx2) // 2
            cy = (by1 + by2) // 2

            tid = Noneif box.id is not None:
                tid = int(box.id[0].cpu().item())

            inside = point_in_roi(cx, cy, ROI)if inside:
                intruded = True

            cv2.rectangle(frame, (bx1, by1), (bx2, by2), (0, 255, 0), 2)
            cv2.circle(frame, (cx, cy), 4, (255, 255, 255), -1)

            label ="person"if tid is not None:
                label += f" ID:{tid}"
            label +=" IN"if insideelse""
            cv2.putText(frame, label, (bx1, max(20, by1 - 8)),
                        cv2.FONT_HERSHEY_SIMPLEX, 0.6,
                        (0, 0, 255)if insideelse (0, 255, 0), 2)if intruded:
        cv2.putText(frame,"INTRUSION DETECTED!", (30, 60),
                    cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 0, 255), 3)

    out.write(frame)
    cv2.imshow("Intrusion Detection (live) - press q", frame)if cv2.waitKey(1) & 0xFF == ord("q"):break

cap.release()
out.release()
cv2.destroyAllWindows()print("Saved:","intrusion_live_out.mp4")
EOF

실행:

python intrusion_live.py

종료는 q.

끝나면 결과 확인:

open intrusion_live_out.mp4