下面是一个使用OpenCV和YOLO模型进行跌倒检测的程序示例:
import cv2
import numpy as np
# 加载预训练的YOLO模型
net = cv2.dnn.readNetFromDarknet("yolo.cfg", "yolo.weights")
# 设置要检测的网络层名称
layer_names = net.getLayerNames()
output_layers = [layer_names[i[0] - 1] for i in net.getUnconnectedOutLayers()]
# 加载类标签
classes = []
with open("yolo.names", "r") as f:
classes = [line.strip() for line in f.readlines()]
# 设置跌倒检测的阈值
conf_threshold = 0.5
# 打开摄像头
cap = cv2.VideoCapture(0)
while True:
# 读取摄像头画面
ret, frame = cap.read()
if not ret:
break
# 对画面进行预处理
height, width, channels = frame.shape
blob = cv2.dnn.blobFromImage(frame, 0.00392, (416, 416), (0, 0, 0), True, crop=False)
# 运行YOLO模型以进行目标检测
net.setInput(blob)
outs = net.forward(output_layers)
# 解析模型输出并进行跌倒检测
class_ids = []
confidences = []
boxes = []
for out in outs:
for detection in out:
scores = detection[5:]
class_id = np.argmax(scores)
confidence = scores[class_id]
if confidence > conf_threshold:
# 检测到人物类别
if classes[class_id] == 'person':
# 计算边界框位置
center_x = int(detection[0] * width)
center_y = int(detection[1] * height)
w = int(detection[2] * width)
h = int(detection[3] * height)
x = int(center_x - w / 2)
y = int(center_y - h / 2)
# 添加到检测结果列表中
boxes.append([x, y, w, h])
confidences.append(float(confidence))
class_ids.append(class_id)
# 使用非最大值抑制来消除重叠边界框
indexes = cv2.dnn.NMSBoxes(boxes, confidences, conf_threshold, 0.4)
for i in range(len(boxes)):
if i in indexes:
x, y, w, h = boxes[i]
label = classes[class_ids[i]]
confidence = confidences[i]
# 绘制边界框和标签
cv2.rectangle(frame, (x, y), (x+w, y+h), (0,255,0), 2)
cv2.putText(frame, f"{label} {confidence:.2f}", (x, y-10), cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0,255,0), 2)
# 如果检测到跌倒,则输出警报
if label == 'fall':
print("Fall detected!")
# 显示结果
cv2.imshow("Fall Detection", frame)
# 按下Q键退出程序
if cv2.waitKey(1) == ord('q'):
break
# 释放资源
cap.release()
cv2.destroyAllWindows()
上述程序用到以下文件和资源:
yolo.cfg:YOLO模型的配置文件。
yolo.weights:预训练的YOLO模型权重文件。
yolo.names:YOLO模型类别标签文件,包含了person和fall两个类别。
- 调用摄像头进行实时检测。
请确保你已经下载了YOLO模型的配置文件、权重文件和类别标签文件,并将其放置在相应的目录下。你还可以根据需要调整阈值、摄像头索引等参数。