当前位置: 首页 > news >正文

基于Python进行人脸识别控制小灯闪烁(识别到指定人脸)

这里我没有给 ESP8266 刷入 MicroPython 固件,而是用的Python和Mixly(在Mixly上写的代码,这个是一个可以图形化的软件,也可以进行部分代码编写,当然复杂程序还是用Arduino IDE,这边两者都可实现,以下仅展示用Mixly2.0进行的操作),且是HTTP服务器版本,非MQTT版本。

此篇是在该篇基础上进行了优化可点此处直接跳转,引入了人脸识别(即校验到指定人脸才亮灯)

用了face_recognition人脸识别库,需要先进行安装:

pipinstallface_recognition

注意如果安装过程中如果有报错类似:

!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!You must use Visual Studio to build a python extension on windows. If you are getting this error it means you have not installed Visual C++. Note that there are many flavors of Visual Studio, like Visual StudioforC#development. You need toinstallVisual StudioforC++.!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

可以先安装Visual Studio的C++构建工具
或者直接下载dlib库,然后再pip install face_recognition。
dlib包链接:dlib包链接

以下是代码:

importrequestsimportcv2importface_recognitionimportosimporttimeimportthreading# ESP8266的IP地址ESP8266_IP="192.168.1.12"BASE_URL=f"http://{ESP8266_IP}"TEST_URL=f"{BASE_URL}/text/plain"LED_ON_URL=f"{BASE_URL}/led/on"LED_OFF_URL=f"{BASE_URL}/led/off"classFaceRecognitionSystem:def__init__(self):"""初始化人脸识别系统"""self.known_faces_dir=r"D:\PythonProject\known_faces"# 图片存放地址self.known_face_encodings=[]self.known_face_names=[]self.last_trigger_time=0self.led_cooldown=3# LED冷却时间(秒)self.led_is_on=False# 加载已知人脸self.load_known_faces()defload_known_faces(self):"""加载已知人脸图片"""ifnotos.path.exists(self.known_faces_dir):print(f"已知人脸目录不存在:{self.known_faces_dir}")returnall_files=os.listdir(self.known_faces_dir)forfilenameinall_files:# 检查文件后缀(兼容大小写)iffilename.lower().endswith(('.jpg','.jpeg','.png')):image_path=os.path.join(self.known_faces_dir,filename)print(f"图片路径:{image_path}")# 检查文件是否为有效图片try:image=face_recognition.load_image_file(image_path)exceptExceptionase:print(f"图片加载失败:{e}")continue# 获取人脸编码face_encodings=face_recognition.face_encodings(image)iflen(face_encodings)>0:self.known_face_encodings.append(face_encodings[0])self.known_face_names.append(os.path.splitext(filename)[0])print(f"已加载人脸:{filename}")else:print(f"未在图片中检测到人脸:{filename}")else:print(f"非支持的图片格式:{filename}")print(f"最终加载人脸数量:{len(self.known_face_encodings)}")defrecognize_faces(self,frame):"""识别人脸并返回是否匹配已知人脸"""ifnotself.known_face_encodings:returnFalse# 调整图像大小以加快处理速度small_frame=cv2.resize(frame,(0,0),fx=0.25,fy=0.25)# 转换颜色空间 BGR->RGBrgb_small_frame=cv2.cvtColor(small_frame,cv2.COLOR_BGR2RGB)# 检测所有人脸位置face_locations=face_recognition.face_locations(rgb_small_frame)ifnotface_locations:returnFalse# 获取所有人脸编码face_encodings=face_recognition.face_encodings(rgb_small_frame,face_locations)# 与已知人脸比较forface_encodinginface_encodings:matches=face_recognition.compare_faces(self.known_face_encodings,face_encoding,tolerance=0.4)# 如果匹配到任意已知人脸ifTrueinmatches:print("匹配到已知人脸")returnTrueelse:print("未匹配到已知人脸")returnFalsedefcontrol_led(self,should_turn_on):"""控制LED开关"""current_time=time.time()ifshould_turn_onandnotself.led_is_on:# 检查冷却时间ifcurrent_time-self.last_trigger_time>=self.led_cooldown:print("检测到已知人脸,正在打开LED...")response=requests.get(LED_ON_URL,timeout=3)ifresponse.status_code==200:print("LED已打开")self.led_is_on=Trueself.last_trigger_time=current_time# 设置3秒后关闭的计时器defturn_off_led():time.sleep(3)response=requests.get(LED_OFF_URL,timeout=3)ifresponse.status_code==200:print("✓ LED已关闭")self.led_is_on=Falsetimer=threading.Thread(target=turn_off_led)timer.daemon=Truetimer.start()else:print(f"无法打开LED:{response.status_code}")deftest_esp8266_connection():"""测试ESP8266连接"""print("测试ESP8266连接...")try:response=requests.get(f"{BASE_URL}/",timeout=3)ifresponse.status_code==200:print(f"ESP8266连接成功 (IP:{ESP8266_IP})")returnTrueexcept:print(f"无法连接到ESP8266 (IP:{ESP8266_IP})")returnFalsedefmain():"""主函数"""# 测试ESP8266连接ifnottest_esp8266_connection():print("连接测试失败,请检查配置")return# 初始化人脸识别系统face_system=FaceRecognitionSystem()ifnotface_system.known_face_encodings:print("未找到已知人脸,请将人脸图片放入 'known_faces' 文件夹")return# 打开摄像头print("正在打开摄像头...")cap=cv2.VideoCapture(0)ifnotcap.isOpened():print("无法打开摄像头")returnprint("摄像头已打开,退出请按 'q' 键退出程序")try:whileTrue:# 读取摄像头画面ret,frame=cap.read()ifnotret:print("无法读取摄像头画面")break# 识别人脸face_detected=face_system.recognize_faces(frame)# 控制LEDface_system.control_led(face_detected)# 在画面上显示状态status_text="已知人脸"ifface_detectedelse"未知人脸"color=(0,255,0)ifface_detectedelse(0,0,255)cv2.putText(frame,f"status:{status_text}",(10,30),cv2.FONT_HERSHEY_SIMPLEX,1,color,2)cv2.putText(frame,"LED: ON"ifface_system.led_is_onelse"LED: OFF",(10,70),cv2.FONT_HERSHEY_SIMPLEX,1,(0,255,255)ifface_system.led_is_onelse(128,128,128),2)cv2.putText(frame,"Press 'q' to quit",(10,frame.shape[0]-10),cv2.FONT_HERSHEY_SIMPLEX,0.6,(255,255,255),2)# 显示画面cv2.imshow('FaceRecognition',frame)# 按'q'退出ifcv2.waitKey(1)&0xFF==ord('q'):break# 控制处理频率,避免过于频繁time.sleep(0.1)exceptExceptionase:print(f"\n程序出错:{e}")finally:# 释放资源cap.release()cv2.destroyAllWindows()# 确保LED关闭try:ifface_system.led_is_on:requests.get(LED_OFF_URL,timeout=2)print("程序退出,LED已关闭")except:passprint("程序已结束")if__name__=="__main__":main()

仍有可优化地方:比如将图片上传到云,从云获取,然后上传时候就进行图片人脸编码,摄像头识别到时可以直接获取。

以上是所有内容,感谢观看。

http://www.jsqmd.com/news/311406/

相关文章:

  • 神经网络深度解析:从神经元到深度学习的进化之路 - 教程
  • 详细介绍:深度学习理论与实战:用生活案例理解回归模型
  • 行为型设计模式:借助某个对象来协调多对象交互的中介者模式,不允许你不知道!
  • 从Vue到Spring Boot:一个Java全栈工程师的实战面试实录
  • 食品防划痕柔性夹爪供应商推荐(2026年1月更新)
  • 从 GPT-2 到 gpt-oss[1]:架构进展分析 - 实践
  • 互联网大厂Java求职者面试实战:Spring Boot与微服务全栈技术问答解析
  • 【毕设项目计算机毕设】基于springboot+vue实现的在线考试系统
  • 膝盖软骨磨损吃什么牌子营养品可以补救:营养补充+康复训练(医生方案)
  • 2026寻找可靠的自适应夹爪供应商?这家金牌厂商值得推荐
  • 蓝奥环保靠谱不,在行业地位及交货及时性如何
  • 2026年平移门电机优质大品牌推荐:锐玛电机(AAVAQ)全场景解决方案解析
  • 聊聊苏州靠谱的新加坡自雇移民品牌机构,怎么选择
  • 2026年1月高端卷帘门电机品牌推荐:锐玛电机(AAVAQ)德系精工与本地化服务双优之选
  • 分享诚信的货运发货企业,全国服务好的有哪些
  • 2026国产高端庭院门电机品牌推荐:锐玛电机(AAVAQ)德系基因赋能本土精工
  • 2026深圳夹爪公司推荐:精密制造与高效服务实力厂家深度分析
  • 2026年大型集团不动产资产管理系统软件优质推荐与盘点
  • 2026数据资产管理平台与资产入表优质厂商推荐
  • 2026年数据资源管理系统推荐 企业级高效选型参考方案
  • 2026年不动产资产管理系统软件 大型集团优选指南
  • 2026年企业数据管理厂商推荐:主数据与数据底座服务商
  • 人工智能数据分析科学家:20个月系统培养大纲 (1.0版)【20260128】001篇
  • Claude Code 有了“大脑“!这个插件让它自己安排任务
  • java项目--智能无人机平台v3pro
  • file_get_contents 将磁盘扇区内容按字节读入内存的庖丁解牛
  • 有考虑过ai自己grep调用记忆吗
  • 306. Java Stream API - 流特性
  • Vite + Vue3 + TS 封装阿里图标 SVG 全局组件
  • 翱捷科技 Android/Linux 芯片平台功耗软件工程师:核心技术解析与实战