自拍偷在线精品自拍偷,亚洲欧美中文日韩v在线观看不卡

再也不怕別人動電腦了!用Python實時監(jiān)控

開發(fā) 后端 人臉識別
最近突然有個奇妙的想法,就是當(dāng)我對著電腦屏幕的時候,電腦會先識別屏幕上的人臉是否是本人,如果識別是本人的話需要回答電腦說的暗語,答對了才會解鎖并且有三次機會。

前言

最近突然有個奇妙的想法,就是當(dāng)我對著電腦屏幕的時候,電腦會先識別屏幕上的人臉是否是本人,如果識別是本人的話需要回答電腦說的暗語,答對了才會解鎖并且有三次機會。如果都沒答對就會發(fā)送郵件給我,通知有人在動我的電腦并上傳該人頭像。

過程

環(huán)境是win10代碼我使用的是python3所以在開始之前需要安裝一些依賴包,請按順序安裝否者會報錯 

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

接下來是構(gòu)建識別人臉以及對比人臉的代碼 

  1. import face_recognition  
  2. import cv2  
  3. import numpy as np  
  4. video_capture = cv2.VideoCapture(0)  
  5. my_image = face_recognition.load_image_file("my.jpg")  
  6. my_face_encoding = face_recognition.face_encodings(my_image)[0]  
  7. known_face_encodings = [  
  8.     my_face_encoding  
  9.  
  10. known_face_names = [  
  11.     "Admin"  
  12.  
  13. face_names = []  
  14. face_locations = []  
  15. face_encodings = []  
  16. process_this_frame = True  
  17. while True:  
  18.     ret, frame = video_capture.read()  
  19.     small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)  
  20.     rgb_small_frame = small_frame[:, :, ::-1]  
  21.     if process_this_frame:  
  22.         face_locations = face_recognition.face_locations(rgb_small_frame)  
  23.         face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)  
  24.         face_names = []  
  25.         for face_encoding in face_encodings:  
  26.             matches = face_recognition.compare_faces(known_face_encodings, face_encoding)  
  27.             name = "Unknown"  
  28.             face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)  
  29.             best_match_index = np.argmin(face_distances)  
  30.             if matches[best_match_index]:  
  31.                 name = known_face_names[best_match_index]  
  32.             face_names.append(name)  
  33.     process_this_frame = not process_this_frame  
  34.     for (top, right, bottom, left), name in zip(face_locations, face_names):  
  35.         top *= 4  
  36.         left *= 4  
  37.         right *= 4  
  38.         bottom *= 4  
  39.         font = cv2.FONT_HERSHEY_DUPLEX  
  40.         cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)  
  41.         cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)  
  42.         cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)  
  43.     cv2.imshow('Video', frame)  
  44.     if cv2.waitKey(1) & 0xFF == ord('q'):  
  45.         break  
  46. video_capture.release()  
  47. cv2.destroyAllWindows() 

其中my.jpg需要你自己拍攝上傳,運行可以發(fā)現(xiàn)在你臉上會出現(xiàn)Admin的框框,我去網(wǎng)上找了張圖片類似這樣子

識別功能已經(jīng)完成了接下來就是語音識別和語音合成,這需要使用到百度AI來實現(xiàn)了,去登錄百度AI的官網(wǎng)到控制臺選擇左邊的語音技術(shù),然后點擊面板的創(chuàng)建應(yīng)用按鈕,來到創(chuàng)建應(yīng)用界面

打造電腦版人臉屏幕解鎖神器

創(chuàng)建后會得到AppID、API Key、Secret Key記下來,然后開始寫語音合成的代碼。安裝百度AI提供的依賴包 

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

然后是簡單的語音播放代碼,運行下面代碼可以聽到萌妹子的聲音 

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

有了上面的代碼就完成了檢測是否在電腦前(人臉識別)以及電腦念出暗語(語音合成)然后我們還需要回答暗號給電腦,所以還需要完成語音識別。 

  1. import wave  
  2. import pyaudio  
  3. from aip import AipSpeech  
  4. APP_ID = ''  
  5. API_KEY = ''  
  6. SECRET_KEY = ''  
  7. client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)  
  8. CHUNK = 1024  
  9. FORMAT = pyaudio.paInt16  
  10. CHANNELS = 1  
  11. RATE = 8000  
  12. RECORD_SECONDS = 3  
  13. WAVE_OUTPUT_FILENAME = "output.wav"  
  14. p = pyaudio.PyAudio()  
  15. stream = p.open(format=FORMATchannels=CHANNELSrate=RATEinput=Trueframes_per_buffer=CHUNK 
  16. print("* recording")  
  17. frames = []  
  18. for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):  
  19.     data = stream.read(CHUNK)  
  20.     frames.append(data)  
  21. print("* done recording")  
  22. stream.stop_stream()  
  23. stream.close()  
  24. p.terminate()  
  25. wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')  
  26. wf.setnchannels(CHANNELS)  
  27. wf.setsampwidth(p.get_sample_size(FORMAT))  
  28. wf.setframerate(RATE)  
  29. wf.writeframes(b''.join(frames))  
  30. def get_file_content():  
  31.     with open(WAVE_OUTPUT_FILENAME, 'rb') as fp:  
  32.         return fp.read()  
  33. result = client.asr(get_file_content(), 'wav', 8000, {'dev_pid': 1537, })  
  34. print(result) 

運行此代碼之前需要安裝pyaudio依賴包,由于在win10系統(tǒng)上安裝會報錯所以可以通過如下方式安裝。到這個鏈接 https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio 去下載對應(yīng)的安裝包然后安裝即可。

打造電腦版人臉屏幕解鎖神器

運行后我說了你好,可以看到識別出來了。那么我們的小模塊功能就都做好了接下來就是如何去整合它們。可以發(fā)現(xiàn)在人臉識別代碼中if matches[best_match_index]這句判斷代碼就是判斷是否為電腦主人,所以我們把這個判斷語句當(dāng)作main函數(shù)的入口。 

  1. if matches[best_match_index]:  
  2.     # 在這里寫識別到之后的功能  
  3.     name = known_face_names[best_match_index] 

那么識別到后我們應(yīng)該讓電腦發(fā)出詢問暗號,也就是語音合成代碼,然我們將它封裝成一個函數(shù),順便重構(gòu)下人臉識別的代碼。 

  1. import cv2  
  2. import time  
  3. import numpy as np  
  4. import face_recognition  
  5. video_capture = cv2.VideoCapture(0)  
  6. my_image = face_recognition.load_image_file("my.jpg")  
  7. my_face_encoding = face_recognition.face_encodings(my_image)[0]  
  8. known_face_encodings = [  
  9.     my_face_encoding  
  10.  
  11. known_face_names = [  
  12.     "Admin"  
  13.  
  14. face_names = []  
  15. face_locations = []  
  16. face_encodings = []  
  17. process_this_frame = True  
  18. def speak(content):  
  19.     import sys  
  20.     from aip import AipSpeech  
  21.     from playsound import playsound  
  22.     APP_ID = ''  
  23.     API_KEY = ''  
  24.     SECRET_KEY = ''  
  25.     client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)  
  26.     result = client.synthesis(content, 'zh', 1, {'vol': 5, 'per': 0, 'spd': 5, })  
  27.     if not isinstance(result, dict):  
  28.         with open('auido.mp3', 'wb') as file:  
  29.             file.write(result)  
  30.     filepath = eval(repr(sys.path[0]).replace('\\', '/')) + '//auido.mp3'  
  31.     playsound(filepath)  
  32. try:  
  33.     while True:  
  34.         ret, frame = video_capture.read()  
  35.         small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)  
  36.         rgb_small_frame = small_frame[:, :, ::-1]  
  37.         if process_this_frame:  
  38.             face_locations = face_recognition.face_locations(rgb_small_frame)  
  39.             face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)  
  40.             face_names = []  
  41.             for face_encoding in face_encodings:  
  42.                 matches = face_recognition.compare_faces(known_face_encodings, face_encoding)  
  43.                 name = "Unknown"  
  44.                 face_distances = face_recognition.face_distance(known_face_encodings, face_encoding)  
  45.                 best_match_index = np.argmin(face_distances)  
  46.                 if matches[best_match_index]:  
  47.                     speak("識別到人臉,開始詢問暗號,請回答接下來我說的問題")  
  48.                     time.sleep(1)  
  49.                     speak("天王蓋地虎")  
  50.                     error = 1 / 0  
  51.                     name = known_face_names[best_match_index]  
  52.                 face_names.append(name)  
  53.         process_this_frame = not process_this_frame  
  54.         for (top, right, bottom, left), name in zip(face_locations, face_names):  
  55.             top *= 4  
  56.             left *= 4  
  57.             right *= 4  
  58.             bottom *= 4 
  59.             font = cv2.FONT_HERSHEY_DUPLEX  
  60.             cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)  
  61.             cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)  
  62.             cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)  
  63.         cv2.imshow('Video', frame)  
  64.         if cv2.waitKey(1) & 0xFF == ord('q'):  
  65.             break  
  66. except Exception as e:  
  67.     print(e)  
  68. finally:  
  69.     video_capture.release()  
  70.     cv2.destroyAllWindows() 

這里有一點需要注意,由于playsound播放音樂的時候會一直占用這個資源,所以播放下一段音樂的時候會報錯,解決方法是修改~\Python37\Lib\site-packages下的playsound.py文件,找到如下代碼

打造電腦版人臉屏幕解鎖神器

在sleep函數(shù)下面添加winCommand('close', alias)這句代碼,保存下就可以了。運行發(fā)現(xiàn)可以正常將兩句話都說出來。那么說出來之后就要去監(jiān)聽了,我們還要打包一個函數(shù)。 

  1. def record():  
  2.     import wave  
  3.     import json  
  4.     import pyaudio  
  5.     from aip import AipSpeech  
  6.     APP_ID = ''  
  7.     API_KEY = ''  
  8.     SECRET_KEY = ''  
  9.     client = AipSpeech(APP_ID, API_KEY, SECRET_KEY)  
  10.     CHUNK = 1024  
  11.     FORMAT = pyaudio.paInt16  
  12.     CHANNELS = 1  
  13.     RATE = 8000  
  14.     RECORD_SECONDS = 3  
  15.     WAVE_OUTPUT_FILENAME = "output.wav"  
  16.     p = pyaudio.PyAudio()  
  17.     stream = p.open(format=FORMATchannels=CHANNELSrate=RATEinput=Trueframes_per_buffer=CHUNK 
  18.     print("* recording")  
  19.     frames = []  
  20.     for i in range(0, int(RATE / CHUNK * RECORD_SECONDS)):  
  21.         data = stream.read(CHUNK)  
  22.         frames.append(data)  
  23.     print("* done recording")  
  24.     stream.stop_stream()  
  25.     stream.close()  
  26.     p.terminate()  
  27.     wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')  
  28.     wf.setnchannels(CHANNELS)  
  29.     wf.setsampwidth(p.get_sample_size(FORMAT))  
  30.     wf.setframerate(RATE)  
  31.     wf.writeframes(b''.join(frames))  
  32.     def get_file_content():  
  33.         with open(WAVE_OUTPUT_FILENAME, 'rb') as fp:  
  34.             return fp.read()  
  35.     result = client.asr(get_file_content(), 'wav', 8000, {'dev_pid': 1537, })  
  36.     result = json.loads(str(result).replace("'", '"'))  
  37.     return result["result"][0] 

將識別到人臉后的代碼修改成如下 

  1. if matches[best_match_index]:  
  2.     speak("識別到人臉,開始詢問暗號,請回答接下來我說的問題")  
  3.     time.sleep(1)  
  4.     speak("天王蓋地虎")  
  5.     flag = False 
  6.      for times in range(0, 3):  
  7.         content = record()  
  8.         if "小雞燉蘑菇" in content:  
  9.             speak("暗號通過")  
  10.             flag = True  
  11.             break  
  12.         else:  
  13.             speak("暗號不通過,再試一次")  
  14.     if flag:  
  15.         print("解鎖")  
  16.     else:  
  17.         print("發(fā)送郵件并將壞人人臉圖片上傳!")  
  18.     error = 1 / 0  
  19.     name = known_face_names[best_match_index] 

運行看看效果,回答電腦小雞燉蘑菇,電腦回答暗號通過。這樣功能就基本上完成了。

打造電腦版人臉屏幕解鎖神器

結(jié)語

至于發(fā)送郵件的功能和鎖屏解鎖的功能我就不一一去實現(xiàn)了,我想這應(yīng)該難不倒在座的各位吧。鎖屏功能可以HOOK讓鍵盤時間無效化,然后用窗口再覆蓋整個桌面即可,至于郵箱發(fā)送網(wǎng)上文章很多的。 

 

責(zé)任編輯:龐桂玉 來源: 戀習(xí)Python
相關(guān)推薦

2022-04-14 10:22:30

NginxLinux

2020-04-20 15:00:22

DevOps工具代碼

2021-08-12 11:05:07

C++語言內(nèi)存泄露

2021-03-19 09:55:15

Linuxshell命令

2021-05-08 07:53:33

面試線程池系統(tǒng)

2020-05-07 16:08:28

Linuxshell命令

2022-09-20 14:30:24

腳本工具SQL數(shù)據(jù)庫

2021-03-03 12:19:20

原型原型鏈JavaScript

2019-12-26 09:38:57

GitHub工具 wxpy

2025-02-28 09:47:36

2018-05-18 14:39:46

華為 華為云

2020-01-21 21:15:16

WiFi網(wǎng)絡(luò)WiFi6

2019-04-10 08:30:53

Python機器學(xué)習(xí)工具

2014-07-18 15:54:04

goTenna:隨身無

2019-08-19 14:59:49

GitHub代碼開發(fā)者

2020-07-14 20:03:55

Windows 10Windows微軟

2022-04-01 07:52:42

JavaScript防抖節(jié)流

2021-12-21 09:05:46

命令Linux敲錯

2021-11-10 23:26:27

iPhone手機屏幕

2021-08-02 10:14:52

AI數(shù)據(jù)人工智能
點贊
收藏

51CTO技術(shù)棧公眾號