基于face_recognition摄像头人脸识别并打包exe

发布时间:2022-06-29 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了基于face_recognition摄像头人脸识别并打包exe脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

使用pyinstaller在Terminal中使用命令 pyinstaller -F (单文件打包、-D打包成debug把所有引用包一起打包)-w(运行不显示cmd命令窗口) file.py

外部调用资打包进程序的方法:

代码

基于face_recognition摄像头人脸识别并打包exe

基于face_recognition摄像头人脸识别并打包exe

import win32serviceutil
import win32service
import win32event
import win32timezone
From watchdog.observers import Observer
from watchdog.events import *
import time
import face_recognITion
import SQLMethod
from SQLDBHelPEr import MSSQL
import _thread
import json
import @R_999_2406@rror
import servicemanager
import os, Sys, time

def get_img_file(file_name):
    imagelist = []
    if file_name.lower().endswith(('.jpg', '.jpeg', '.png')):
        if file_name.find('FACE_SNAP') > 0:
            # PRint(parent)
            # print(filename)
            imagelist.append(file_name)
    return imagelist
def dect_img(knowid, knowname, known_face_encodings, imgpath):
    dectids = []
    face_names = []  # 识别出来的图像中人脸的标记名
    face_locat = []  # 识别出来的人脸图像位置

    if known_face_encodings:
        frame = face_recognition.load_image_file(imgpath)
        face_locations = face_recognition.face_locations(frame)
        mface_encodings = face_recognition.face_encodings(frame)
        if face_locations == []:
            print('图像未获取到人脸')
            return dectids, face_names, face_locat
        if mface_encodings:
            for _index, face_encoding in enumerate(mface_encodings):
                # 已知图像编码和测试人脸图像编码比对获取true/false集合:[true,false,false,false]
                results = face_recognition.COMpare_faces(known_face_encodings, face_encoding, tolerance=0.4)
                print(results)
                if True in results:
                    dectid = knowid[results.index(True)]
                    name = knowname[results.index(True)]
                    dectids.append(dectid)
                    face_names.append(name)
                    face_locat.append(face_locations[_index])
            return dectids, face_names, face_locat
        else:
            return dectids, face_names, face_locat
def insertsql_dectimg(imgpaths):
    if len(imgpaths) > 0:
        ms = MSSQL(host="localhost", user="sa", pwd="wqy", db="Imgdetect", charset="utf8")
        for imgpath in imgpaths:
            knowid, knowname, known_face_encodings = SqlMethod.GetKnowImgEncode_ID()
            dectids, face_names, face_locat = dect_img(knowid, knowname, known_face_encodings, imgpath)
            if face_names:
                for (top, right, bottom, left), name, dectid in zip(face_locat, face_names, dectids):
                    print(dectid)
                    print(name)
                    if dectid:
                        a1 = """insert into EmpCrossFace values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
                        res = ms.ExecNonQuery(a1,
                                              (dectid, name,
                                               time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()),
                                               imgpath, top,
                                               right, bottom, left, 1, False))
            else:
                a1 = """insert into EmpCrossFace values(%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
                res = ms.ExecNonQuery(a1,
                                      ('', '未知',
                                       time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()), imgpath, 0,
                                       0, 0,
                                       0, 0, False))
        return res
def theard_method(src_path):
    watch_files = get_img_file(src_path)
    if len(watch_files) > 0:
        insertsql_dectimg(watch_files)
    print("文件被创建了 %s" % src_path)

class MyHandler(FileSystemEventHandler):
    def __init__(self):
        if getattr(sys, 'frozen', False):
            pathname = sys._MeiPASS
        else:
            pathname = os.path.split(os.path.realpath(__FILE__))[0]
        with open(pathname+ '/res/config.js', 'r') as f:
            j = json.load(f)
            self.file_path = j["config"][0]["file_path"]
    def on_modified(self, event):
        print("文件被修改了 %s" % event.src_path)

    def on_created(self, event):
        # start_new_thread启动线程
        # 参数一:调用的方法名 参数二:元组传递调用的方法要使用的参数
        _thread.start_new_thread(theard_method,(event.src_path,))
class PythonService(win32serviceutil.ServiceFramework):
    _svc_name_ = "DectFacePythonService"                    #服务名
    _svc_display_name_ = "人脸识别Face_Recognition"                 #job在windows services上显示的名字
    _svc_description_ = "人脸识别Face_Recognition"        #job的描述

    def __init__(self, args):
        win32serviceutil.ServiceFramework.__init__(self, args)
        self.hWaitStop = win32event.CreateEvent(None, 0, 0, None)
        # self.file_path = "C:/Users/wqy/Desktop/companyfaceimage"
        # f = open(os.path.join(os.path.abspath('.'))+'/config.js')
        # j = json.load(f)
        # self.file_path =j["config"][0]["file_path"]
    def SvcDoRun(self):
        # 启动方法
        event_handler = MyHandler()
        observer = Observer()
        observer.schedule(event_handler, event_handler.file_path, recursive=True)
        observer.start()
        observer.join()
        win32event.WaitForSingleObject(self.hWaitStop, win32event.INFINITE)

    def SvcStop(self):
        self.ReportServicestatus(win32service.SERVICE_STOP_PENDING)
        win32event.SetEvent(self.hWaitStop)


if __name__ == '__main__':
    if len(sys.argv) == 1:
        try:
            evtsrc_dll = os.path.abspath(servicemanager.__file__)
            servicemanager.PrepareToHostSingle(PythonService)
            servicemanager.Initialize('PythonService', evtsrc_dll)
            servicemanager.StartServiceCtrlDispatcher()
        except win32service.error as details:
            if details == winerror.ERROR_FAILED_SERVICE_CONTROLLER_CONNECT:
                win32serviceutil.usage()
    else:
        win32serviceutil.HandleCommandLine(PythonService)
View Code

代码中调用了face_recognition打包用到了face_recognition_models的一些文件,face_recognition_models在Python36的lib的安装包中可以找到。直接拷贝放到项目中。

pyinstaller -F DectFacePythonServer.py打包完成后 删除生成的build和dist文件,更改生成的DectFacePythonServer.spec文件

# -*- mode: python ; coding: utf-8 -*-


block_cipher = None#项目中引用的包需要的运行文件
face_models = [#list嵌套tuple元组(文件的具体地址指向到根目录,打包后存放资源的文件夹)
('.\face_recognition_models\models\dlib_face_recognition_resnet_model_v1.dat', './face_recognition_models/models'),
('.\face_recognition_models\models\mmod_human_face_detector.dat', './face_recognition_models/models'),
('.\face_recognition_models\models\Shape_predictor_5_face_landmarks.dat', './face_recognition_models/models'),
('.\face_recognition_models\models\shape_predictor_68_face_landmarks.dat', './face_recognition_models/models'),
]  #项目中使用的资源配置等文件
face_dataset=[
('.\res\config.js','./res'),
('.\res\config.ini','./res')
]  
a = Analysis(['DectFacePythonServer.py'],
             pathex=['C:\Users\wqy\Desktop\flaskProject'],
             binaries=face_models,
             datas=face_dataset,
             hiddenimports=[],
             hookspath=[],
             hooksconfig={},
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_asSEMblies=False,
             cipher=block_cipher,
             noarchive=False)
pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)

exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,  
          [],
          name='DectFacePythonServer',
          debug=False,
          bootloader_ignore_signals=False,
          strip=False,
          upx=True,
          upx_exclude=[],
          runtime_tmpdir=None,
          console=False,
          disable_windowed_traceback=False,
          target_Arch=None,
          codesign_identity=None,
          entitlements_file=None )

Terminal命令pyinstaller DectFacePythonServer.spec

脚本宝典总结

以上是脚本宝典为你收集整理的基于face_recognition摄像头人脸识别并打包exe全部内容,希望文章能够帮你解决基于face_recognition摄像头人脸识别并打包exe所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。