-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdetection.py
More file actions
93 lines (67 loc) · 1.88 KB
/
Copy pathdetection.py
File metadata and controls
93 lines (67 loc) · 1.88 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
from ultralytics import YOLO
import numpy as np
import cv2
import time
import imutils
import requests
from collections import deque
model = YOLO("yolov8n.pt")
buffer = []
fx, fy = 600, 600
cx, cy = 300, 300
REAL_WIDTH = 0.1
URL = "http://127.0.0.1:8000/predict"
vs = cv2.VideoCapture(0)
def estimate_depth(w):
if w == 0:
return 1e-4
return (fx * REAL_WIDTH) / w
start_time = time.time()
RUN_TIME = 9
while True:
ret, frame = vs.read()
if not ret:
continue
frame = imutils.resize(frame, width=600)
results = model(frame, verbose=False)
for r in results:
if len(r.boxes) == 0:
continue
box = r.boxes[0]
x1, y1, x2, y2 = box.xyxy[0].cpu().numpy()
cx_pixel = int((x1 + x2) / 2)
cy_pixel = int((y1 + y2) / 2)
w = x2 - x1
Z = estimate_depth(w)
X = (cx_pixel - cx) * Z / fx
Y = (cy_pixel - cy) * Z / fy
buffer.append([X, Y, Z])
cv2.circle(frame, (cx_pixel, cy_pixel), 5, (0, 0, 255), -1)
cv2.rectangle(frame, (int(x1), int(y1)), (int(x2), int(y2)), (0, 255, 0), 2)
break
cv2.imshow("YOLO", frame)
if time.time() - start_time > RUN_TIME and len(buffer) > 20:
arr = np.array(buffer)
center = np.median(arr, axis=0)
print("FINAL STABLE GOAL:", center)
try:
requests.post(
URL,
json={
"x": float(center[0]),
"y": float(center[1]),
"z": float(center[2]),
"roll": 0,
"pitch": 0,
"yaw": 0
},
timeout=2
)
except Exception as e:
print("API error:", e)
break
if cv2.waitKey(1) & 0xFF == ord('q'):
break
vs.release()
cv2.destroyAllWindows()
print("Demo finished.")