当前位置: 首页 > 科技观察

再也不怕别人碰电脑了!用Python实时监控

时间:2023-03-13 05:15:48 科技观察

前言最近突然有个绝妙的想法,就是当我面对电脑屏幕的时候,电脑会先识别屏幕上的脸是不是我自己的,如果是自己的,我需要回答电脑说出的暗语,答对解锁,有3次机会。如果他们没有回答正确,他们会给我发一封电子邮件,通知我有人在触摸我的电脑并上传此人的头像。进程环境是win10代码,我用的是python3,所以启动前需要安装一些依赖包,请按顺序安装,否则会报错pipinstallcmake-ihttps://pypi.tuna.tsinghua.edu.cn/simplepipinstallldlib-ihttps://pypi.tuna.tsinghua.edu.cn/simplepipinstallface_recognition-ihttps://pypi.tuna.tsinghua.edu.cn/simplepipinstallface_python-ihttps://pypi.tuna.tsinghua.edu.cn/simple下步骤是建立识别人脸和比较人脸的代码importface_recognitionimportcv2importnumpyasnpvideo_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]]face_names=[]face_locations=[]face_encodings=[]process_this_frame=TruewhileTrue:ret,frame=video_capture.read()small_frame=cv2.resize(frame,(0,0),fx=0.25,fy=0.25)rgb_small_frame=small_frame[:,:,::-1]ifprocess_this_frame:face_locations=face_recognition.face_locations(rgb_small_frame)face_encodings=face_recognition.face_encodings(rgb_small_frame,face_locations)face_names=[]forface_encodinginface_encodings:matches=face_recognition.compare_faces(known_face_encodings,face_encoding)name="未知"face_distances=face_recognition.face_distance(known_face_encodings,face_encoding)best_match_index=np.argmin(face_distances)ifmatches[best_match_index]:name=known_face_names[best]_match_indexface_names.append(name)process_this_frame=notprocess_this_framefor(top,right,bottom,left),nameinzip(face_locations,face_names):top*=4left*=4right*=4bottom*=4font=cv2.FONT_HERSHEY_DUPLEXcv2.rectangle(frame,(左,上),(右,下),(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)ifcv2.waitKey(1)&0xFF==ord('q'):breakvideo_capture.release()cv2.destroyAllWindows()其中my.jpg需要自己拍摄上传。当你运行它的时候,你会发现你的脸上会有一个管理框。我去网上找了一张类似这样的图片。识别功能已经完成下一步是语音识别和语音合成,需要使用百度AI来实现。进入百度AI官网,进入控制台选择左侧的语音技术,然后点击面板上的创建应用按钮,进入创建应用界面打造电脑版人脸屏幕解锁神器。创建完成后会得到AppID、APIKey、SecretKey记下来,然后开始编写语音合成的代码。安装百度AI提供的依赖包pipinstallbaidu-aip-ihttps://pypi.tuna.tsinghua。edu.cn/simplepipinstallplaysound-ihttps://pypi.tuna.tsinghua.edu.cn/simple然后就是一个简单的语音播放代码,运行下面的代码就可以听到萌妹子的声音importsysfromaipimportAipSpeechfromplaysoundimportplaysoundAPP_ID=''API_KEY=''SECRET_KEY=''client=AipSpeech(APP_ID,API_KEY,SECRET_KEY)result=client.synthesis('Hello','zh',1,{'vol':5,'per':4,'spd':5,})ifnotisinstance(result,dict):withopen('auido.mp3','wb')asfile:file.write(result)filepath=eval(repr(sys.path[0]).replace('\\','/'))+'//auido.mp3'playsound(filepath)有了上面的代码就完成了检测是否在电脑前(人脸识别)电脑读取代码(语音合成)然后我们需要向计算机回答代码,因此需要完成语音识别。importwaveimportpyaudiofromaipimportAipSpeechAPP_ID=''API_KEY=''SECRET_KEY=''client=AipSpeech(APP_ID,API_KEY,SECRET_KEY)CHUNK=1024FORMAT=pyaudio.paInt16CHANNELS=1RATE=8000RECORD_SECONDS=3WAVE_OUTPUT_FILENAME="output.wav."p=Apyudio.=Pyudiop.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)print("*recording")frames=[]foriinrange(0,int(RATE/CHUNK*RECORD_SECONDS)):数据=stream.read(CHUNK)frames.append(data)print("*donerecording")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))defget_file_content():withopen(WAVE_OUTPUT_FILENAME,'rb')asfp:returnfp.read()result=client.asr(get_file_content(),'wav',8000,{'dev_pid':1537,})print(result)运行这段代码前需要安装pyaudio依赖包,因为在win10系统上安装会报错可以安装为f奥尔洛斯。到这个链接https://www.lfd.uci.edu/~gohlke/pythonlibs/#pyaudio下载对应的安装包并安装。建完电脑版的人脸屏幕解锁神器,打了个招呼,可以看到已经被识别了。那么我们的小模块功能就都准备好了,接下来就是如何集成了。可以发现人脸识别代码中的ifmatches[best_match_index]判断代码是判断是不是电脑的主人,所以我们把这个判断语句作为main函数的入口。ifmatches[best_match_index]:#这里写识别后的函数。name=known_face_names[best_match_index]那么识别之后要让电脑发出查询代码,也就是语音合成代码。然后我们把它封装成一个函数,顺便重构一下人脸识别的代码。importcv2importtimeimportnumpyasnpimportface_recognitionvideo_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=Truedefspeak(内容):importsysfromaipimportAipSpeechfromplaysoundimportplaysoundAPP_ID=''API_KEY=''SECRET_KEY=''client=AipSpeech(APP_ID,API_KEY,SECRET_KEY)result=client.synthesis(内容,'zh',1,{'vol':5,'per':0,'spd':5,})ifnotisinstance(result,dict):withopen('auido.mp3','wb')asfile:file.write(result)filepath=eval(repr(sys.path[0]).replace('\\','/'))+'//auido.mp3'playsound(文件路径)try:whileTrue:ret,frame=video_capture.read()small_frame=cv2.resize(frame,(0,0),fx=0.25,fy=0.25)rgb_small_frame=small_frame[:,:,::-1]ifprocess_this_frame:face_locations=face_recognition.face_locations(rgb_small_frame)face_encodings=face_recognition.face_encodings(rgb_small_frame,face_locations)face_names=[]forface_encodinginface_encodings:matches=face_recognition.compare_faces(known_face_encodings,face_encoding)name="未知"face_distances=face_recognition.face_distance(known_face_encodings,face_encoding)best_match_index=np.arg)min(face_distances)[best_match_index]:speak("识别到人脸,开始询问暗号,请回答下面我说的问题")time.sleep(1)speak("天王盖地虎")error=1/0name=known_face_names[best_match_index]face_names.append(name)process_this_frame=notprocess_this_framefor(top,right,bottom,left),nameinzip(face_locations,face_names):top*=4left*=4right*=4bottom*=4font=cv2.FONT_HERSHEY_DUPLEXcv2.rectangle(frame,(左,上),(右,下),(0,0,255),2)cv2.rectangle(框架,(左,下-35),(右,下),(0,0,255),cv2.FILLED)cv2.putText(frame,name,(left+6,bottom-6),font,1.0,(255,255,255),1)cv2.imshow('Video',frame)ifcv2.waitKey(1)&0xFF==ord('q'):breakexceptionase:print(e)finally:video_capture.release()cv2.destroyAllWindows()这里有一点需要注意。由于playsound在播放音乐的时候会一直占用这个资源,所以在播放下一首音乐的时候会报错。解决方法是修改~在\Python37\Lib\site-packages下的playsound.py文件中,找到如下代码制作电脑版人脸屏幕解锁神器。在sleep函数下添加代码winCommand('close',alias),保存运行,发现两个句子都可以正常说了。然后说完了还要听,还要封装一个功能。defrecord():importwaveimportjsonimportpyaudiofromaipimportAipSpeechAPP_ID=''API_KEY=''SECRET_KEY=''client=AipSpeech(APP_ID,API_KEY,SECRET_KEY)CHUNK=1024FORMAT=pyaudio.paInt16CHANNELS=1RATE=8000RECORD_SECONDS=3WAVE_OUTPUT_FILENAME"p="输出()stream=p.open(format=FORMAT,channels=CHANNELS,rate=RATE,input=True,frames_per_buffer=CHUNK)print("*recording")frames=[]foriinrange(0,int(RATE/CHUNK*RECORD_SECONDS)):data=stream.read(CHUNK)frames.append(data)print("*donerecording")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))defget_file_content():withopen(WAVE_OUTPUT_FILENAME,'rb')asfp:returnfp.read()result=client.asr(get_file_content(),'wav',8000,{'dev_pid':1537,})result=json.loads(str(result).replace("'",'"'))returnresult["结果"][0]修改人脸识别后的代码为如下ifmatches[best_match_index]:speak("识别人脸,开始求密码,请回答下一个我要说的问题")时间。sleep(1)speak("盖地虎天王")flag=Falsefortimesinrange(0,3):content=record()if"鸡炖蘑菇"incontent:speak("密码通过")flag=Truebreakelse:speak("密码未通过passed,Tryagain")ifflag:print("Unlock")else:print("发送邮件,上传坏人头像!")error=1/0name=known_face_names[best_match_index]运行看看效果,电脑答鸡炖蘑菇,电脑答密码,功能基本通过这个完成。打造电脑版人脸屏幕解锁神器结语至于发送邮件功能和锁屏解锁功能就不一一实现了。我认为这对在座的每个人来说都不是问题。锁屏功能可以HOOK让键盘时间失效,然后用窗口覆盖整个桌面。至于发邮件,网上有很多文章。