作者:美图博客

https://www.meitubk.com/zatan/386.html

前言

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

过程

很多人学习python,不知道从何学起。
很多人学习python,掌握了基本语法过后,不知道在哪里寻找案例上手。
很多已经做案例的人,却不知道如何去学习更加高深的知识。
那么针对这三类人,我给大家提供一个好的学习平台,免费领取视频教程,电子书籍,以及课程的源代码!
QQ群:1097524789

环境是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的框框,我去网上找了张图片类似这样子

打造电脑版人脸屏幕解锁神器

创建后会得到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]

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

打造电脑版人脸屏幕解锁神器

结语

至于发送邮件的功能和锁屏解锁的功能我就不一一去实现了,我想这应该难不倒在座的各位吧。锁屏功能可以HOOK让键盘时间无效化,然后用窗口再覆盖整个桌面即可,至于邮箱发送网上文章很多的。

再也不怕别人动电脑了!用Python实时监控的更多相关文章

  1. python 实时监控剪切板,并替换其中的部分内容,重新写入剪切板

    #实时监控剪贴板内容的变化,并替换其中的回车,换行,逗号,再写入剪切板,以供使用. import pyperclip import time last_string = pyperclip.paste ...

  2. 【QT开发】QT在windows下的exe应用程序如何在别人的电脑上直接运行

     当你利用QT编译了一个可执行程序,需要将这个可执行程序拷贝到别人的电脑上运行,这个时候除了这个可执行程序外,还需要支持的库才可用运行.一般来说通过下面的方法可以实现.     首先,需要看你用的是什 ...

  3. Python中Celery 的基本用法以及Django 结合 Celery 的使用和实时监控进程

    celery是什么 1 celery是一个简单,灵活且可靠的,处理大量消息的分布式系统 2 专注于实时处理的异步任务队列 3 同时也支持任务调度 执行流程 Celery 基本使用 tasks.py i ...

  4. 教你用python爬虫监控教务系统,查成绩快人一步!

    教你用python爬虫监控教务系统,查成绩快人一步!这几天考了大大小小几门课,教务系统又没有成绩通知功能,为了急切想知道自己挂了多少门,于是我写下这个脚本. 设计思路:设计思路很简单,首先对已有的成绩 ...

  5. python多线程监控指定目录

    import win32file import tempfile import threading import win32con import os dirs=["C:\\WINDOWS\ ...

  6. 基于邮件系统的远程实时监控系统的实现 Python版

    人生苦短,我用Python~ 界内的Python宣传标语,对Python而言,这是种标榜,实际上,Python确实是当下最好用的开发语言之一. 在相继学习了C++/C#/Java之后,接触Python ...

  7. 性能测试 基于Python结合InfluxDB及Grafana图表实时监控Android系统和应用进程

    基于Python结合InfluxDB及Grafana图表实时监控Android系统和应用进程   By: 授客 QQ:1033553122     1. 测试环境 2. 实现功能 3. 使用前提 4. ...

  8. Python 基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控

    基于Python结合pykafka实现kafka生产及消费速率&主题分区偏移实时监控   By: 授客 QQ:1033553122   1.测试环境 python 3.4 zookeeper- ...

  9. python性能监控初试

    标 题: python性能监控初试作 者: itdef链 接: http://www.cnblogs.com/itdef/p/3990765.html 欢迎转帖 请保持文本完整并注明出处 之前性能统计 ...

随机推荐

  1. 大话一个CPU(沙子是如何影响未来的)

    大话一个CPU(沙子是如何影响未来的) CPU是个啥? 先大体上了解一下 中央处理器 (英语:Central Processing Unit,缩写:CPU),是计算机的主要设备之一,功能主要是解释计算 ...

  2. SQL列转行,行转列实现

    在工作中,大家可能会遇到一些SQL列转行.行转列的问题,恰好,我也遇到了,就在此记录一下.此处所用的是SQLServer2008R2. 行转列,列转行,都要预先知道要要处理多少数据,在此我就以三种方案 ...

  3. python 装饰器(四):装饰器基础(三)叠放装饰器,参数化装饰器

    叠放装饰器 示例 7-19 演示了叠放装饰器的方式:@lru_cache 应用到 @clock 装饰fibonacci 得到的结果上.在示例 7-21 中,模块中最后一个函数应用了两个 @htmliz ...

  4. nginx配置文件服务器——带说明

    需求: 搭建一个文件服务器,提供指定软件下载,在访问文件服务器下载软件时,在访问的主页上要有对应的软件使用.安装等说明(本来是可以搞一个readme的,但这个在文件服务器上要下载还要打开,还不如直接显 ...

  5. Oracle Database Tools

    The following are some products, tools, and utilities you can use to achieve your goals as a databas ...

  6. P3406 海底高铁 (洛谷)

    题目背景 大东亚海底隧道连接着厦门.新北.博艾.那霸.鹿儿岛等城市,横穿东海,耗资1000亿博艾元,历时15年,于公元2058年建成.凭借该隧道,从厦门可以乘坐火车直达台湾.博艾和日本,全程只需要4个 ...

  7. SQL 给某字段添加汉字却显示??

    错误展示: 解决方案: 1.在要修改的数据库上单击鼠标右键,并选择“属性”.   2.在弹出的数据库属性窗口中点击“选择页”中的“选项”.   3.将排序规则由默认的SQL_Latin1_Genera ...

  8. 脸书(Facebook)如何绑定谷歌二次验证码/谷歌身份验证/双重认证?

    1.打开Facebook,找到双重验证界面   打开Facebook,点击“设置”-“安全与登陆”-“使用双重验证”-“身份验证应用”-“在其他设备上设置应用”-“输入验证码” *****想使用Fac ...

  9. jmeter之断言、数据提取器(正则表达式、jsonpath、beanshell)、聚合报告、参数化

    ctx - ( JMeterContext) - gives access to the context vars - ( JMeterVariables) - gives read/write ac ...

  10. LaTeX公式学习

    简介 本文公式较多可能有加载较慢. 使用 LaTeX 的主要原因之一是它可以方便地排版公式.我们使用数学模式来排版公式. 公式 插入公式 可以用一对$来启用数学模式. 行中公式可以用如下方法: $数学 ...