# 标记车辆
for (x, y, w, h) in cars:
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Car Detection', frame)
if cv2.waitKey(1) == ord('q'):
break
释放资源
video.release()
cv2.destroyAllWindows()
![在这里插入图片描述](https://img-blog.csdnimg.cn/d186be21bdd046ba8b9b5e533ccbd43c.jpg)3. 目标跟踪示例代码:
import cv2
import dlib
加载目标跟踪器
tracker = dlib.correlation_tracker()
加载视频
video = cv2.VideoCapture(‘object_video.mp4’)
读取第一帧
ret, frame = video.read()
if not ret:
exit()
选择目标区域
bbox = cv2.selectROI(frame, False)
初始化目标跟踪器
tracker.start_track(frame, dlib.rectangle(*bbox))
while True:
# 读取视频帧
ret, frame = video.read()
if not ret:
break
# 更新目标跟踪器
tracker.update(frame)
pos = tracker.get_position()
# 提取目标位置
x = int(pos.left())
y = int(pos.top())
w = int(pos.width())
h = int(pos.height())
# 标记目标
cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)
# 显示结果
cv2.imshow('Object Tracking', frame)
if cv2.waitKey(1) == ord('q'):
break
释放资源
video.release()
cv2.destroyAllWindows()
请注意,示例代码中使用的级联分类器和训练数据文件(如`haarcascade_frontalface_default.xml`和`cars.xml`)可以从Open