这是一个无人机跟踪的代码分析

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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
<div style="max-height: 300px; max-width: 100%; overflow: auto;">
import copy
import math
import sys
import threading
import time
from pathlib import Path
from typing import Optional, Tuple

import cv2
import numpy as np

import PX4MavCtrlV4 as PX4MavCtrl
import UE4CtrlAPI
import VisionCaptureApi
from detect_drone_ultralytics import DroneDetectorUltralytics

# --- Configuration -----------------------------------------------------------------
THIS_DIR = Path(__file__).resolve().parent
# 使用 fengru 文件夹中训练好的无人机检测模型
DEFAULT_WEIGHTS = THIS_DIR / "fengru" / "runs" / "train" / "exp4" / "weights" / "best.pt"
WEIGHTS_PATH = Path(sys.argv[1]).resolve() if len(sys.argv) > 1 else DEFAULT_WEIGHTS
TARGET_CLASS_NAME = "drone" # YOLO11 无人机检测类别名
TARGET_CONF_THRESHOLD = 0.3 # 降低置信度阈值,更容易检测到目标
TARGET_AREA_RATIO = 0.015 # Desired bounding-box area ratio when at the preferred distance
FRAME_RATE = 30.0 # 提高到30 FPS实现实时检测
DETECT_IMG_SCALE = 0.6 # 检测图像缩放比例 (缩小到60%以提高速度)

# PID-like control gains (similar to detect_ball.py K_z and K_yawrate)
K_FORWARD = 2.5 # Forward speed gain based on area error
K_LATERAL = 0.0025 # Lateral speed gain based on horizontal center error
K_VERTICAL = 0.0020 # Vertical speed gain based on vertical center error
K_YAW = 0.0040 # Yaw rate gain based on horizontal center error

MAX_FORWARD_VEL = 2.0
MAX_BACKWARD_VEL = 1.0
MAX_LATERAL_VEL = 1.5
MAX_VERTICAL_VEL = 1.0
MAX_YAW_RATE = 0.6
REACQUIRE_PIXEL_THRESHOLD = 80.0
SEARCH_HOLD_DURATION = 1.0
SEARCH_YAW_RATE = 0.3
FOLLOWER_INIT_POS = [0.0, 0.0, 0.0] # 跟随机的初始位置,第一架飞机
FOLLOWER_CRUISE_ALT = -10.0 # NED: -10m = 10m above ground 起飞高度
TARGET_COPTER_ID = 2
TARGET_VEHICLE_TYPE = 3
TARGET_INIT_POS = [3.0, 0, 0.0] # 目标初始位置 第二架飞机,x方向偏移3m
TARGET_CRUISE_ALT = -10.0 # NED: -10m = 10m above ground # 目标起飞高度
TARGET_WAIT_TIME = 5.0 # Target drone waits this long at cruise altitude before follower starts
SEARCH_YAW_ANGLE_DEG = 10.0 # 搜索时偏航角范围 ±10度
SEARCH_YAW_SPEED = 0.2 # rad/s, yaw rotation speed when searching


# --- Global State --------------------------------------------------------------------


def clamp(value: float, lower: float, upper: float) -> float:
return max(lower, min(upper, value))


def create_tracker() -> cv2.Tracker:
if hasattr(cv2, "TrackerKCF_create"):
return cv2.TrackerKCF_create()
if hasattr(cv2, "legacy") and hasattr(cv2.legacy, "TrackerKCF_create"):
return cv2.legacy.TrackerKCF_create()
raise RuntimeError("OpenCV KCF tracker is unavailable in this environment.")


def select_detection(detections, class_names):
if not detections:
return None
target_index = None
if TARGET_CLASS_NAME in class_names:
target_index = class_names.index(TARGET_CLASS_NAME)
if target_index is not None:
candidates = [det for det in detections if det[0] == target_index and det[2] >= TARGET_CONF_THRESHOLD]
if candidates:
return max(candidates, key=lambda item: item[2])
filtered = [det for det in detections if det[2] >= TARGET_CONF_THRESHOLD]
return max(filtered, key=lambda item: item[2]) if filtered else None


def compute_control(center: Tuple[float, float], area: float, width: int, height: int) -> Tuple[float, float, float, float]:
"""
Compute control commands based on detection center error and area.
Similar to detect_ball.py Controller function.

Args:
center: (cx, cy) detection center in pixels
area: detection bounding box area in pixels^2
width: image width
height: image height

Returns:
(vx, vy, vz, yaw_rate) control velocities in FRD frame
"""
cx, cy = center
# Calculate pixel errors from image center
ex = cx - width / 2.0 # horizontal error (positive = target is right)
ey = cy - height / 2.0 # vertical error (positive = target is below)

# Calculate area ratio error
area_ratio = area / float(width * height) if width * height else 0.0
area_error = TARGET_AREA_RATIO - area_ratio # positive = need to move forward

# Control logic similar to detect_ball.py
# Forward velocity based on area error
vx = K_FORWARD * area_error
vx = clamp(vx, -MAX_BACKWARD_VEL, MAX_FORWARD_VEL)

# Lateral velocity based on horizontal error
vy = K_LATERAL * ex
vy = clamp(vy, -MAX_LATERAL_VEL, MAX_LATERAL_VEL)

# Vertical velocity based on vertical error
vz = K_VERTICAL * ey
vz = clamp(vz, -MAX_VERTICAL_VEL, MAX_VERTICAL_VEL)

# Yaw rate based on horizontal error
yaw_rate = K_YAW * ex
yaw_rate = clamp(yaw_rate, -MAX_YAW_RATE, MAX_YAW_RATE)

return vx, vy, vz, yaw_rate


def search_control(last_cmd: Tuple[float, float, float, float], time_since_seen: float, toggle_state: int) -> Tuple[float, float, float, float]:
"""
Search control: oscillate yaw within ±10 degrees when target is lost.
Also commands pitch changes via gimbal control (not velocity).
"""
if time_since_seen < SEARCH_HOLD_DURATION:
return last_cmd

# Oscillate yaw within ±SEARCH_YAW_ANGLE_DEG degrees (±10度)
# Use sine wave to create smooth left-right scanning motion
search_phase = time_since_seen * SEARCH_YAW_SPEED
yaw_angle_rad = math.radians(SEARCH_YAW_ANGLE_DEG) * math.sin(search_phase)
# Convert angle to yaw rate (approximate derivative)
yaw_rate = SEARCH_YAW_SPEED * math.radians(SEARCH_YAW_ANGLE_DEG) * math.cos(search_phase)

return 0.0, 0.0, 0.0, yaw_rate


def ensure_offboard(mav: PX4MavCtrl.PX4MavCtrler):
"""Ensure MAV is armed and in offboard mode."""
retry_count = 0
max_retries = 5
while retry_count < max_retries:
if not mav.isInOffboard:
print(f" Attempting to enter offboard mode... (attempt {retry_count + 1}/{max_retries})")
mav.initOffboard()
time.sleep(0.5)
if not mav.isArmed:
print(f" Attempting to arm... (attempt {retry_count + 1}/{max_retries})")
mav.SendMavArm(True)
time.sleep(0.5)
if mav.isInOffboard and mav.isArmed:
print(f" ✓ Successfully armed and in offboard mode")
return True
retry_count += 1
time.sleep(1.0)
print(f" ✗ Failed to enter offboard mode after {max_retries} attempts")
print(f" Status: isInOffboard={mav.isInOffboard}, isArmed={mav.isArmed}")
return False


def ctrl_target_drone_hover(target_mav: PX4MavCtrl.PX4MavCtrler, wait_time: float):
"""
Control target drone: take off to cruise altitude and hover.
Similar to target_follow.py CtrlTargetDrone function.
"""
print("Target drone (ID=2) taking off...")
# Ensure target is in offboard mode
if not ensure_offboard(target_mav):
print("ERROR: Target drone failed to enter offboard mode!")
return

# Take off to cruise altitude
print(f" Sending takeoff command: position=({TARGET_INIT_POS[0]}, {TARGET_INIT_POS[1]}, {TARGET_CRUISE_ALT})")
target_mav.SendPosNED(TARGET_INIT_POS[0], TARGET_INIT_POS[1], TARGET_CRUISE_ALT, 0.0)
time.sleep(5.0) # Wait for takeoff

print(f"Target drone hovering at {-TARGET_CRUISE_ALT}m altitude, waiting {wait_time}s...")
# Hover at cruise altitude
time_interval = 1.0 / 10.0 # 10Hz control loop
last_time = time.time()
start_time = time.time()

while True:
last_time = last_time + time_interval
sleep_time = last_time - time.time()
if sleep_time > 0:
time.sleep(sleep_time)
else:
last_time = time.time()

# Keep sending hover command
target_mav.SendPosNED(TARGET_INIT_POS[0], TARGET_INIT_POS[1], TARGET_CRUISE_ALT, 0.0)

# Check if initial wait time has passed (signal for follower to start)
elapsed = time.time() - start_time
if elapsed > wait_time and elapsed < wait_time + 0.5:
print("Target drone hover complete, follower can start searching...")


def detection_and_control_loop(
vis: VisionCaptureApi.VisionCaptureApi,
follower_mav: PX4MavCtrl.PX4MavCtrler,
target_mav: PX4MavCtrl.PX4MavCtrler,
start_delay: float
):
"""
Main tracking loop for follower drone.
Waits for target to be ready, then takes off, searches, detects and tracks.
"""
# detector = detectapi(weights=str(WEIGHTS_PATH)) # 旧的球体检测器
detector = DroneDetectorUltralytics(weights_path=str(WEIGHTS_PATH)) # 新的无人机检测器
tracker: Optional[cv2.Tracker] = None
last_ctrl = (0.0, 0.0, 0.0, 0.0)
last_seen_time = 0.0
search_toggle = 0

# Wait for target drone to be ready
print(f"Follower waiting {start_delay}s for target drone to be ready...")
time.sleep(start_delay)

# Ensure follower is in offboard mode and at initial position
print("Follower (ID=1) preparing for takeoff...")
if not ensure_offboard(follower_mav):
print("ERROR: Follower drone failed to enter offboard mode!")
return

print(f" Moving to initial position: ({FOLLOWER_INIT_POS[0]}, {FOLLOWER_INIT_POS[1]}, {FOLLOWER_INIT_POS[2]})")
follower_mav.SendPosNED(FOLLOWER_INIT_POS[0], FOLLOWER_INIT_POS[1], FOLLOWER_INIT_POS[2], 0.0)
time.sleep(3.0)

# Take off to cruise altitude
print(f"Follower taking off to {-FOLLOWER_CRUISE_ALT}m cruise altitude...")
print(f" Sending takeoff command: position=({FOLLOWER_INIT_POS[0]}, {FOLLOWER_INIT_POS[1]}, {FOLLOWER_CRUISE_ALT})")
follower_mav.SendPosNED(FOLLOWER_INIT_POS[0], FOLLOWER_INIT_POS[1], FOLLOWER_CRUISE_ALT, 0.0)
time.sleep(5.0)
print("Follower at cruise altitude, starting YOLO detection and tracking...")

frame_interval = 1.0 / FRAME_RATE
next_tick = time.time()

# 添加帧率统计
frame_count = 0
detection_count = 0
last_fps_time = time.time()

while True:
next_tick += frame_interval
sleep_time = next_tick - time.time()
if sleep_time > 0:
time.sleep(sleep_time)
else:
next_tick = time.time()

if not vis.hasData[0]:
continue
frame = copy.deepcopy(vis.Img[0])
vis.hasData[0] = False
height, width = frame.shape[:2]

frame_count += 1

track_ok = False
track_center = None
track_box = None
if tracker is not None:
track_ok, tracked_roi = tracker.update(frame)
if track_ok:
tx, ty, tw, th = tracked_roi
track_box = (int(tx), int(ty), int(tx + tw), int(ty + th))
track_center = (tx + tw / 2.0, ty + th / 2.0)
else:
tracker = None

# 如果需要加速检测,可以缩小图像
if DETECT_IMG_SCALE < 1.0:
detect_frame = cv2.resize(frame, None, fx=DETECT_IMG_SCALE, fy=DETECT_IMG_SCALE, interpolation=cv2.INTER_LINEAR)
else:
detect_frame = frame

result, names, _, _ = detector.detect([detect_frame])
annotated = result[0][0]
detections = result[0][1]

# 如果缩放了图像,需要将检测框坐标还原到原始尺寸
if DETECT_IMG_SCALE < 1.0:
scale_factor = 1.0 / DETECT_IMG_SCALE
scaled_detections = []
for det in detections:
cls_id, bbox, conf = det
x1, y1, x2, y2 = bbox
scaled_bbox = [int(x1 * scale_factor), int(y1 * scale_factor),
int(x2 * scale_factor), int(y2 * scale_factor)]
scaled_detections.append((cls_id, scaled_bbox, conf))
detections = scaled_detections
# 使用原始图像作为底图
annotated = frame.copy()
# 手动在原始图像上绘制检测框
for cls_id, bbox, conf in detections:
x1, y1, x2, y2 = bbox
# 绘制绿色检测框
cv2.rectangle(annotated, (x1, y1), (x2, y2), (0, 255, 0), 2)
# 绘制标签
label = f"{names[cls_id] if cls_id in names else 'drone'} {conf:.2f}"
cv2.putText(annotated, label, (x1, y1 - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 255, 0), 2)

chosen = select_detection(detections, names)

detection_count += 1

detection_center = None
detection_area = 0.0
detection_box = None
if chosen is not None:
cls_id, bbox, conf = chosen
x1, y1, x2, y2 = bbox
detection_box = (int(x1), int(y1), int(x2), int(y2))
detection_center = ((x1 + x2) / 2.0, (y1 + y2) / 2.0)
detection_area = max(0.0, (x2 - x1)) * max(0.0, (y2 - y1))

# Update tracker when YOLO detects target
if tracker is None:
tracker = create_tracker()
tracker.init(frame, (x1, y1, x2 - x1, y2 - y1))
# print(f"Tracker initialized: center=({detection_center[0]:.1f}, {detection_center[1]:.1f}), area={detection_area:.1f}") # 移除输出
elif track_center is not None:
error = math.hypot(detection_center[0] - track_center[0], detection_center[1] - track_center[1])
if error > REACQUIRE_PIXEL_THRESHOLD:
tracker = create_tracker()
tracker.init(frame, (x1, y1, x2 - x1, y2 - y1))
# print(f"Tracker reinitialized due to large error: {error:.1f} pixels") # 移除输出
track_center = detection_center
track_box = detection_box
track_ok = True
last_seen_time = time.time()

# Use detection center if available, otherwise use tracker center
control_center = detection_center if detection_center is not None else track_center
control_area = detection_area if detection_center is not None else (
(track_box[2] - track_box[0]) * (track_box[3] - track_box[1]) if track_box else 0.0
)

if control_center is not None:
last_ctrl = compute_control(control_center, control_area, width, height)
follower_mav.SendVelFRD(*last_ctrl)
# 移除控制信息输出,避免UE4界面显示红色信息
else:
time_since_seen = time.time() - last_seen_time
if time_since_seen > 5.0:
search_toggle += 1
last_seen_time = time.time()
fallback_ctrl = search_control(last_ctrl, time_since_seen, search_toggle)
follower_mav.SendVelFRD(*fallback_ctrl)
last_ctrl = fallback_ctrl
# if time_since_seen > SEARCH_HOLD_DURATION:
# print(f"Searching... time_since_seen={time_since_seen:.1f}s")

# Draw bounding boxes on annotated image
# Red box: YOLO detection (like detect_ball.py detection box)
# Blue box: Tracker box
if detection_box is not None:
cv2.rectangle(annotated, (detection_box[0], detection_box[1]), (detection_box[2], detection_box[3]), (0, 0, 255), 2)
cv2.putText(annotated, "YOLO", (detection_box[0], detection_box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 2)
if track_box is not None and detection_box != track_box:
cv2.rectangle(annotated, (track_box[0], track_box[1]), (track_box[2], track_box[3]), (255, 0, 0), 2)
cv2.putText(annotated, "Tracker", (track_box[0], track_box[1] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (255, 0, 0), 2)

# Draw image center crosshair
cv2.line(annotated, (int(width/2) - 20, int(height/2)), (int(width/2) + 20, int(height/2)), (0, 255, 0), 2)
cv2.line(annotated, (int(width/2), int(height/2) - 20), (int(width/2), int(height/2) + 20), (0, 255, 0), 2)

# 显示FPS统计信息
current_time = time.time()
if current_time - last_fps_time >= 1.0:
fps = frame_count / (current_time - last_fps_time)
det_fps = detection_count / (current_time - last_fps_time)
print(f"[FPS] Frame: {fps:.1f} | Detection: {det_fps:.1f} | Total Detections: {len(detections)} | Selected: {chosen is not None}")
frame_count = 0
detection_count = 0
last_fps_time = current_time

# 在图像上显示FPS和检测信息
fps_text = f"FPS: {int(frame_count / max(1, current_time - last_fps_time))}"
cv2.putText(annotated, fps_text, (10, 30), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 0), 2)

det_text = f"Detections: {len(detections)}"
cv2.putText(annotated, det_text, (10, 70), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (0, 255, 255), 2)

cv2.imshow("YOLO UAV Tracking", annotated)
cv2.waitKey(1)


def main():
"""
Main function - similar to target_follow.py structure.
Creates two drones: follower (ID=1) and target (ID=2).
Target takes off first and hovers, then follower takes off and tracks.
"""
vis = VisionCaptureApi.VisionCaptureApi()
ue = UE4CtrlAPI.UE4CtrlAPI()
vis.jsonLoad()
if not vis.sendReqToUE4():
print("Failed to connect to UE4 vision source.")
sys.exit(0)
vis.startImgCap()
time.sleep(2)

# 优化图像质量和性能设置
ue.sendUE4Cmd('t.MaxFPS 60', 0) # 提高帧率到60 FPS
ue.sendUE4Cmd('r.MotionBlurQuality 0', 0) # 禁用运动模糊,提高清晰度
ue.sendUE4Cmd('r.DefaultFeature.AntiAliasing 2', 0) # 启用FXAA抗锯齿
ue.sendUE4Cmd('r.PostProcessAAQuality 4', 0) # 最高质量抗锯齿
ue.sendUE4Cmd('r.Streaming.PoolSize 2000', 0) # 增加纹理池,提高清晰度

# Remove white walls, keep only ground
print("Removing white walls from scene...")
ue.sendUE4Cmd('RflyHideActorByName BP_Wall', 0)
time.sleep(0.5)

# Create two MAV controllers like target_follow.py
print("Creating MAV controllers for 2 vehicles...")
vehicle_num = 2
mav_list = []
for i in range(vehicle_num):
mav_list.append(PX4MavCtrl.PX4MavCtrler(i + 1))

# Initialize MAV loops
for i in range(vehicle_num):
print(f" Initializing MAV {i+1} loops...")
mav_list[i].InitMavLoop()
mav_list[i].InitTrueDataLoop()

print("Waiting for MAV connections to stabilize...")
time.sleep(2)

# Initialize offboard mode for both drones
for i in range(vehicle_num):
print(f" Initializing offboard mode for MAV {i+1}...")
mav_list[i].initOffboard()

print("Waiting for offboard mode initialization...")
time.sleep(2)

# Assign roles
follower_mav = mav_list[0] # ID=1, for tracking
target_mav = mav_list[1] # ID=2, to be tracked

print("\n=== Starting Drone Tracking Scenario ===")
print("Target drone (ID=2) will take off first and hover")
print("Follower drone (ID=1) will take off later and track using YOLO")

# Start target drone control thread (takes off and hovers)
target_thread = threading.Thread(
target=ctrl_target_drone_hover,
args=(target_mav, TARGET_WAIT_TIME),
daemon=True
)
target_thread.start()

# Start follower detection and tracking loop (waits, then takes off and tracks)
try:
detection_and_control_loop(vis, follower_mav, target_mav, TARGET_WAIT_TIME)
finally:
cv2.destroyAllWindows()
print("\nTracking ended.")


if __name__ == "__main__":
main()
</div>

鸟的眼睛

鸟类眼睛的秘密

鸟类的视野宽度普遍在270度以上,甚至可以达到360度。当鸟类注视前方时,双眼的视野还可以重合。如果注视两侧,身侧和身后的影像都可以收入眼中。

草食性鸟为了避免被捕食,眼睛位于两侧,它们的视野非常广阔,稍微歪头就可以将身体周围的景象收入眼中,判断哪个方位有没有危险。但是广阔的视野也会造成它们定位不精准,所以鸟类会采用不断点头的方式,让视野中的东西动起来,来判断目标距离自己的位置。

造成鸟类视觉和人类视觉有这么大不同的,主要是三种细胞在起作用:视觉神经细胞、视杆细胞、视锥细胞。

这三种细胞分别对应的是:视觉敏锐度、光源敏感度、颜色。

简单来说就是,能不能在一堆东西中抓到重点、晚上能不能看清东西、眼中能看到多少颜色。

1.影响视觉敏锐度的是视觉神经细胞在视网膜上的密度,猫头鹰数值在5-10,人类在30-60之间,其它大型猛禽比人类高出2-3倍。

2.视杆细胞主要感知光线,猫头鹰虽然视力那么低,但是它们的视杆细胞分布密度很大,对光线的感知力是人类的35-100倍。

3.视锥细胞主要辨认颜色。每个视锥细胞中含有视色素,不同的视色素吸收不同的光线波长,剩下的波长经过反射在大脑中形成色觉。人类有三种含不同色素的视锥细胞,而鸟类有四种,第四种就是紫外光线。

栉膜的形状像一把梳子,直立于眼后房中。当光线照射进来,被栉膜反射到视网膜上,就会形成变化的阴影。而这个阴影很可能能够帮助鸟类辨别方向。

油滴主要有五种颜色:绿、黄、橙、红和透明色,不同颜色的油滴有不同的作用。飞翔在开阔空中的鸟类, * 蓝色的油滴比例就比较大,这能够让它们的视野中增加其它颜色与蓝色的对比度,也就是与天空的对比度,便于发现空中的猛禽。*

能看到紫外线的代价就是较短的寿命,紫外线会对眼睛造成损伤、视网膜衰退。

如果说人类眼睛中央凹的作用只是让物体更清晰的话,那有些猛禽的中央凹就相当于放大镜和望远镜了

对空识别的视觉模型

原文链接:【反无人机目标检测数据集】空对空视觉检测微型无人机:深度学习的实验评估_det-fly数据集-CSDN博客

尽管深度学习方法在许多目标检测任务中表现出色,但其在无人机检测中的潜力尚未得到充分探索。

近年来,微型无人机(UAV)的视觉检测技术受到越来越多的关注,因为它是许多重要应用的核心技术。例如,在基于视觉的无人机集群系统中,视觉检测至关重要,每个无人机都需要使用机载摄像头来测量其邻近无人机的相对运动[1]。此外,如今微型无人机的恶意使用已成为公共安全和个人隐私的严重威胁。对恶意微型无人机的视觉检测[2][3]是开发民用无人机防御系统的关键技术。另一个应用是无人机之间的“看见并避让”[4]。特别是,随着越来越多的商用无人机占据低空领域,例如用于包裹递送,如何确保无人机能够及时检测到其他无人机以安全导航而不发生碰撞,是一个重要问题。

无人机的检测可以分为两种应用场景。第一种是地对空场景,即在地面上部署摄像头以检测飞行的无人机。第二种场景是空对空场景,即飞行的无人机利用其机载摄像头检测其他飞行的无人机(例如,参见图1)。本文主要关注空对空场景。此外,尽管可以使用不同类型的传感器来检测微型无人机,如视觉、雷达[5]和声学传感器[6],但由于微型无人机的机载载荷极为有限,视觉传感器是空对空场景中少数合适的选择之一。
现有的无人机检测方法可分为两类。第一类是传统方法,由两步操作组成。第一步是提取目标特征,例如使用方向梯度直方图(HOG)或尺度不变特征变换(SIFT)来表示。第二步是使用机器学习算法(如支持向量机(SVM)或Adaboost)对特征进行分类。第二类是基于深度学习的方法,它通过端到端的人工神经网络直接输出检测结果。与传统方法使用手工设计的特征不同,基于深度学习的方法依赖于深度卷积神经网络(DCNN)特征,因此具有更强的表示复杂目标的能力。然而,使用DCNN的缺点是计算需求高,并且需要大量数据集进行训练。

避障用的一个方法是人工势场,类似引力和斥力,把无人机从障碍物排斥开。能不能人工引力,让目标吸引我方的无人机呢

基于人工势场方法(Artificial Potential Field,APF)于 1986 年由 Khatib 所提出,此方法是将智 能体(移动机器人或无人机)所处环境用势场形式来描述,通过其位置信息来控制智能体的避障或 规避运动,其核心思想是构建出障碍物周围斥力场和目标点位置引力场两个势场共同作用下的人 工势场环境,搜索或探索势场函数梯度下降方向来寻找无碰撞较优的路线。势场一般由两部分构 成,一部分是目标点智能体(旋翼无人机)产生的引力场,方向由智能体指向目标点;另一部分是 障碍物与智能体之间产生的斥力场。执行搜索任务空间的总势场可表示为斥力场和引力场两个势 场相累加合力的作用,从而通过引力和斥力累加合力来控制无人机的运动。 为了便于研究,将智能体(旋翼无人机)视为球形刚体模型,将障碍物视为球体。人工势场包 含引力场和斥力场,目标点位置对智能体(无人机)施加引力,障碍物对智能体施加斥力,避免智 能体与自身发生碰撞。智能体(无人机)路径规划中,各点的合力为该点斥力和引力总和。

哈里斯鹰优化算法(HHO)

哈里斯鹰优化算法灵感来源于自然界中哈里斯鹰的合作行为和追逐方式,即突袭。在这种聪明的策略中,几只鹰从不同的方向合作扑向猎物,试图出其不意。哈里斯鹰可以根据场景的动态性质和猎物的逃脱模式揭示各种追逐模式。群体围捕

电子科大

单一 YOLO 检测方法相比,改进 YOLO 算法的误检率降低了 10%,漏检率降低了 5%;在轨迹预测方面,与传统的贝塞尔曲线预测方法相比,本文的预测算法在预测误差方面降低了16.2%,预测部分计算时长减少了 13.6%。

杭电

无人机因其多功能性和经济效益,在众多民用领域中得到了广泛应用。然而无人机的发展增加了对强大的反无人机系统的需求。作为反制的首要环节,如何快速、有效地检测、跟瞄目标无人机具有重要意义。基于视觉检测的低成本和易部署优势,本研究提出了一种基于机器视觉的轻量级无人机跟踪与瞄准系统,并针对无人机视觉检测中的数据集缺乏、小目标检测难、嵌入式平台部署及检测范围扩展四个问题进行研究,具体包括以下方面:(1) 数据集构建与算法分析:针对无人机检测领域缺少数据集的问题,本研究构建了一个包含 10800 张图像及其标注文件的高质量数据集。这些图像由 4K 分辨率高清相机拍摄,涵盖了多样化的拍摄角度、背景、光照条件和飞行高度,确保了数据的多样性和代表性。无人机的相对距离范围为 5 至 200 米,飞行高度在 0 至100 米之间。此外,基于该数据集,本研究使用七种典型深度学习算法进行实验,探究拍摄角度、图像灰度、目标尺度及训练-测试图像分辨率对算法表现的影响。实验结果表明,拍摄角度、目标尺度、图像灰度及分辨率对算法性能有显著影响,且大多数算法在小目标检测方面存在较大困难。(2) YOLO-Drone 算法优化:为解决小目标检测的难题,本研究提出了一种名为 YOLO-Drone 的改进算法。该算法引入多尺度密集连接以提高小目标的检测效果。同时,为避免改进带来的计算量和参数增多,采用多层共享检测头以减少YOLOv8 解耦头的参数和计算量。实验表明,YOLO-Drone 算法在精度上较基准模型 YOLOv8n 提升了 0.1%,召回率提高 19%,mAP50 提升 9.6%,mAP50:95 提升6.7%,检测头参数减少 80%。(3) 嵌入式端优化与加速:为保证 YOLO-Drone 在算力有限的嵌入式设备上依然具备高精度和快速检测能力,本研究在服务器端采用 LAMP 剪枝以进一步减少算法的参数和计算量,同时引入基于响应的知识蒸馏方法以弥补剪枝带来的性能损失。实验结果显示,剪枝后模型的参数减少 88%,计算量降低 40%,且性能下降不超过 1.1%。与其他深度学习模型相比,YOLO-Drone 在小目标检测方面表现最佳,推理速度居于第二。最终,嵌入式端使用 TensorRT 进一步加速 YOLO-Drone的运行,实验表明加速效果超过 50%,模型在嵌入式设备上实现了 14.7ms 的推理延迟,满足实时检测需求。(4)云台控制

南开

无人机技术日渐普及的环境下,各种“黑飞”、“滥飞”事件给公共安全带来了 诸多安全隐患,采用技术手段对无人机进行监测具有重要意义。低空域无人机 具有体积小、机动性高的检测难点。而基于深度学习的目标检测与跟踪算法能 够有效实现低慢小无人机的检测与跟踪,因此展开基于深度学习的高速高精度 高稳定性的检测与跟踪算法的研究具有重要的现实与理论意义。

广东

一是,空中非合作目标的特性 使得无人机难以精确获取其运动信息,这无疑增加了跟踪的难度。二是,空中非合作 目标运动轨迹多变,导致无人机跟踪过程所处的环境复杂,容易受到自身与外界不确 定因素的影响。三是,跟踪空中非合作目标还要求跟踪系统具备快速反应的能力。例 如,在跟踪敌方目标时,一旦目标察觉到有飞行器近距离跟踪,可能会采取快速变换 轨道的方式以摆脱追踪。因此,如何迅速接近空中非合作目标并稳定跟随其运动轨迹, 是实现其他任务的关键所在。

(1)对于空中非合作目标跟踪问题,跟踪器与目标之间无法通信,跟踪器只能通过测 量工具获取目标信息[38]。为此,一些学者对基于视觉传感器的跟踪控制进行研究。实 际上,基于视觉的无人机是通过机载视觉传感器捕捉目标信息(如目标的方位角和仰 角),但其无法直接测量相对距离[39, 40]。为此,Zhao 等人提出了一种基于视觉的控制 算法,它可以通过无人机的高度估计相对距离[41]。然而,对于空中目标而言,相对距离 无法从跟踪器的高度估算,必须通过其他方法获得。通过使用相机球面投影模型和中 心点图像特征,Mebarki 等人提出了一种基于图像的非线性控制器,实现无人机控制, 但系统收敛速度较慢[42]。Zheng 等人提出了一种基于虚拟相机的控制方法,可以在不 进行图像处理的情况下恢复无人机的动力学特性,但它需要目标的先验知识[43]。因此, 在相对位置未知且没有目标先验知识的情况,使用基于视觉的无人机跟踪空中非合作 目标是一个有待解决的问题。

(2)外界干扰 无人机需要较强的抗干扰能力,以便在风或其他干扰情况下进行精确跟踪。为了 获得理想的鲁棒控制性能,有必要应用一些抑制或消除扰动的方法[44–46]。扰动观测器 (Disturbance Observation,DO)是增强鲁棒性的有效工具[47–49]。为有效观测非线性系 统中的包络干扰,Chen 构建了一个非线性扰动观测器渐进估计干扰[50]。根据滑模控制 算法,Benallegue 等人设计了一种滑模扰动观测器来估计风引起的外界扰动,以提高 鲁棒性[51]。为更精确的估计外界干扰,需要提高干扰观测器中开关函数的增益,但过 大的增益会导致抖震。为了解决这个问题,超扭曲算法被应用到扰动观测器设计中[52]。 超扭曲算法是基于二阶非线性技术,其提高了控制方案的可行性,即时间效率和鲁棒 性[53, 54]。Han 等人设计了一种非线性扰动观测器来估计严格反馈系统的未知干扰[55]。 以上所提到的干扰观测器只实现渐进稳定

[38] LIU W, LI Z, SUN S, et al. Design a novel target to improve positioning accuracy of
autonomous vehicular navigation system in GPS denied environments[J]. IEEE Trans-
actions on Industrial Informatics, 2021, 17(11): 7575-7588.
[39] STEPANYAN V, HOVAKIMYAN N. Visual tracking of a maneuvering target[J]. Jour-
nal of Guidance, Control, and Dynamics, 2008, 31(1): 66-80.
[40] LI T, YU J, QIU Q, et al. Hybrid uncalibrated visual servoing control of harvesting
robots with RGB-D cameras[J]. IEEE Transactions on Industrial Electronics, 2022, 70
(3): 2729-2738.
[41] ZHAO W, LIU H, LEWIS F L, et al. Robust visual servoing control for ground target
tracking of quadrotors[J]. IEEE Transactions on Control Systems Technology, 2019, 28
(5): 1980-1987.
[42] MEBARKI R, LIPPIELLO V, SICILIANO B. Nonlinear visual control of unmanned
aerial vehicles in GPS-denied environments[J]. IEEE Transactions on Robotics, 2015,
31(4): 1004-1017.
[43] ZHENG D, WANG H, WANG J, et al. Image-based visual servoing of a quadrotor using
virtual camera approach[J]. IEEE/ASME Transactions on Mechatronics, 2016, 22(2):
55
972-982.
[44] ZHENG X, LI X M, YAO D, et al. Observer-based finite-time consensus control for
multiagent systems with nonlinear faults[J]. Information Sciences, 2023, 621: 183-199.
[45] NI J, SHI P. Adaptive neural network fixed-time leader-follower consensus for multi-
agent systems with constraints and disturbances[J]. IEEE Transactions on Cybernetics,
2020, 51(4): 1835-1848.
[46] YAO D, LI H, SHI Y. Adaptive event-triggered sliding-mode control for consensus
tracking of nonlinear multiagent systems with unknown perturbations[J]. IEEE Trans-
actions on Cybernetics, 2022, 53(4): 2672-2684.
[47] WANG C, ZUO Z, SUN J, et al. Consensus disturbance rejection for Lipschitz nonlinear
multi-agent systems with input delay: A DOBC approach[J]. Journal of the Franklin
Institute, 2017, 354(1): 298-315.
[48] REN H, WANG Y, LIU M, et al. An optimal estimation framework of multi-agent
systems with random transport protocol[J]. IEEE Transactions on Signal Processing,
2022, 70: 2548-2559.
[49] MA L, ZONG G, ZHAO X, et al. Observed-based adaptive finite-time tracking control
for a class of nonstrict-feedback nonlinear systems with input saturation[J]. Journal of
the Franklin Institute, 2020, 357(16): 11518-11544.
[50] CHEN F, LEI W, ZHANG K, et al. A novel nonlinear resilient control for a quadro-
tor UAV via backstepping control and nonlinear disturbance observer[J]. Nonlinear
Dynamics, 2016, 85: 1281-1295.
[51] BENALLEGUE A, MOKHTARI A, FRIDMAN L. High-order sliding-mode observer
for a quadrotor UAV[J]. International Journal of Robust and Nonlinear Control: IFAC-
Affiliated Journal, 2008, 18(4-5): 427-440.
[52] NAGESH I, EDWARDS C. A multivariable super-twisting sliding mode approach[J].
Automatica, 2014, 50(3): 984-988.
[53] UTKIN V. On convergence time and disturbance rejection of super-twisting control[J].
IEEE Transactions on Automatic Control, 2013, 58(8): 2013-2017.
56
广东工业大学硕士学位论文
参考文献
[54] 涂宇, 王怡, 吴志海, 等. 基于超扭曲算法的解耦非奇异快速终端滑模[J]. 控制工
程, 2020, 27: 271-277.
[55] HAN S I. Fuzzy supertwisting dynamic surface control for MIMO strict-feedback non-
linear dynamic systems with supertwisting nonlinear disturbance observer and a new
partial tracking error constraint[J]. IEEE Transactions on Fuzzy Systems, 2019, 27(11):
2101-2114.

南航

写的不错 基于视觉的无人机目标检测跟踪与轨迹预测技术研究 多旋翼无人机在快速发展带来广泛应用的同时,也因为“滥飞”和“黑飞”等问题,给社 会生活和个人安全带来了危害,因此亟需开展对反无人机系统的研究工作。而近年来的深度学 习大力发展,其中基于神经网络的目标检测与轨迹预测技术是研究热点。本文对反无人机系统 中的无人机目标检测跟踪算法和轨迹预测技术进行研究,最后搭建了实验平台进行实飞验证。 首先, 针对机载视觉系统中的无人机目标检测和跟踪任务要求,设计了整个视觉检测跟踪 引导的流程,并给出了系统的总体方案,根据系统的性能指标,进行了硬件上的选型和调试。 其次, 针对小型多旋翼无人机目标检测跟踪问题,本文提出了一种融合 AirBorne-YOLOv3 检测模型的相关核滤波跟踪算法。所提算法针对机载设备算力低和无人机目标尺度变化大、部 分场景背景复杂且目标尺寸较小的特点,替换了原算法的主干网络,引入了改进的感受野模块, 对先验框进行优化和重分配,并提出了一种针对小目标检测的新的回归损失函数。最后通过互 补滤波的方式将检测算法与跟踪算法融合,实验结果表明,所提算法在保证实时性的同时,提 高了对无人机目标的检测精度,尤其是对小目标,且跟踪也具有尺度适应性。 接着,针对多旋翼无人机飞行灵活、可频繁变向等特点,本文提出了一种基于双向门控循 环单元的轨迹预测模型,通过设计并整合两种不同的预测框架,包括基于相邻两点的位置变化 的预测和基于两点间隔的位置变化的预测,提高了算法对无人机在飞行拐点处的位置预测精度。 最后,搭建了反无人机系统实飞验证平台,将无人机检测跟踪和轨迹预测算法移植到机载 处理器上进行实飞,实验表明,本文设计的无人机目标检测跟踪算法和轨迹预测算法满足了反 制系统的需求,具备工程可实践性。

KCF 跟踪算法主要是用一个叫岭回归的分类模型对相关滤波器进行训练[42],并对目标相关
区域及周边进行采样,得到正负样本,并计算与下一帧的相关性,最后将输出响应最高的部分
作为待跟踪目标。根据待跟踪无人机的运动特性,下一时刻物体出现在目标周围区域的概率大
于相距较远的区域,在工程实践当中,样本采用的是高斯分布,即样本距离目标的距离可以被
度量为[0,1]之间的数值。接着使用样本循环移位的方法对目标周边区域进行循环矩阵采样,目
的是加快计算,再用这些样本训练分类器,从而完成最终的跟踪目标判别。

把 AirBorne-YOLOv3 的检测结果反馈给 KCF 来修正跟踪结果,AirBorne-YOLOv3
检测算法可以检测不同尺度大小的目标,且针对小目标也能得到较高的准确率

多旋翼无人机飞行轨迹是一种基于时间序列的数据,且利用了历史飞行数据信
息,而前馈神经网络是一种静态网络,不具备“记忆”功能,因此在此基础上增加了短期记忆
能力的循环神经网络应运而生。但是在网络的学习过程中,遇到的主要问题就是梯度爆炸和梯
度消失,且很难建模长时间间隔的状态之间的依赖关系,为了改善循环神经网络的长程依赖关
系,以下的两种网络给出了具体的方案。

长短期记忆网络(LSTM)改善了梯度爆炸或消失的问题[48]

门控循环单元(GRU)相比 LSTM 来说更加简单,它是源于 Pavia 在更加复杂的 LSTM 模
型中做出的简化[51],其参数更少,同时 GRU 引入了更新门用来控制遗忘和更新间的平衡,

image-20251030174027007

在跟踪算法中加入预测算法,在预测值周围进行搜索匹配,减少搜索的范围。
常见的预测算法有卡尔曼滤波、粒子滤波等[15],还可以通过减少内核的方式减少
搜索范围,如 Meanshift 算法,Camshift 算法等

多模融合识别技术所依赖的核心在于对不同
波段、不同成像机制和不同数据处理模式的兼容与充分
挖掘,既能够各自发挥分辨率高、全天时与全天候观测、
远距离监测等不同优势,又能够通过多源信息的互补性
降低单一传感器误检与漏检的风险,从而显著提升对低
空飞行小目标的识别效率与准确率

  • 基于融合的3D检测:
    • 将雷达提供的可疑目标3D位置与高分辨率光学图像进行融合。雷达先“发现”目标,然后引导摄像头“看清”并识别目标,这是一种非常有效的协同工作模式。
    • 例如,可以使用雷达点云作为3D候选区域,然后在对应的图像区域进行精细识别。
  • 运动特征检测:
    • 由于目标小,外观特征弱,可以利用其运动特征。通过分析连续帧中微小的运动模式,可以将无人机从静态背景中分离出来。
  • 时序信息利用:
    • 不依赖于单帧检测,而是使用多帧数据或视频流,通过时序模型(如3D卷积、Transformer、递归神经网络)来整合信息,提升对弱小目标的检测能力。

目标识别是一个,跟踪算法是一个,单目标跟踪 多目标跟踪 ,通用目标跟踪 特定目标跟踪 比如 KCF BoT-SORT

全局搜索+局部搜索,如果确定了目标就在局部搜索,减少计算量

yolo12开始引入了注意力机制,但是传统的transformer速度慢,精度高

复旦 激光雷达+视觉Yolov5+卡尔曼滤波 跟踪室内无人机

UAV Tracking with Lidar as a Camera Sensor in GNSS-Denied Environments

2023年International Conference on Localization and GNSS (ICL-GNSS)

ousetr公司出品的激光雷达 激光雷达+摄像头 OS0-128 10hz激光雷达摄像头,无人机配备了OptiTrack标记,可在运动捕捉(MOCAP)系统中以100 Hz的频率获取无人机的实际位置,该系统在图2中也有部分显示

ROS Noetic Ubuntu 20.04 YOLOv5 Jetson Nano Open3D https://www.open3d.org

项目代码 https://github.com/TIERS/UAV-tracking-based-on-LiDAR-as-a-camera

ROS resource monitor tool 测量硬件使用情况 https://github.com/alspitz/cpu_monitor

近距离的无人机精确跟踪,有利于对接等精密操作

在本文中,我们提出了一种基于图像和Ouster激光雷达传感器生成的3D点云数据集成的无人机跟踪方法。我们遵循的方法示意图如图1所示。与其他仅依赖点云的方法不同,该方法无需手动给出无人机的初始位置,即可在信号图像中检测到无人机。此外,该检测过程还会在点云中生成一个近似感兴趣区域(ROI),如果未检测到无人机,该区域将进一步扩大。
这种方法通过避免进行全面的点云搜索来减少计算开销。无人机识别是通过在感兴趣区域(ROI)内对点进行聚类来实现的,然后使用卡尔曼滤波器(KF)进行连续的位置估计。

距离7米以上,点是个位数 2m以内可以分析出形状。增加部分反射可以增加点

基于图像的无人机跟踪方法平均误差相对较小;然而,其整体误差分布并不一致,因为Seq 1序列中的Y轴误差高达0.3米。相反,基于点云的无人机跟踪方法平均误差最大,但其误差分布更为均匀。另一方面,我们提出的方法实现了最小的平均误差和最小的误差波动。此外,为了补充定量轨迹分析,我们还从三个不同视角提供了基于点云跟踪方法和我们提出方法的轨迹可视化,如图6所示,其行为更为一致。

国外的激光雷达太贵,可以考虑国产

复旦的MDPI论文

这是他们团队用一种方法发了很多会议,这是唯一一个期刊的

A Benchmark for Multi-Modal LiDAR SLAM with Ground Truth in GNSS-Denied Environments MDPI的remote sensing

机载激光雷达室内建图 不是无人机追踪

芬兰图尔库大学

Adaptive Lidar Scan Frame Integration: Tracking Known MAVs in 3D Point Clouds

激光雷达点云中跟踪微型飞行器(MAVs)的新方法

这三种模态描述如下:(i)自适应高频跟踪。在第一个过程中,稀疏点云以高达100赫兹的频率进行集成。微型飞行器(MAV)只能通过数量减少的点进行跟踪,但我们能够以高精度估计其位置和速度。在此过程中,微型飞行器在所有处理过的帧中不一定都能被识别出来。
(ii)自适应中频跟踪。第二个过程在典型激光雷达扫描仪的频率范围内(即5至20赫兹)运行。该范围内的频率会动态调整,以优化点云的密度。在这些频率下,提取的代表微型飞行器(MAV)的点云会因运动而失真,从而导致定位和速度估计的准确性降低。然而,由于该过程能够在大多数(如果不是全部)帧中识别出MAV,因此能够实现更稳健和持久的跟踪。
(iii)低频轨迹和物体验证。与前两个过程并行运行的第三个也是最后一个过程是进行长期跟踪,并根据预定义的维度约束验证微型飞行器(MAV)的重构轨迹。

Livox 3D Lidar with 81.7 度 x25.1度 FoV 100HZ ROS Melodic under Ubuntu 18.04

The computer runs the

robot’s driver1 , the Tello MAV driver2 , the Livox lidar driver3 ,

and our open-source MAV tracking package4 . The latter is a

multi-threaded node able to process the different point clouds

in real time. The point cloud library (PCL) [34] is utilized to

extract the position of the MAV from the lidar’s point cloud.

1 https://github.com/TIERS/dashgo-d1-ros

2 https://github.com/TIERS/tello-driver-ros

3 https://github.com/Livox-SDK/livox ros driver

4 https://github.com/TIERS/adaptive-lidar-tracking

分析了不同距离点云密度,十米也就个位数了

德国

Potential of LiDAR sensors for the detection of UAVs

车载激光雷达探测无人机

数据For our experiments we used data which we acquired with the measurement vehicle MODISSA [10] during a joint field

trial in cooperation with the Institute Franco-Allemand

不公开

Laurenzis M., Hengy, S., Hammer, M., Hommes, A., Johannes, W., Rassy, O., Bacher, E., Schertzer, S., Poyet, J.-M., “An adaptive sensing approach for detection of small UAV: first investigation of static sensor network and moving sensor platform,” Proc. SPIE 10646 Paper 10646-27, (2018)

对多种无人机进行了检测,分析不同距离的点数,有的使用视觉可以看到,但是激光没用。根据召回率确定,超过50%的FN在30米以上的距离内被检测到,因此认为

3m-30m是激光雷达探测无人机的合理范围


© 2025 Gravitykole 使用 Stellar 创建
总访问 113701 次 | 本页访问 326 次