手势开关灯
太久没水,那可不行。今日又来写一段专业程序员看了也皱眉的垃圾全屋智能雏形代码。应该是笑掉大牙级别吧。下面进入正题。首先思路就是通过cvzone那个手势识别,判断开关灯指令。接下来是通过mqtt局域网里发布一下(注意打开防火墙)。最后是另一台机器订阅获得这个消息,解析出开关灯指令,然后执行动作。
手势识别与消息发布端:
import time
import cv2
import numpy as np
from cvzone.HandTrackingModule import HandDetector
from paho.mqtt import client as mqtt_client
broker = '192.168.0.107'
port = 1883
topic = "/mqtt/lamp"
def connect_mqtt():
def on_connect(client, userdata, flags, rc):
if rc == 0:
print("Connected to MQTT Broker!")
else:
print("Failed to connect, return code %d\n", rc)
client = mqtt_client.Client()
client.on_connect = on_connect
client.connect(broker, port)
return client
def publish(client,msg_cmd):
msg = f"messages: {msg_cmd}"
result = client.publish(topic, msg)
status = result[0]
if status == 0:
print(f"Send `{msg}` to topic `{topic}`")
else:
print(f"Failed to send message to topic {topic}")
cap = cv2.VideoCapture(1)
hand_detector = HandDetector(maxHands=1,detectionCon=0.75)
client = connect_mqtt()
client.loop_start()
while True:
length_open = 0
length_close = 0
flag,img = cap.read()
img = cv2.flip(img,1)
if flag:
hands,img = hand_detector.findHands(img,flipType=False)
if hands:
lmlist=hands[0]['lmList']
# 食指与无名指碰撞开灯,
# 大拇指和小指碰撞关灯
# https://blog.csdn.net/vivo01/article/details/135071340
lmlist[8] = lmlist[8][:2] #index_finger
lmlist[16] = lmlist[16][:2] #ring_finger
lmlist[4] = lmlist[4][:2] #thumb
lmlist[20] = lmlist[20][:2] #small finger
length_open, _,img = hand_detector.findDistance(lmlist[8],lmlist[16],img)
length_close,_,img = hand_detector.findDistance(lmlist[4],lmlist[20],img)
if length_open * length_close == 0: #如果手部没有看完全等问题那么会重新循环读取。
continue
if length_open < 40 and length_close > 50:
print("turn on")
publish(client,"1")
time.sleep(0.4)
if length_close < 40 and length_open > 50:
print("turn off")
publish(client,"0")
time.sleep(0.4)
cv2.imshow('img',img)
key = cv2.waitKey(1)
if key == ord('q'):
break
else:
print('Camera failed')
break
cap.release()
cv2.destroyAllWindows()
消息获得与硬件灯泡打开执行端:
import RPi.GPIO as GPIO
import paho.mqtt.client as mqtt
import time
broker = "192.168.0.107"
port = 1883
topic = "/mqtt/lamp"
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
LED=21
GPIO.setup(LED, GPIO.OUT)
GPIO.output(LED,GPIO.LOW)
def on_connect(client, userdata, flags, rc):
print("Connected with result code "+str(rc))
client.subscribe(topic)
def on_message(client, userdata, msg,ledpin=LED):
mypay = msg.payload.decode("utf-8")
#print ("message received:",msg.topic,mypay)
print(mypay)
if mypay[-1]=="1":
GPIO.output(ledpin,GPIO.HIGH)
if mypay[-1]=="0":
GPIO.output(ledpin,GPIO.LOW)
client = mqtt.Client()
client.on_connect = on_connect
client.on_message = on_message
client.connect(broker,port)
#client.loop_forever()
try:
client.loop_forever()
except:
GPIO.output(LED,GPIO.LOW)