运动传感器
1.访问微信公众平台 https://mp.weixin.qq.com
2.查看服务号开发文档
3.开始开发>接口测试号申请>进入微信公众帐号测试号申请系统
4.扫码登录即可
将app ID和appsecret记录下来
将微信号记录下来
安装HTTP库 requests:
pip install requests
安装opencv
pip install opencv-python
编写代码
运动检测
from playsound import playsound
import datetime
import cv2
import threading
import time
from 发送消息.WxTools import Wx_Tools
"""
运动传感器,当有物体移动大于阈值,将自动报警
"""
def Motion_detected():
camera = cv2.VideoCapture(0, cv2.CAP_DSHOW)
global backGround
global is_send_msg
global is_detected
backGround = None
is_send_msg = False
is_detected = False
es = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (5, 4))
while True:
gra, frame = camera.read()
gray_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) # 转换为灰度图片
gray_frame = cv2.GaussianBlur(gray_frame, (25, 25), 3) # 使用高斯滤波消除噪点
if backGround is None:
backGround = gray_frame
continue
else:
diff = cv2.absdiff(backGround, gray_frame) # 比较两张图片的别
diff = cv2.threshold(diff, 50, 255, cv2.THRESH_BINARY)[1] # 阈值运算
diff = cv2.dilate(diff, es, iterations=3) # 形态学膨胀
contours, hierarchy = cv2.findContours(diff.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
is_detected = False
for c in contours:
if cv2.contourArea(c) < 2000:
continue
(x, y, w, h) = cv2.boundingRect(c)
cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)
is_detected = True
if not is_send_msg:
is_send_msg = True
app_id = '你的app_id '
app_secret = '你的app_secret '
wx_tools = Wx_Tools(app_id, app_secret)
wx_tools.send_wx_customer_msg('关注微信公众号后的微信号', '有人进入, 请留意')
try:
global t2
t2 = threading.Thread(target=play_sound)
t2.start()
except:
pass
if is_detected:
show_text = "Motion:Detected"
show_color = (0, 0, 255)
else:
show_text = "Motion:Undetected"
show_color = (0, 255, 0)
cv2.putText(frame, show_text, (10, 20), cv2.FONT_HERSHEY_SIMPLEX, 0.5, show_color, 2)
cv2.putText(frame, datetime.datetime.now().strftime("%A %d %B %Y %I:%M:%S%p"),
(10, frame.shape[0] - 10), cv2.FONT_HERSHEY_SIMPLEX, 0.35, (0, 255, 0), 1)
cv2.imshow('video', frame)
# cv2.imshow('diff', diff)
key = cv2.waitKey(1) & 0xFFf
if key == ord('q'):
camera.release()
cv2.destroyAllWindows()
def count_time():
while True:
time.sleep(5)
global backGround
global is_send_msg
backGround = None
is_send_msg = False
def play_sound():
playsound('auido.mp3')
if __name__ == "__main__":
t = threading.Thread(target=Motion_detected)
t1 = threading.Thread(target=count_time)
t.start()
t1.start()
发送微信通知
import json
import requests
import time
class Wx_Tools():
"""
查看关注微信公众号的用户
https://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
"""
def __init__(self, app_id, app_secret):
self.app_id = app_id
self.app_secret=app_secret
def get_access_token(self):
url = f'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={self.app_id}&secret={self.app_secret}'
resp=requests. get(url). json()
access_token = resp.get('access_token')
return access_token
def send_wx_customer_msg(self, opend_id, msg="有人闯入了你的家"):
url = f'https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={self.get_access_token()}'
req_data={
"touser": opend_id,
"msgtype": "text",
"text":
{
"content": ("时间:{}\r\n"
"事件:{}\r\n"
"地点:超市".format(time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time())),msg))
}
}
requests.post(url, data=json.dumps(req_data, ensure_ascii=False).encode("utf-8"))
if __name__ == "__main__":
app_id = '你的app_id '
app_secret = '你的app_secret '
wx_tools = Wx_Tools(app_id, app_secret)
wx_tools.send_wx_customer_msg('你的微信号', '有人进入, 请留意')
试试吧!