AI老年人防跌倒监测系统,通过摄像头,实时分析异常动作,自动发送给家人或社区报警。 - last_alert_time = current_time

📅 2026-12-01 👤 拼多多助力营销技巧 📂 首码项目 👁️ 134 次阅读

AI老年人防跌倒监测系统

下面是一个基于Python的AI老年人防跌倒监测系统,利用计算机视觉技术实时分析异常动作,并在检测到跌倒时自动通知家人和社区。

import cv2

import numpy as np

import time

import threading

import smtplib

from email.mime.text import MIMEText

from email.mime.multipart import MIMEMultipart

from email.mime.image import MIMEImage

import os

import json

from datetime import datetime

import mediapipe as mp

import pygame

import requests

from twilio.rest import Client

import geocoder

# 初始化pygame用于声音报警

pygame.mixer.init()

fall_sound = pygame.mixer.Sound("fall_detected.wav") # 需要准备一个报警音效文件

# 系统配置

CONFIG_FILE = "config.json"

# 默认配置

DEFAULT_CONFIG = {

"camera_index": 0,

"detection_threshold": 0.7,

"alert_cooldown": 30, # 警报冷却时间(秒)

"email_settings": {

"sender_email": "your_email@example.com",

"sender_password": "your_email_password",

"receiver_emails": ["family_member1@example.com", "family_member2@example.com"],

"smtp_server": "smtp.example.com",

"smtp_port": 587

},

"sms_settings": {

"account_sid": "your_twilio_account_sid",

"auth_token": "your_twilio_auth_token",

"twilio_number": "+1234567890",

"receiver_numbers": ["+0987654321", "+1122334455"]

},

"community_alert_url": "https://community-alert-api.example.com/report",

"geolocation_enabled": True,

"log_file": "fall_detection_log.txt"

}

# 加载或创建配置文件

def load_config():

if os.path.exists(CONFIG_FILE):

try:

with open(CONFIG_FILE, 'r') as f:

return json.load(f)

except:

print("配置文件损坏,使用默认配置")

return DEFAULT_CONFIG

else:

with open(CONFIG_FILE, 'w') as f:

json.dump(DEFAULT_CONFIG, f, indent=4)

print("创建了新的配置文件,请编辑config.json进行设置")

return DEFAULT_CONFIG

# 保存配置

def save_config(config):

with open(CONFIG_FILE, 'w') as f:

json.dump(config, f, indent=4)

# 初始化MediaPipe姿势检测

mp_pose = mp.solutions.pose

pose = mp_pose.Pose(min_detection_confidence=0.5, min_tracking_confidence=0.5)

mp_drawing = mp.solutions.drawing_utils

# 跌倒检测类

class FallDetector:

def __init__(self, config):

self.config = config

self.last_alert_time = 0

self.fall_count = 0

self.alert_active = False

self.current_location = "未知位置"

# 初始化地理位置

if config.get("geolocation_enabled", True):

self.update_location()

def update_location(self):

try:

g = geocoder.ip('me')

if g.ok:

self.current_location = f"{g.city}, {g.state}, {g.country}"

else:

self.current_location = "位置获取失败"

except:

self.current_location = "位置服务不可用"

def detect_fall(self, landmarks):

"""基于姿势关键点检测跌倒"""

if not landmarks:

return False

# 获取关键点坐标

nose = landmarks[mp_pose.PoseLandmark.NOSE.value]

left_hip = landmarks[mp_pose.PoseLandmark.LEFT_HIP.value]

right_hip = landmarks[mp_pose.PoseLandmark.RIGHT_HIP.value]

left_ankle = landmarks[mp_pose.PoseLandmark.LEFT_ANKLE.value]

right_ankle = landmarks[mp_pose.PoseLandmark.RIGHT_ANKLE.value]

# 计算身体方向向量

hip_center = ((left_hip.x + right_hip.x)/2, (left_hip.y + right_hip.y)/2)

ankle_center = ((left_ankle.x + right_ankle.x)/2, (left_ankle.y + right_ankle.y)/2)

# 计算身体角度(垂直方向)

body_vector = (hip_center[0] - ankle_center[0], hip_center[1] - ankle_center[1])

angle = np.degrees(np.arctan2(body_vector[1], body_vector[0]))

# 计算头部与臀部的距离(高度差)

height_diff = abs(nose.y - hip_center[1])

# 跌倒条件:身体接近水平(角度<45度或>135度)且头部靠近臀部(高度差小)

is_fall = (abs(angle) < 45 or abs(angle) > 135) and height_diff < 0.1

return is_fall

def send_alerts(self, frame=None):

"""发送多种形式的警报"""

current_time = time.time()

# 检查冷却时间

if current_time - self.last_alert_time < self.config["alert_cooldown"]:

return

self.last_alert_time = current_time

self.fall_count += 1

timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

location_info = f"位置: {self.current_location}" if self.config["geolocation_enabled"] else ""

# 记录日志

log_entry = f"[{timestamp}] 检测到跌倒事件 #{self.fall_count} | {location_info}\n"

with open(self.config["log_file"], "a") as log_file:

log_file.write(log_entry)

print(log_entry.strip())

# 播放警报声

threading.Thread(target=self.play_alert_sound).start()

# 发送电子邮件警报

threading.Thread(target=self.send_email_alert, args=(timestamp, location_info)).start()

# 发送短信警报

threading.Thread(target=self.send_sms_alert, args=(timestamp, location_info)).start()

# 发送社区警报

threading.Thread(target=self.send_community_alert, args=(timestamp, location_info)).start()

# 标记警报激活状态

self.alert_active = True

threading.Timer(10, self.reset_alert).start() # 10秒后重置警报状态

def play_alert_sound(self):

"""播放警报声音"""

try:

fall_sound.play()

except Exception as e:

print(f"无法播放声音: {e}")

def send_email_alert(self, timestamp, location_info):

"""发送电子邮件警报"""

try:

config = self.config["email_settings"]

msg = MIMEMultipart()

msg['From'] = config["sender_email"]

msg['To'] = ", ".join(config["receiver_emails"])

msg['Subject'] = f"紧急警报:检测到跌倒事件 #{self.fall_count}"

body = f"""

跌倒检测警报

系统检测到可能的跌倒事件。

{timestamp}

事件编号:{self.fall_count}

位置:{location_info}

请立即联系老人确认安全状况!

此邮件由AI防跌倒监测系统自动发送

"""

msg.attach(MIMEText(body, 'html'))

server = smtplib.SMTP(config["smtp_server"], config["smtp_port"])

server.starttls()

server.login(config["sender_email"], config["sender_password"])

server.send_message(msg)

server.quit()

print("电子邮件警报已发送")

except Exception as e:

print(f"发送电子邮件失败: {e}")

def send_sms_alert(self, timestamp, location_info):

"""发送短信警报(使用Twilio)"""

try:

config = self.config["sms_settings"]

client = Client(config["account_sid"], config["auth_token"])

message_body = (

f"紧急警报:检测到跌倒事件 #{self.fall_count}\n"

f"位置: {location_info}\n"

"请立即联系老人确认安全状况!"

)

for number in config["receiver_numbers"]:

message = client.messages.create(

body=message_body,

from_=config["twilio_number"],

to=number

)

print(f"短信发送至 {number}: SID {message.sid}")

except Exception as e:

print(f"发送短信失败: {e}")

def send_community_alert(self, timestamp, location_info):

"""发送社区警报(模拟API调用)"""

try: 拼多多帮助力入口

payload = {

"event_type": "fall_detected",

"timestamp": timestamp,

"location": location_info,

"event_id": self.fall_count,

"reporter": "ai_fall_detection_system"

}

# 实际应用中应使用requests.post发送数据

# response = requests.post(self.config["community_alert_url"], json=payload)

# print(f"社区警报发送状态: {response.status_code}")

print(f"模拟社区警报发送: {json.dumps(payload)}")

except Exception as e:

print(f"发送社区警报失败: {e}")

def reset_alert(self):

"""重置警报状态"""

self.alert_active = False

# 主应用程序

def main():

# 加载配置

config = load_config()

# 初始化跌倒检测器

detector = FallDetector(config)

# 打开摄像头

cap = cv2.VideoCapture(config["camera_index"])

if not cap.isOpened():

print("无法打开摄像头")

return

print("AI老年人防跌倒监测系统已启动...")

print("按 'q' 键退出程序")

while True:

ret, frame = cap.read()

if not ret:

print("无法读取视频帧")

break

# 转换颜色空间

image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)

results = pose.process(image)

# 绘制姿势关键点

image.flags.writeable = True

image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

if results.pose_landmarks:

mp_drawing.draw_landmarks(

image, results.pose_landmarks, mp_pose.POSE_CONNECTIONS)

# 检测跌倒

if detector.detect_fall(results.pose_landmarks.landmark):

cv2.putText(image, "跌倒警告!", (50, 50),

cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)

# 触发警报

if not detector.alert_active:

detector.send_alerts(frame)

# 显示警报状态

if detector.alert_active:

cv2.putText(image, "警报已发送!", (50, 100),

cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 0, 255), 2, cv2.LINE_AA)

# 显示状态信息

cv2.putText(image, f"状态: {'监测中' if not detector.alert_active else '警报中'}", (50, 150),

cv2.FONT_HERSHEY_SIMPLEX, 0.7, (0, 255, 0) if not detector.alert_active else (0, 0, 255), 2)

cv2.putText(image, f"事件计数: {detector.fall_count}", (50, 200),

cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 255), 2)

cv2.putText(image, f"位置: {detector.current_location}", (50, 250),

cv2.FONT_HERSHEY_SIMPLEX, 0.7, (255, 255, 0), 2)

# 显示图像

cv2.imshow('AI老年人防跌倒监测系统', image)

# 退出条件

if cv2.waitKey(1) & 0xFF == ord('q'):

break

# 清理资源

cap.release()

cv2.destroyAllWindows()

if __name__ == "__main__":

main()

系统功能说明

这个AI老年人防跌倒监测系统具有以下核心功能:

1. 实时跌倒检测

- 使用MediaPipe库进行人体姿势估计

- 基于身体角度和高度变化检测跌倒动作

- 实时显示检测结果和警报状态

2. 多级警报系统

- 声音警报:检测到跌倒时播放警报音

- 短信警报:通过Twilio API发送短信给家人

- 电子邮件警报:发送包含时间、位置和事件详情的HTML邮件

- 社区警报:向社区监控系统发送警报(模拟API调用)

3. 位置服务

- 自动获取设备地理位置(城市、州/省、国家)

- 在警报中包含位置信息

4. 系统管理

- 配置文件管理(JSON格式)

- 事件日志记录

- 警报冷却时间设置(防止重复警报)

5. 用户界面

- 实时视频显示

- 姿势关键点可视化

- 系统状态显示

创新与变革管理理论应用

系统在设计中融入了以下创新与变革管理理论:

1. 技术接受模型(TAM):系统设计注重易用性和实用性,降低老年人使用门槛

2. 社会技术系统理论:整合技术系统(AI检测)和社会系统(家庭、社区响应)

3. 变革扩散理论:通过多级警报网络促进新技术在家庭中的采纳和应用

4. 用户中心设计:界面简洁直观,适合老年人使用场景

5. 危机管理理论:建立完整的预警-响应-恢复机制

系统部署与使用指南

硬件要求

- 带摄像头的计算机或树莓派等设备

- 扬声器(用于声音警报)

- 稳定的网络连接

软件依赖

pip install opencv-python mediapipe numpy pygame requests twilio geocoder

配置步骤

1. 创建配置文件

"config.json"(程序会自动生成模板)

2. 填写以下关键信息:

- 邮箱设置(SMTP服务器、账号密码)

- Twilio短信服务凭证

- 接收警报的邮箱和电话号码

- 社区警报API地址(可选)

3. 准备一个报警音效文件

"fall_detected.wav" 放在同一目录

运行系统

python fall_detection_system.py

使用注意事项

1. 确保摄像头视野覆盖监测区域

2. 测试所有警报渠道是否正常工作

3. 定期检查日志文件

"fall_detection_log.txt"

4. 根据环境调整检测灵敏度(修改代码中的阈值)

扩展与改进方向

1. 增强检测算法:

- 集成深度学习模型提高检测准确率

- 添加活动识别区分跌倒和其他动作

2. 系统集成:

- 连接智能家居系统(自动开灯、解锁门)

- 集成医疗应急响应系统

3. 用户体验改进:

- 开发移动端APP查看实时状态

- 添加语音交互功能

- 实现远程视频监控

4. 数据分析:

- 建立跌倒风险预测模型

- 分析活动模式提供健康建议

这个系统通过创新的技术手段解决了老年人跌倒这一重要的社会问题,体现了科技以人为本的设计理念,同时通过多级响应机制构建了家庭-社区协同的安全防护网。

我是编程小白,请大家多多指教,谢谢!

标签: 拼多多助力网站平台 赚钱项目 拼多多助力网 首码项目 手赚APP
拼多多助力营销技巧