opencv行人检测图片视频代码
时间: 2023-09-30 16:02:37 浏览: 111
以下是基于OpenCV的行人检测代码:
```python
import cv2
# 加载分类器
pedestrian_cascade = cv2.CascadeClassifier('haarcascade_fullbody.xml')
# 图片行人检测
img = cv2.imread('image.jpg')
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
pedestrians = pedestrian_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in pedestrians:
cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Pedestrian Detection', img)
cv2.waitKey()
# 视频行人检测
cap = cv2.VideoCapture('video.mp4')
while True:
ret, frame = cap.read()
if not ret:
break
gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
pedestrians = pedestrian_cascade.detectMultiScale(gray, 1.1, 4)
for (x, y, w, h) in pedestrians:
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
cv2.imshow('Pedestrian Detection', frame)
if cv2.waitKey(1) == ord('q'):
break
cap.release()
cv2.destroyAllWindows()
```
需要注意的是,代码中使用了OpenCV自带的Haar分类器进行行人检测。同时,也可以使用更加先进的深度学习模型进行行人检测,如YOLOv5、SSD等。
阅读全文