find runs -type f -name"*.mp4" |head -n 20
여기서 침입 감지에 사용할 mp4 하나 경로를 복사
예:
runs/detect/track/exp/xxx.mp4 또는 input10s.mp4
파일 생성:
cat > intrusion_file.py <<'EOF'
import cv2
from ultralytics import YOLO
# ===== 설정 =====
VIDEO_PATH ="input10s.mp4" # ← 여기만 네 mp4 경로로 바꿔줘!
MODEL_PATH ="yolov8n.pt"
# ROI(침입 구역) 사각형: (x1,y1)~(x2,y2)
# 일단 화면 가운데쯤 크게 잡아두고, 실행 후 조정하면 됨.
ROI = (200, 120, 520, 420)# x1, y1, x2, y2
CONF_TH = 0.35# 탐지 신뢰도 임계값
# =================
model = YOLO(MODEL_PATH)
cap = cv2.VideoCapture(VIDEO_PATH)
if not cap.isOpened():
raise SystemExit(f"❌ Cannot open video: {VIDEO_PATH}")
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_file_out.mp4",
cv2.VideoWriter_fourcc(*"mp4v"),
fps,
(w, h),
)
def point_in_roi(cx, cy, roi):
x1, y1, x2, y2 = roi
return (x1 <= cx <= x2) and (y1 <= cy <= y2)
x1, y1, x2, y2 = ROI
print(f"ROI = {ROI}, output = intrusion_file_out.mp4")
while True:
ret, frame = cap.read()
if not ret:
break
intruded = False
# track: ID를 붙여 추적
results = model.track(frame, persist=True, verbose=False, conf=CONF_TH, classes=[0]) # classes=[0] => person만
r = results[0]
# ROI 그리기
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
# track id
tid = None
if 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 = f"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 (file) - press q", frame)
if cv2.waitKey(1) & 0xFF == ord("q"):
break
cap.release()
out.release()
cv2.destroyAllWindows()
print("Saved:","intrusion_file_out.mp4")
EOF
intrusion_file.py 열어서 VIDEO_PATH를 mp4 경로로 바꾸기
(가장 쉬운 방법: find ...에서 나온 경로를 복사해서 붙여넣기)
실행:
python intrusion_file.py
끝나면 결과 확인:
open intrusion_file_out.mp4
ROI 안으로 들어갈 때 “INTRUSION DETECTED!” 뜨면 성공.