物体检测与跟踪
物体检测与跟踪是计算机视觉中的重要任务,其中物体检测用于在图像或视频中定位和识
别物体,而物体跟踪则是在连续帧中追踪物体的位置和轨迹。下面将详细介绍如何使用
OpenCV 进行这些操作。示例代码使用 Python 语言编写。
1. 物体检测:
物体检测的目标是在图像或视频中找到一个或多个感兴趣的物体,并进行识别。OpenCV
提供了多个基于深度学习的物体检测模型,如 YOLO、SSD 和 Faster R-CNN。以下是使用
SSD 模型进行物体检测的示例代码:
```python
import cv2
# 加载模型配置和权重
net = cv2.dnn.readNetFromCaffe('object_detection.prototxt', 'object_detection.caffemodel')
# 读取图像
image = cv2.imread('image.jpg')
# 创建一个输入 blob
blob = cv2.dnn.blobFromImage(cv2.resize(image, (300, 300)), 0.007843, (300, 300), 127.5)
# 设置输入 blob
net.setInput(blob)
# 前向传播计算
detections = net.forward()
# 遍历检测结果
for i in range(detections.shape[2]):
confidence = detections[0, 0, i, 2]
# 设置置信度阈值
if confidence > 0.5:
# 获取物体边界框坐标
box = detections[0, 0, i, 3:7] * np.array([image.shape[1], image.shape[0],
image.shape[1], image.shape[0]])
# 绘制边界框和置信度
cv2.rectangle(image, (int(box[0]), int(box[1])), (int(box[2]), int(box[3])), (0, 255, 0), 2)
text = f'{confidence*100:.2f}%'
cv2.putText(image, text, (int(box[0]), int(box[1])-10), cv2.FONT_HERSHEY_SIMPLEX,