前言

最近突然有个奇妙的想法,就是当我对着电脑屏幕的时候,电脑会先识别屏幕上的人脸是否是本人,如果识别是本人的话需要回答电脑说的暗语,答对了才会解锁并且有三次机会。如果都没答对就会发送邮件给我,通知有人在动我的电脑并上传该人头像。

过程

环境是win10代码我使用的是python3所以在开始之前需要安装一些依赖包,请按顺序安装否者会报错

pip install cmake -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install dlib -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install face_recognition -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install opencv-python -i https://pypi.tuna.tsinghua.edu.cn/simple

接下来是构建识别人脸以及对比人脸的代码

import face_recognition
import cv2
import numpy as np video_capture = cv2.VideoCapture(0)
my_image = face_recognition.load_image_file("my.jpg")
my_face_encoding = face_recognition.face_encodings(my_image)[0]
known_face_encodings = [
my_face_encoding
]
known_face_names = [
"Admin"
] face_names = []
face_locations = []
face_encodings = []
process_this_frame = True while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1]
if process_this_frame:
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
name = known_face_names[best_match_index]
face_names.append(name) process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
left *= 4
right *= 4
bottom *= 4
font = cv2.FONT_HERSHEY_DUPLEX
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break video_capture.release()
cv2.destroyAllWindows()

其中my.jpg需要你自己拍摄上传,运行可以发现在你脸上会出现Admin的框框,我去网上找了张图片类似这样子



识别功能已经完成了接下来就是语音识别和语音合成,这需要使用到百度AI来实现了,去登录百度AI的官网到控制台选择左边的语音技术,然后点击面板的创建应用按钮,来到创建应用界面



创建后会得到AppID、API Key、Secret Key记下来,然后开始写语音合成的代码。安装百度AI提供的依赖包

pip install baidu-aip -i https://pypi.tuna.tsinghua.edu.cn/simple
pip install playsound -i https://pypi.tuna.tsinghua.edu.cn/simple

然后是简单的语音播放代码,运行下面代码可以听到萌妹子的声音

import sys
from aip import AipSpeech
from playsound import playsound APP_ID = ''
API_KEY = ''
SECRET_KEY = '' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis('你好吖', 'zh', 1, {'vol': 5, 'per': 4, 'spd': 5, }) if not isinstance(result, dict):
with open('auido.mp3', 'wb') as file:
file.write(result) filepath = eval(repr(sys.path[0]).replace('\\', '/')) + '//auido.mp3'
playsound(filepath)

有了上面的代码就完成了检测是否在电脑前(人脸识别)以及电脑念出暗语(语音合成)然后我们还需要回答暗号给电脑,所以还需要完成语音识别。

import wave
import pyaudio
from aip import AipSpeech APP_ID = ''
API_KEY = ''
SECRET_KEY = '' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav" p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording") stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames)) def get_file_content():
with open(WAVE_OUTPUT_FILENAME, 'rb') as fp:
return fp.read() result = client.asr(get_file_content(), 'wav', 8000, {'dev_pid': 1537, })
print(result)

运行此代码之前需要安装pyaudio依赖包,由于在win10系统上安装会报错所以可以通过如下方式安装。到这个链接 https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio 去下载对应的安装包然后安装即可。



运行后我说了你好,可以看到识别出来了。那么我们的小模块功能就都做好了接下来就是如何去整合它们。可以发现在人脸识别代码中if matches[best_match_index]这句判断代码就是判断是否为电脑主人,所以我们把这个判断语句当作main函数的入口。

if matches[best_match_index]:
# 在这里写识别到之后的功能
name = known_face_names[best_match_index]

那么识别到后我们应该让电脑发出询问暗号,也就是语音合成代码,然我们将它封装成一个函数,顺便重构下人脸识别的代码。

import cv2
import time
import numpy as np
import face_recognition video_capture = cv2.VideoCapture(0)
my_image = face_recognition.load_image_file("my.jpg")
my_face_encoding = face_recognition.face_encodings(my_image)[0]
known_face_encodings = [
my_face_encoding
]
known_face_names = [
"Admin"
] face_names = []
face_locations = []
face_encodings = []
process_this_frame = True def speak(content):
import sys
from aip import AipSpeech
from playsound import playsound
APP_ID = ''
API_KEY = ''
SECRET_KEY = ''
client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
result = client.synthesis(content, 'zh', 1, {'vol': 5, 'per': 0, 'spd': 5, })
if not isinstance(result, dict):
with open('auido.mp3', 'wb') as file:
file.write(result)
filepath = eval(repr(sys.path[0]).replace('\\', '/')) + '//auido.mp3'
playsound(filepath) try:
while True:
ret, frame = video_capture.read()
small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)
rgb_small_frame = small_frame[:, :, ::-1]
if process_this_frame:
face_locations = face_recognition.face_locations(rgb_small_frame)
face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)
face_names = []
for face_encoding in face_encodings:
matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
name = "Unknown"
face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)
best_match_index = np.argmin(face_distances)
if matches[best_match_index]:
speak("识别到人脸,开始询问暗号,请回答接下来我说的问题")
time.sleep(1)
speak("天王盖地虎")
error = 1 / 0
name = known_face_names[best_match_index]
face_names.append(name)
process_this_frame = not process_this_frame
for (top, right, bottom, left), name in zip(face_locations, face_names):
top *= 4
left *= 4
right *= 4
bottom *= 4
font = cv2.FONT_HERSHEY_DUPLEX
cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)
cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1) cv2.imshow('Video', frame)
if cv2.waitKey(1) & 0xFF == ord('q'):
break
except Exception as e:
print(e)
finally:
video_capture.release()
cv2.destroyAllWindows()

这里有一点需要注意,由于playsound播放音乐的时候会一直占用这个资源,所以播放下一段音乐的时候会报错,解决方法是修改~\Python37\Lib\site-packages下的playsound.py文件,找到如下代码



sleep函数下面添加winCommand('close', alias)这句代码,保存下就可以了。运行发现可以正常将两句话都说出来。那么说出来之后就要去监听了,我们还要打包一个函数。

def record():
import wave
import json
import pyaudio
from aip import AipSpeech APP_ID = ''
API_KEY = ''
SECRET_KEY = '' client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)
CHUNK = 1024
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 8000
RECORD_SECONDS = 3
WAVE_OUTPUT_FILENAME = "output.wav" p = pyaudio.PyAudio()
stream = p.open(format=FORMAT, channels=CHANNELS, rate=RATE, input=True, frames_per_buffer=CHUNK) print("* recording")
frames = []
for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):
data = stream.read(CHUNK)
frames.append(data)
print("* done recording") stream.stop_stream()
stream.close()
p.terminate()
wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
wf.setnchannels(CHANNELS)
wf.setsampwidth(p.get_sample_size(FORMAT))
wf.setframerate(RATE)
wf.writeframes(b''.join(frames)) def get_file_content():
with open(WAVE_OUTPUT_FILENAME, 'rb') as fp:
return fp.read() result = client.asr(get_file_content(), 'wav', 8000, {'dev_pid': 1537, })
result = json.loads(str(result).replace("'", '"'))
return result["result"][0]

将识别到人脸后的代码修改成如下

if matches[best_match_index]:
speak("识别到人脸,开始询问暗号,请回答接下来我说的问题")
time.sleep(1)
speak("天王盖地虎") flag = False
for times in range(0, 3):
content = record()
if "小鸡炖蘑菇" in content:
speak("暗号通过")
flag = True
break
else:
speak("暗号不通过,再试一次")
if flag:
print("解锁")
else:
print("发送邮件并将坏人人脸图片上传!")
error = 1 / 0
name = known_face_names[best_match_index]

运行看看效果,回答电脑小鸡炖蘑菇,电脑回答暗号通过。这样功能就基本上完成了。

结语

至于发送邮件的功能和锁屏解锁的功能我就不一一去实现了,我想这应该难不倒在座的各位吧。如果在上面的教程中有什么疑问可以在下面留言或者在我的博客上留言。还有本文纯属原创,转载请注明出处!

我的博客地址

https://www.meitubk.com/

上文有需要解决的问题可以到博客去留言,有邮件通知我会及时去回复。感谢博客园的盆友们支持!

用Python打造电脑人脸屏幕解锁神器附带接头暗号!的更多相关文章

  1. python制作电脑定时关机办公神器,另含其它两种方式,无需编程!

      小编本人目前就是在电脑面前工作,常常会工作到凌晨两三点还在为自己的梦想奋斗着.有时在办公椅上就稀里糊涂睡着了,我相信有很多朋友和我一样,这样是很不好的.第一对身体不好,第二对电脑不好.   对身体 ...

  2. 【python】10分钟教你用python打造贪吃蛇超详细教程

    10分钟教你用python打造贪吃蛇超详细教程 在家闲着没妹子约, 刚好最近又学了一下python,听说pygame挺好玩的.今天就在家研究一下, 弄了个贪吃蛇出来.希望大家喜欢. 先看程序效果: 0 ...

  3. ScreenToGif: 屏幕录制神器

    ScreenToGif:一款小众但很好用的屏幕录制神器  牛人干货 2020-01-07 00:23:08 今天干货君给大家介绍一款电脑屏幕录制神器-ScreenToGif . ScreenToGif ...

  4. 计算Android屏幕解锁组合数

    晚饭时和同事聊到安卓屏幕解锁时会有多少种解锁方案,觉得很有趣,吃完饭开始想办法解题,花了大概2个小时解决.思路如下: 使用索引值0-9表示从左到右.从上到下的9个点,行.列号很容易从索引值得到: 使用 ...

  5. Android 修改屏幕解锁方式

    Android 修改屏幕解锁方式 问题 在手机第一次开机的时候,运行手机激活的APP 在激活APP允许过程中,当用户按电源键的时候,屏幕黑掉,进入锁屏状态 手机默认的锁屏是滑动解锁 用户这个时候再一次 ...

  6. Android Loader使用,屏幕解锁,重复荷载

    正在使用AsyncTaskLoader时间.当手机被解锁,重复加载数据,码,如以下: static class CouponShopQueryLoader extends AsyncTaskLoade ...

  7. Android监听屏幕解锁和判断屏幕状态

    开发后台服务的时候经常需要对屏幕状态进行判断,如果是想要监听屏幕解锁事件,可以在配置里面注册action为 android.intent.action.USER_PRESENT的广播,则可以监听解锁事 ...

  8. 30行Python代码实现人脸检测

    参考OpenCV自带的例子,30行Python代码实现人脸检测,不得不说,Python这个语言的优势太明显了,几乎把所有复杂的细节都屏蔽了,虽然效率较差,不过在调用OpenCV的模块时,因为模块都是C ...

  9. 教你用python打造WiFiddos

    本文来源于i春秋学院,未经允许严禁转载. 0x00 前言因为在百度上很难找到有关于用python打造WiFidos的工具的,而且不希望大家成为一名脚本小子,所以我打算写一篇,需要的工具有scapy,i ...

随机推荐

  1. PMP学习笔记(一)

    前9节列举出了很多例子来辅助理解什么是项目管理,在学习的过程当中听到了一些名词,查询过一些资料之后,在这里梳理出来 1.关键路径法 关键路径是指设计中从输入到输出经过的延时最长的逻辑路径.优化关键路径 ...

  2. Spring 事务注意事项

    使用事务注意事项 1,事务是程序运行如果没有错误,会自动提交事物,如果程序运行发生异常,则会自动回滚. 如果使用了try捕获异常时.一定要在catch里面手动回滚. 事务手动回滚代码 Transact ...

  3. Gold30Mins

  4. 模块 psutil 系统信息获取

    psutil模块介绍 psutil是一个开源切跨平台的库,其提供了便利的函数用来获取才做系统的信息,比如CPU,内存,磁盘,网络等.此外,psutil还可以用来进行进程管理,包括判断进程是否存在.获取 ...

  5. 深入解读ES6系列(一)

    ECMAScript 6(ES6)简介 前言: 哈喽小伙伴们,爱说'废'话的Z又回来了,欢迎来到Super IT曾的博客时间,我说啦这个月要带的福利,说了更的博客肯定不能水你们,要一起进步学习嘛,今天 ...

  6. H - Bone Collector

    H - Bone Collector Many years ago , in Teddy's hometown there was a man who was called "Bone Co ...

  7. Java并发基础09. 多个线程间共享数据问题

    先看一个多线程间共享数据的问题: 设计四个线程,其中两个线程每次对data增加1,另外两个线程每次对data减少1. 从问题来看,很明显涉及到了线程间通数据的共享,四个线程共享一个 data,共同操作 ...

  8. python:爬取博主的所有文章的链接、标题和内容

    以爬取我自己的博客为例:https://www.cnblogs.com/Mr-choa/ 1.获取所有的文章的链接: 博客文章总共占两页,比如打开第一页:https://www.cnblogs.com ...

  9. PTA数据结构与算法题目集(中文) 7-3

    PTA数据结构与算法题目集(中文)  7-3 树的同构 给定两棵树T1和T2.如果T1可以通过若干次左右孩子互换就变成T2,则我们称两棵树是“同构”的.例如图1给出的两棵树就是同构的,因为我们把其中一 ...

  10. CentOS 7 Docker安装

    1. uname -a 查询机器信息,确保CPU为64位,且Linux内核在3.10版本以上 2. 更新yum包: yum update 3. 在 /etc/yum.repos.d下创建 docker ...