脚本之家,脚本语言编程技术及教程分享平台!
分类导航

Python|VBS|Ruby|Lua|perl|VBA|Golang|PowerShell|Erlang|autoit|Dos|bat|

服务器之家 - 脚本之家 - Python - python实现的人脸识别打卡系统

python实现的人脸识别打卡系统

2021-10-26 09:43king-xw Python

这篇文章主要介绍了python实现的人脸识别打卡系统,帮助大家更好的理解和学习使用python,感兴趣的朋友可以了解下

项目地址:

https://github.com/king-xw/face_recogntion

简介

本仓库是使用python编写的一个简单的人脸识别考勤打卡系统

主要功能有录入人脸信息、人脸识别打卡、设置上下班时间、导出打卡日志等

下面是各模块截图

首页

python实现的人脸识别打卡系统

录入人脸信息

python实现的人脸识别打卡系统

人脸识别打卡

python实现的人脸识别打卡系统

输出日志

python实现的人脸识别打卡系统

使用

直接运行**==workattendancesystem==**.py即可

主要代码

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
import datetime
import time
import win32api
import win32con
import wx
import wx.grid
import sqlite3
from time import localtime, strftime
import os
from skimage import io as iio
import io
import zlib
import dlib  # 人脸识别的库dlib
import numpy as np  # 数据处理的库numpy
import cv2  # 图像处理的库opencv
import _thread
import threading
import win32com.client
import tkinter as tk
from tkinter import filedialog
import csv
 
spk = win32com.client.dispatch("sapi.spvoice")
 
id_new_register = 160
id_finish_register = 161
 
id_start_punchcard = 190
id_end_puncard = 191
 
id_today_logcat = 283
id_custom_logcat = 284
 
id_working_hours = 301
id_offwork_hours = 302
id_delete = 303
 
id_worker_unaviable = -1
 
path_face = "data/face_img_database/"
# face recognition model, the object maps human faces into 128d vectors
facerec = dlib.face_recognition_model_v1("model/dlib_face_recognition_resnet_model_v1.dat")
# dlib 预测器
detector = dlib.get_frontal_face_detector()
predictor = dlib.shape_predictor('model/shape_predictor_68_face_landmarks.dat')
 
 
def speak_info(info):
    spk.speak(info)
 
 
def return_euclidean_distance(feature_1, feature_2):
    feature_1 = np.array(feature_1)
    feature_2 = np.array(feature_2)
    dist = np.sqrt(np.sum(np.square(feature_1 - feature_2)))
    print("欧式距离: ", dist)
    if dist > 0.4:
        return "diff"
    else:
        return "same"
 
 
class was(wx.frame):
    def __init__(self):
        wx.frame.__init__(self, parent=none, title="智能监控打卡系统", size=(920, 560))
 
        self.folderpath = none
        self.initmenu()
        self.initinfotext()
        self.initgallery()
        self.initdatabase()
        self.initdata()
 
    def initdata(self):
        self.name = ""
        self.id = id_worker_unaviable
        self.face_feature = ""
        self.pic_num = 0
        self.flag_registed = false
        self.loaddatabase(1)
 
    def initmenu(self):
 
        menubar = wx.menubar()  # 生成菜单栏
        menu_font = wx.font()  # font(facename="consolas",pointsize=20)
        menu_font.setpointsize(14)
        menu_font.setweight(wx.bold)
 
        registermenu = wx.menu()  # 生成菜单
        self.new_register = wx.menuitem(registermenu, id_new_register, "新建录入")
        self.new_register.setbitmap(wx.bitmap("drawable/new_register.png"))
        self.new_register.settextcolour("slate black")
        self.new_register.setfont(menu_font)
        registermenu.append(self.new_register)
 
        self.finish_register = wx.menuitem(registermenu, id_finish_register, "完成录入")
        self.finish_register.setbitmap(wx.bitmap("drawable/finish_register.png"))
        self.finish_register.settextcolour("slate black")
        self.finish_register.setfont(menu_font)
        self.finish_register.enable(false)
        registermenu.append(self.finish_register)
 
        puncardmenu = wx.menu()
        self.start_punchcard = wx.menuitem(puncardmenu, id_start_punchcard, "开始签到")
        self.start_punchcard.setbitmap(wx.bitmap("drawable/start_punchcard.png"))
        self.start_punchcard.settextcolour("slate black")
        self.start_punchcard.setfont(menu_font)
        puncardmenu.append(self.start_punchcard)
 
        self.end_puncard = wx.menuitem(puncardmenu, id_end_puncard, "结束签到")
        self.end_puncard.setbitmap(wx.bitmap("drawable/end_puncard.png"))
        self.end_puncard.settextcolour("slate black")
        self.end_puncard.setfont(menu_font)
        self.end_puncard.enable(false)
        puncardmenu.append(self.end_puncard)
 
        logcatmenu = wx.menu()
        self.today_logcat = wx.menuitem(logcatmenu, id_today_logcat, "输出今日日志")
        self.today_logcat.setbitmap(wx.bitmap("drawable/open_logcat.png"))
        self.today_logcat.setfont(menu_font)
        self.today_logcat.settextcolour("slate black")
        logcatmenu.append(self.today_logcat)
 
        self.custom_logcat = wx.menuitem(logcatmenu, id_custom_logcat, "输出自定义日志")
        self.custom_logcat.setbitmap(wx.bitmap("drawable/open_logcat.png"))
        self.custom_logcat.setfont(menu_font)
        self.custom_logcat.settextcolour("slate black")
        logcatmenu.append(self.custom_logcat)
 
        setmenu = wx.menu()
        self.working_hours = wx.menuitem(setmenu, id_working_hours, "上班时间")
        self.working_hours.setbitmap(wx.bitmap("drawable/close_logcat.png"))
        self.working_hours.setfont(menu_font)
        self.working_hours.settextcolour("slate black")
        setmenu.append(self.working_hours)
 
        self.offwork_hours = wx.menuitem(setmenu, id_offwork_hours, "下班时间")
        self.offwork_hours.setbitmap(wx.bitmap("drawable/open_logcat.png"))
        self.offwork_hours.setfont(menu_font)
        self.offwork_hours.settextcolour("slate black")
        setmenu.append(self.offwork_hours)
 
        self.delete = wx.menuitem(setmenu, id_delete, "删除人员")
        self.delete.setbitmap(wx.bitmap("drawable/end_puncard.png"))
        self.delete.setfont(menu_font)
        self.delete.settextcolour("slate black")
        setmenu.append(self.delete)
 
        menubar.append(registermenu, "&人脸录入")
        menubar.append(puncardmenu, "&刷脸签到")
        menubar.append(logcatmenu, "&考勤日志")
        menubar.append(setmenu, "&设置")
 
        self.setmenubar(menubar)
 
        self.bind(wx.evt_menu, self.onnewregisterclicked, id=id_new_register)
        self.bind(wx.evt_menu, self.onfinishregisterclicked, id=id_finish_register)
        self.bind(wx.evt_menu, self.onstartpunchcardclicked, id=id_start_punchcard)
        self.bind(wx.evt_menu, self.onendpunchcardclicked, id=id_end_puncard)
        self.bind(wx.evt_menu, self.exporttodaylog, id=id_today_logcat)
        self.bind(wx.evt_menu, self.exportcustomlog, id=id_custom_logcat)
        self.bind(wx.evt_menu, self.setworkinghours, id=id_working_hours)
        self.bind(wx.evt_menu, self.setoffworkhours, id=id_offwork_hours)
        self.bind(wx.evt_menu, self.deletebtn, id=id_delete)
 
    def setworkinghours(self, event):
        global working
        global setworkingsign
        setworkingsign = false
        self.loaddatabase(1)
        # self.working_hours.enable(true)
        self.working_hours = wx.gettextfromuser(message="请输入上班时间", caption="温馨提示", default_value="08:00:00",
                                                parent=none)
        working = self.working_hours
        setworkingsign = true
        pass
 
    def setoffworkhours(self, event):
        global offworking
        self.loaddatabase(1)
        # self.offwork_hours.enable(true)
        self.offwork_hours = wx.gettextfromuser(message="请输入下班时间", caption="温馨提示", default_value="18:00:00",
                                                parent=none)
        offworking = self.offwork_hours
        win32api.messagebox(0, "请确保同时设置上班时间和下班时间并且先设置上班时间", "提醒", win32con.mb_iconwarning)
        if setworkingsign:
            self.loaddatabase(4)
        else:
            win32api.messagebox(0, "您未设置上班时间", "提醒", win32con.mb_iconwarning)
        pass
 
    def exporttodaylog(self, event):
        global folderpath1
        folderpath1 = ""
        self.save_route1(event)
        if not folderpath1 == "":
            self.loaddatabase(3)
            day = time.strftime("%y-%m-%d")
            path = folderpath1 + "/" + day + ".csv"
            f = open(path, 'w', newline='', encoding='utf-8')
            csv_writer = csv.writer(f)
            csv_writer.writerow(["编号", "姓名", "打卡时间", "是否迟到"])
            size = len(logcat_id)
            index = 0
            while size - 1 >= index:
                localtime1 = str(logcat_datetime[index]).replace('[', '').replace(']', '')
                csv_writer.writerow([logcat_id[index], logcat_name[index], localtime1, logcat_late[index]])
                index += 1;
            f.close()
        pass
 
    def exportcustomlog(self, event):
        global dialog
        global t1
        global t2
        global folderpath2
        folderpath2 = ""
        dialog = wx.dialog(self)
        label1 = wx.statictext(dialog, -1, "输入员工id", pos=(30, 10))
        t1 = wx.textctrl(dialog, -1, '', pos=(130, 10), size=(130, -1))
        label2 = wx.statictext(dialog, -1, "输出日期(天)", pos=(30, 50))
        samplelist = [u'1', u'3', u'7', u'30']
        t2 = wx.combobox(dialog, -1, value="1", pos=(130, 50), size=(130, -1), choices=samplelist,
                         style=wx.cb_readonly)
        button = wx.button(dialog, -1, "选择文件保存路径", pos=(120, 90))
        button.bind(wx.evt_button, self.save_route2, button)
        btn_confirm = wx.button(dialog, 1, "确认", pos=(30, 150))
        btn_close = wx.button(dialog, 2, "取消", pos=(250, 150))
        btn_close.bind(wx.evt_button, self.onclose, btn_close)
        btn_confirm.bind(wx.evt_button, self.docustomlog, btn_confirm)
        dialog.showmodal()
        pass
 
    # 关闭主窗口前确认一下是否真的关闭
    def onclose(self, event):
        dlg = wx.messagedialog(none, u'确定要关闭本窗口吗?', u'操作提示', wx.yes_no)
        if dlg.showmodal() == wx.id_yes:
            dialog.destroy()
 
    def onclose1(self, event):
        dlg = wx.messagedialog(none, u'确定要关闭本窗口吗?', u'操作提示', wx.yes_no)
        if dlg.showmodal() == wx.id_yes:
            dialog1.destroy()
 
    def onyes(self, event):
        dlg = wx.messagedialog(none, u'确定要删除该编号的员工?', u'操作提示', wx.yes_no)
        if dlg.showmodal() == wx.id_yes:
            return true
 
    def deletebtn(self, event):
        global dialog1
        global t4
        dialog1 = wx.dialog(self)
        label1 = wx.statictext(dialog1, -1, "输入员工id: ", pos=(40, 34))
        t4 = wx.textctrl(dialog1, -1, '', pos=(130, 30), size=(130, -1))
        btn_confirm = wx.button(dialog1, 1, "确认", pos=(30, 150))
        btn_close = wx.button(dialog1, 2, "取消", pos=(250, 150))
        btn_close.bind(wx.evt_button, self.onclose1, btn_close)
        btn_confirm.bind(wx.evt_button, self.deletebyid, btn_confirm)
        dialog1.showmodal()
 
    def docustomlog(self, event):
        if not folderpath2 == "":
            number = t1.getvalue()
            days = t2.getvalue()
            flag = self.findbyid(number, days)
            print("查询的天数是:", days)
            if flag:
                row = len(find_id)
                path = folderpath2 + '/' + find_name[0] + '.csv'
                f = open(path, 'w', newline='', encoding='utf-8')
                csv_writer = csv.writer(f)
                csv_writer.writerow(["编号", "姓名", "打卡时间", "是否迟到"])
                for index in range(row):
                    s1 = str(find_datetime[index]).replace('[', '').replace(']', '')
                    csv_writer.writerow([str(find_id[index]), str(find_name[index]), s1, str(find_late[index])])
 
                f.close()
                success = wx.messagedialog(none, '日志保存成功,请注意查看', 'info', wx.ok)
                success.showmodal()
            else:
                warn = wx.messagedialog(none, '输入id不正确,请重新输入', 'info', wx.ok)
                warn.showmodal()
            dialog.destroy()
        else:
            win32api.messagebox(0, "请输入文件导出位置", "提醒", win32con.mb_iconwarning)
 
        pass
 
    def deletebyid(self, event):
        global delete_name
        delete_name = []
        id = t4.getvalue()
        print("删除员工的id为:", id)
        conn = sqlite3.connect("inspurer.db"# 建立数据库连接
        cur = conn.cursor()  # 得到游标对象
        sql = 'select name from worker_info where id=' + id
        sql1 = 'delete from worker_info where id=' + id
        sql2 = 'delete from logcat where id=' + id
        length = len(cur.execute(sql).fetchall())
        if length <= 0:
            win32api.messagebox(0, "没有查询到该员工,请重新输入id", "提醒", win32con.mb_iconwarning)
            return false
        else:
            origin = cur.execute(sql).fetchall()
            for row in origin:
                delete_name.append(row[0])
                name = delete_name[0]
                print("名字是", name)
            if self.onyes(event):
                cur.execute(sql1)
                cur.execute(sql2)
                conn.commit()
                dir = path_face + name
                for file in os.listdir(dir):
                    os.remove(dir + "/" + file)
                    print("已删除已录入人脸的图片", dir + "/" + file)
                os.rmdir(path_face + name)
                print("已删除已录入人脸的姓名文件夹", dir)
                dialog1.destroy()
                self.initdata()
                return true
 
    def findbyid(self, id, day):
        global find_id, find_name, find_datetime, find_late
        find_id = []
        find_name = []
        find_datetime = []
        find_late = []
        dayago = (datetime.datetime.now() - datetime.timedelta(days=int(day)))
        # 转换为其他字符串格式:
        day_before = dayago.strftime("%y-%m-%d")
        today = datetime.date.today()
        first = today.replace(day=1)
        last_month = first - datetime.timedelta(days=1)
        print(last_month.strftime("%y-%m"))
        print(last_month)
        conn = sqlite3.connect("inspurer.db"# 建立数据库连接
        cur = conn.cursor()  # 得到游标对象
        sql = 'select id ,name,datetime,late from logcat where id=' + id
 
        if day == '30':
            str = "'"
            sql1 = 'select id ,name,datetime,late from logcat where id=' + id + ' ' + 'and datetime like ' + str + '%' + last_month.strftime(
                "%y-%m") + '%' + str
        else:
            sql1 = 'select id ,name,datetime,late from logcat where id=' + id + ' ' + 'and datetime>=' + day_before
        length = len(cur.execute(sql).fetchall())
        if length <= 0:
            return false
        else:
            cur.execute(sql1)
            origin = cur.fetchall()
            for row in origin:
                find_id.append(row[0])
                find_name.append(row[1])
                find_datetime.append(row[2])
                find_late.append(row[3])
            return true
        pass
 
    def save_route1(self, event):
        global folderpath1
        root = tk.tk()
        root.withdraw()
        folderpath1 = filedialog.askdirectory()  # 获得选择好的文件夹
        pass
 
    def save_route2(self, event):
        global folderpath2
        root = tk.tk()
        root.withdraw()
        folderpath2 = filedialog.askdirectory()  # 获得选择好的文件夹
        pass
 
    def register_cap(self, event):
        # 创建 cv2 摄像头对象
        self.cap = cv2.videocapture(0)
        # cap.set(propid, value)
        # 设置视频参数,propid设置的视频参数,value设置的参数值
        # self.cap.set(3, 600)
        # self.cap.set(4,600)
        # cap是否初始化成功
        while self.cap.isopened():
            # cap.read()
            # 返回两个值:
            #    一个布尔值true/false,用来判断读取视频是否成功/是否到视频末尾
            #    图像对象,图像的三维矩阵
            flag, im_rd = self.cap.read()
 
            # 每帧数据延时1ms,延时为0读取的是静态帧
            kk = cv2.waitkey(1)
            # 人脸数 dets
            dets = detector(im_rd, 1)
 
            # 检测到人脸
            if len(dets) != 0:
                biggest_face = dets[0]
                # 取占比最大的脸
                maxarea = 0
                for det in dets:
                    w = det.right() - det.left()
                    h = det.top() - det.bottom()
                    if w * h > maxarea:
                        biggest_face = det
                        maxarea = w * h
                        # 绘制矩形框
 
                cv2.rectangle(im_rd, tuple([biggest_face.left(), biggest_face.top()]),
                              tuple([biggest_face.right(), biggest_face.bottom()]),
                              (255, 0, 0), 2)
                img_height, img_width = im_rd.shape[:2]
                image1 = cv2.cvtcolor(im_rd, cv2.color_bgr2rgb)
                pic = wx.bitmap.frombuffer(img_width, img_height, image1)
                # 显示图片在panel上
                self.bmp.setbitmap(pic)
 
                # 获取当前捕获到的图像的所有人脸的特征,存储到 features_cap_arr
                shape = predictor(im_rd, biggest_face)
                features_cap = facerec.compute_face_descriptor(im_rd, shape)
 
                # 对于某张人脸,遍历所有存储的人脸特征
                for i, knew_face_feature in enumerate(self.knew_face_feature):
                    # 将某张人脸与存储的所有人脸数据进行比对
                    compare = return_euclidean_distance(features_cap, knew_face_feature)
                    if compare == "same":  # 找到了相似脸
                        self.infotext.appendtext(self.getdateandtime() + "工号:" + str(self.knew_id[i])
                                                 + " 姓名:" + self.knew_name[i] + " 的人脸数据已存在\r\n")
                        self.flag_registed = true
                        self.onfinishregister()
                        _thread.exit()
 
                face_height = biggest_face.bottom() - biggest_face.top()
                face_width = biggest_face.right() - biggest_face.left()
                im_blank = np.zeros((face_height, face_width, 3), np.uint8)
                try:
                    for ii in range(face_height):
                        for jj in range(face_width):
                            im_blank[ii][jj] = im_rd[biggest_face.top() + ii][biggest_face.left() + jj]
                    if len(self.name) > 0:
                        cv2.imencode('.jpg', im_blank)[1].tofile(
                            path_face + self.name + "/img_face_" + str(self.pic_num) + ".jpg")  # 正确方法
                        self.pic_num += 1
                        print("写入本地:", str(path_face + self.name) + "/img_face_" + str(self.pic_num) + ".jpg")
                        self.infotext.appendtext(
                            self.getdateandtime() + "图片:" + str(path_face + self.name) + "/img_face_" + str(
                                self.pic_num) + ".jpg保存成功\r\n")
                except:
                    print("保存照片异常,请对准摄像头")
 
                if self.new_register.isenabled():
                    _thread.exit()
                if self.pic_num == 30:
                    self.onfinishregister()
                    _thread.exit()
 
    def onnewregisterclicked(self, event):
        self.new_register.enable(false)
        self.finish_register.enable(true)
        self.loaddatabase(1)
        while self.id == id_worker_unaviable:
            self.id = wx.getnumberfromuser(message="请输入您的工号(-1不可用)",
                                           prompt="工号", caption="温馨提示",
                                           value=id_worker_unaviable,
                                           parent=self.bmp, max=100000000, min=id_worker_unaviable)
            for knew_id in self.knew_id:
                if knew_id == self.id:
                    self.id = id_worker_unaviable
                    wx.messagebox(message="工号已存在,请重新输入", caption="警告")
 
        while self.name == '':
            self.name = wx.gettextfromuser(message="请输入您的的姓名,用于创建姓名文件夹",
                                           caption="温馨提示",
                                           default_value="", parent=self.bmp)
 
            # 监测是否重名
            for exsit_name in (os.listdir(path_face)):
                if self.name == exsit_name:
                    wx.messagebox(message="姓名文件夹已存在,请重新输入", caption="警告")
                    self.name = ''
                    break
        os.makedirs(path_face + self.name)
        _thread.start_new_thread(self.register_cap, (event,))
        pass
 
    def onfinishregister(self):
 
        self.new_register.enable(true)
        self.finish_register.enable(false)
        self.cap.release()
 
        self.bmp.setbitmap(wx.bitmap(self.pic_index))
        if self.flag_registed == true:
            dir = path_face + self.name
            for file in os.listdir(dir):
                os.remove(dir + "/" + file)
                print("已删除已录入人脸的图片", dir + "/" + file)
            os.rmdir(path_face + self.name)
            print("已删除已录入人脸的姓名文件夹", dir)
            self.initdata()
            return
        if self.pic_num > 0:
            pics = os.listdir(path_face + self.name)
            feature_list = []
            feature_average = []
            for i in range(len(pics)):
                pic_path = path_face + self.name + "/" + pics[i]
                print("正在读的人脸图像:", pic_path)
                img = iio.imread(pic_path)
                img_gray = cv2.cvtcolor(img, cv2.color_bgr2rgb)
                dets = detector(img_gray, 1)
                if len(dets) != 0:
                    shape = predictor(img_gray, dets[0])
                    face_descriptor = facerec.compute_face_descriptor(img_gray, shape)
                    feature_list.append(face_descriptor)
                else:
                    face_descriptor = 0
                    print("未在照片中识别到人脸")
            if len(feature_list) > 0:
                for j in range(128):
                    # 防止越界
                    feature_average.append(0)
                    for i in range(len(feature_list)):
                        feature_average[j] += feature_list[i][j]
                    feature_average[j] = (feature_average[j]) / len(feature_list)
                self.insertarow([self.id, self.name, feature_average], 1)
                self.infotext.appendtext(self.getdateandtime() + "工号:" + str(self.id)
                                         + " 姓名:" + self.name + " 的人脸数据已成功存入\r\n")
            pass
 
        else:
            os.rmdir(path_face + self.name)
            print("已删除空文件夹", path_face + self.name)
        self.initdata()
 
    def onfinishregisterclicked(self, event):
        self.onfinishregister()
        pass
 
    def punchcard_cap(self, event):
 
        # 调用设置上班时间的函数,根据当前时间和上班时间判断是否迟到
 
        self.cap = cv2.videocapture(0)
        # cap.set(propid, value)
        # 设置视频参数,propid设置的视频参数,value设置的参数值
        # self.cap.set(3, 600)
        # self.cap.set(4,600)
        # cap是否初始化成功
        self.loaddatabase(5)
        print("长度是")
        print(len(working_times))
        if len(working_times) == 0:
            win32api.messagebox(0, "您未设置上班时间,请先设置上班时间后再设置下班时间", "提醒", win32con.mb_iconwarning)
            self.start_punchcard.enable(true)
            self.end_puncard.enable(false)
        else:
            working = working_times[0]
            print("-----------")
            print(working)
            offworking = offworking_times[0]
            print("-----------")
            print(offworking)
            while self.cap.isopened():
                # cap.read()
                # 返回两个值:
                #    一个布尔值true/false,用来判断读取视频是否成功/是否到视频末尾
                #    图像对象,图像的三维矩阵
                flag, im_rd = self.cap.read()
                # 每帧数据延时1ms,延时为0读取的是静态帧
                kk = cv2.waitkey(1)
                # 人脸数 dets
                dets = detector(im_rd, 1)
 
                # 检测到人脸
                if len(dets) != 0:
                    biggest_face = dets[0]
                    # 取占比最大的脸
                    maxarea = 0
                    for det in dets:
                        w = det.right() - det.left()
                        h = det.top() - det.bottom()
                        if w * h > maxarea:
                            biggest_face = det
                            maxarea = w * h
                            # 绘制矩形框
 
                    cv2.rectangle(im_rd, tuple([biggest_face.left(), biggest_face.top()]),
                                  tuple([biggest_face.right(), biggest_face.bottom()]),
                                  (255, 0, 255), 2)
                    img_height, img_width = im_rd.shape[:2]
                    image1 = cv2.cvtcolor(im_rd, cv2.color_bgr2rgb)
                    pic = wx.bitmap.frombuffer(img_width, img_height, image1)
                    # 显示图片在panel上
                    self.bmp.setbitmap(pic)
 
                    # 获取当前捕获到的图像的所有人脸的特征,存储到 features_cap_arr
                    shape = predictor(im_rd, biggest_face)
                    features_cap = facerec.compute_face_descriptor(im_rd, shape)
 
                    # 对于某张人脸,遍历所有存储的人脸特征
                    for i, knew_face_feature in enumerate(self.knew_face_feature):
                        # 将某张人脸与存储的所有人脸数据进行比对
                        compare = return_euclidean_distance(features_cap, knew_face_feature)
                        if compare == "same":  # 找到了相似脸
                            print("same")
                            flag = 0
                            nowdt = self.getdateandtime()
                            for j, logcat_name in enumerate(self.logcat_name):
                                if logcat_name == self.knew_name[i] and nowdt[0:nowdt.index(" ")] == \
                                        self.logcat_datetime[
                                            j][
                                        0:self.logcat_datetime[
                                            j].index(" ")]:
                                    self.infotext.appendtext(nowdt + "工号:" + str(self.knew_id[i])
                                                             + " 姓名:" + self.knew_name[i] + " 签到失败,重复签到\r\n")
                                    speak_info(self.knew_name[i] + " 签到失败,重复签到 ")
                                    flag = 1
                                    break
 
                            if flag == 1:
                                break
 
                            if nowdt[nowdt.index(" ") + 1:-1] <= working:
                                self.infotext.appendtext(nowdt + "工号:" + str(self.knew_id[i])
                                                         + " 姓名:" + self.knew_name[i] + " 成功签到,且未迟到\r\n")
                                speak_info(self.knew_name[i] + " 成功签到 ")
                                self.insertarow([self.knew_id[i], self.knew_name[i], nowdt, "否"], 2)
                            elif offworking >= nowdt[nowdt.index(" ") + 1:-1] >= working:
                                self.infotext.appendtext(nowdt + "工号:" + str(self.knew_id[i])
                                                         + " 姓名:" + self.knew_name[i] + " 成功签到,但迟到了\r\n")
                                speak_info(self.knew_name[i] + " 成功签到,但迟到了 ")
                                self.insertarow([self.knew_id[i], self.knew_name[i], nowdt, "是"], 2)
                            elif nowdt[nowdt.index(" ") + 1:-1] > offworking:
                                self.infotext.appendtext(nowdt + "工号:" + str(self.knew_id[i])
                                                         + " 姓名:" + self.knew_name[i] + " 签到失败,超过签到时间\r\n")
                                speak_info(self.knew_name[i] + " 签到失败,超过下班时间 ")
                            self.loaddatabase(2)
                            break
 
                    if self.start_punchcard.isenabled():
                        self.bmp.setbitmap(wx.bitmap(self.pic_index))
                        _thread.exit()
 
    def onstartpunchcardclicked(self, event):
        self.start_punchcard.enable(false)
        self.end_puncard.enable(true)
        self.loaddatabase(2)
        threading.thread(target=self.punchcard_cap, args=(event,)).start()
        pass
 
    def onendpunchcardclicked(self, event):
        self.start_punchcard.enable(true)
        self.end_puncard.enable(false)
        pass
 
    def initinfotext(self):
        # 少了这两句infotext背景颜色设置失败,莫名奇怪
        resulttext = wx.statictext(parent=self, pos=(10, 20), size=(90, 60))
        resulttext.setbackgroundcolour(wx.green)
        # resulttext.setbackgroundcolour((12,12,12))
        self.info = "\r\n" + self.getdateandtime() + "程序初始化成功\r\n"
        # 第二个参数水平混动条
        self.infotext = wx.textctrl(parent=self, size=(320, 500),
                                    style=(wx.te_multiline | wx.hscroll | wx.te_readonly))
        # 前景色,也就是字体颜色
        self.infotext.setforegroundcolour('black')
        self.infotext.setlabel(self.info)
        font = wx.font()
        font.setpointsize(12)
        font.setweight(wx.bold)
        font.setunderlined(true)
 
        self.infotext.setfont(font)
        self.infotext.setbackgroundcolour('white')
        pass
 
    def initgallery(self):
        self.pic_index = wx.image("drawable/index.png", wx.bitmap_type_any).scale(600, 500)
        self.bmp = wx.staticbitmap(parent=self, pos=(320, 0), bitmap=wx.bitmap(self.pic_index))
        pass
 
    def getdateandtime(self):
        dateandtime = strftime("%y-%m-%d %h:%m:%s", localtime())
        return "[" + dateandtime + "]"
 
    # 数据库部分
    # 初始化数据库
    def initdatabase(self):
        conn = sqlite3.connect("inspurer.db")  # 建立数据库连接
        cur = conn.cursor()  # 得到游标对象
        cur.execute('''create table if not exists worker_info
        (name text not null,
        id int not null primary key,
        face_feature array not null)''')
        cur.execute('''create table if not exists logcat
         (datetime text not null,
         id int not null,
         name text not null,
         late text not null)''')
        cur.execute('''create table if not exists time
         (id int
        constraint table_name_pk
            primary key,
         working_time time not null,
         offwork_time time not null)''')
        cur.close()
        conn.commit()
        conn.close()
 
    def adapt_array(self, arr):
        out = io.bytesio()
        np.save(out, arr)
        out.seek(0)
 
        dataa = out.read()
        # 压缩数据流
        return sqlite3.binary(zlib.compress(dataa, zlib.z_best_compression))
 
    def convert_array(self, text):
        out = io.bytesio(text)
        out.seek(0)
 
        dataa = out.read()
        # 解压缩数据流
        out = io.bytesio(zlib.decompress(dataa))
        return np.load(out)
 
    def insertarow(self, row, type):
        conn = sqlite3.connect("inspurer.db")  # 建立数据库连接
        cur = conn.cursor()  # 得到游标对象
        if type == 1:
            cur.execute("insert into worker_info (id,name,face_feature) values(?,?,?)",
                        (row[0], row[1], self.adapt_array(row[2])))
            print("写人脸数据成功")
        if type == 2:
            cur.execute("insert into logcat (id,name,datetime,late) values(?,?,?,?)",
                        (row[0], row[1], row[2], row[3]))
            print("写日志成功")
            pass
        cur.close()
        conn.commit()
        conn.close()
        pass
 
    def loaddatabase(self, type):
        nowday = self.getdateandtime()
        day = nowday[0:nowday.index(" ")]
        print(day)
        global logcat_id, logcat_name, logcat_datetime, logcat_late, working_times, offworking_times
        conn = sqlite3.connect("inspurer.db")  # 建立数据库连接
 
        cur = conn.cursor()  # 得到游标对象
 
        if type == 1:
            self.knew_id = []
            self.knew_name = []
            self.knew_face_feature = []
            cur.execute('select id,name,face_feature from worker_info')
            origin = cur.fetchall()
            for row in origin:
                print(row[0])
                self.knew_id.append(row[0])
                print(row[1])
                self.knew_name.append(row[1])
                print(self.convert_array(row[2]))
                self.knew_face_feature.append(self.convert_array(row[2]))
        if type == 2:
            self.logcat_id = []
            self.logcat_name = []
            self.logcat_datetime = []
            self.logcat_late = []
            cur.execute('select id,name,datetime,late from logcat')
            origin = cur.fetchall()
            for row in origin:
                print(row[0])
                self.logcat_id.append(row[0])
                print(row[1])
                self.logcat_name.append(row[1])
                print(row[2])
                self.logcat_datetime.append(row[2])
                print(row[3])
                self.logcat_late.append(row[3])
        if type == 3:
            logcat_id = []
            logcat_name = []
            logcat_datetime = []
            logcat_late = []
            s = "'"
            sql = 'select w.id,w.name,l.datetime,l.late from worker_info w left join logcat l  on  w.id=l.id and l.datetime like' + ' ' + s + day + '%' + s + ' ' + 'order by datetime desc'
            print(sql)
            cur.execute(sql)
            origin = cur.fetchall()
            for row in origin:
                print(row[0])
                logcat_id.append(row[0])
                print(row[1])
                logcat_name.append(row[1])
                print(row[2])
                logcat_datetime.append(row[2])
                print(row[3])
                logcat_late.append(row[3])
        if type == 4:
            sql = 'select working_time from time'
            cur.execute(sql)
            countresult = (cur.fetchall())
            print(countresult)
            str = "'"
            if not countresult:
                sql = 'insert into time (id,working_time,offworking_time) values (1,' + str + working + str + ',' + str + offworking + str + ')'
                cur.execute(sql)
                print(sql)
                conn.commit()
                print("插入时间成功")
            else:
                str="'"
                sql = 'update time set working_time=' + str + working + str + ',offworking_time=' + str + offworking + str + ' where id=1'
                cur.execute(sql)
                conn.commit()
                print(sql)
                print("更新时间成功")
 
        if type==5:
            sql = 'select working_time,offworking_time from time'
            cur.execute(sql)
            print(sql)
            origin = cur.fetchall()
            print(origin)
            working_times = []
            offworking_times = []
            for row in origin:
                print("这是数据库取出的上班时间")
                print(row[0])
                working_times.append(row[0])
                print("这是数据库取出的下班时间")
                print(row[1])
                offworking_times.append(row[1])
        cur.close()
        conn.commit()
        conn.close()
        pass
 
 
app = wx.app()
frame = was()
frame.show()
app.mainloop()

以上就是python实现的人脸识别打卡系统的详细内容,更多关于python 人脸识别打卡的资料请关注服务器之家其它相关文章!

原文链接:https://github.com/king-xw/Face_Recogntion

延伸 · 阅读

精彩推荐