-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathwindow.py
More file actions
287 lines (275 loc) · 12.5 KB
/
Copy pathwindow.py
File metadata and controls
287 lines (275 loc) · 12.5 KB
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
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
from PyQt5.QtWidgets import *
from windowQt import Ui_MainWindow
from Input import Ui_Dialog
import cv2 as cv
import xml.etree.ElementTree as ET
import shutil
import numpy as np
from PIL import Image
import time
import os
import _thread
recognizer = cv.face.LBPHFaceRecognizer_create()
face_cascade = cv.CascadeClassifier('facebook/haarcascade_frontalface_default.xml')
font = cv.FONT_HERSHEY_SIMPLEX
names = ['初始']
yourname = ''
def find_dic_name(yourname, window):
name_exist = False
m = 1
if os.path.exists('facebook/dictionary.xml'):
tree = ET.parse('facebook/dictionary.xml')
root = tree.getroot()
for face in root:
if face.attrib['name'] == yourname:
print(face.attrib['name'] + ':' + face.attrib['label'])
name_exist = True
break
m = len(root)
if not name_exist:
print(yourname + ':' + str(m + 1))
new_node = ET.Element('face', {'name': yourname, 'label': str(m + 1)})
root.append(new_node)
tree.write('facebook/dictionary.xml')
else:
root = ET.Element('facebook')
new_node = ET.SubElement(root, 'face', {'name': yourname, 'label': str(m)})
tree = ET.ElementTree(root)
tree.write('facebook/dictionary.xml', encoding='utf-8', xml_declaration=True)
_thread.start_new_thread(trainner, (window,))
def get_images_and_labels(path):
image_paths = []
for file in os.listdir(path):
image_paths.append(os.path.join(path, file))
for image_path in image_paths:
img = Image.open(image_path).convert('L')
img_np = np.array(img, 'uint8')
face = face_cascade.detectMultiScale(img_np)
for (x, y, w, h) in face:
face_sample = img_np[y:y + h, x:x + w]
the_name = os.path.split(image_path)[1].split('.')[0]
cv.imwrite('facebook/faces_data/face_sample_' + the_name + '.png',face_sample)
def trainner(window):
Photo_dirs = 'Pictures/Photo'
for Photo_dir in os.listdir(Photo_dirs):
get_images_and_labels(Photo_dirs + '/' + Photo_dir)
if os.path.exists('Pictures/Known/' + Photo_dir):
shutil.rmtree('Pictures/Known/' + Photo_dir)
shutil.copytree(Photo_dirs + '/' + Photo_dir, 'Pictures/Known/' + Photo_dir)
shutil.rmtree(Photo_dirs + '/' + Photo_dir)
ids = []
face_samples = []
the_names = []
for file in os.listdir('facebook/faces_data/'):
if not file.endswith('.png'):
continue
img = cv.imread('facebook/faces_data/' + file,cv.IMREAD_GRAYSCALE)
face_samples.append(img)
the_names.append(file.split('_')[2])
tree = ET.parse('facebook/dictionary.xml')
root = tree.getroot()
for the_name in the_names:
for face in root:
if the_name == face.attrib['name']:
ids.append(int(face.attrib['label']))
recognizer.train(face_samples, np.array(ids))
recognizer.save('facebook/trainner.xml')
recognizer.read('facebook/trainner.xml')
window.label_5.setText('人脸数据训练完成!!!')
if window.textBrowser.toPlainText().find(window.yourname) == -1:
window.textBrowser.append(window.yourname)
window.yourname = ''
window.pushButton.setEnabled(True)
window.pushButton_2.setEnabled(True)
window.pushButton_3.setEnabled(True)
window.pushButton_4.setEnabled(False)
window.pushButton_5.setEnabled(False)
def text_browser_add(window):
if os.path.exists('facebook/dictionary.xml'):
tree = ET.parse('facebook/dictionary.xml')
root = tree.getroot()
for face in root:
window.textBrowser.append(face.attrib['name'])
def create_dirs():
path = os.getcwd()
if not os.path.exists(path+'/Pictures'):
os.mkdir(path+'/Pictures')
os.mkdir(path+'/Pictures/Known')
os.mkdir(path+'/Pictures/Photo')
elif not os.path.exists(path+'/Pictures/Known'):
os.mkdir(path+'/Pictures/Known')
elif not os.path.exists(path+'/Pictures/Photo'):
os.mkdir(path+'/Pictures/Photo')
if not os.path.exists(path+'/facebook/faces_data'):
os.mkdir(path+'/facebook/faces_data')
class Input_Name(QDialog, Ui_Dialog):
def __init__(self):
super(Input_Name, self).__init__()
self.setupUi(self)
def Button1_Clicked(self):
have_hanzi = False
if self.lineEdit.text() != '':
global yourname
yourname = self.lineEdit.text()
for yourname_c in yourname:
if '\u4e00' <= yourname_c <= '\u9fa5':
have_hanzi = True
if have_hanzi:
QMessageBox.warning(self, '警告', '名字里请不要有汉字', QMessageBox.Yes | QMessageBox.No)
else:
self.close()
return yourname
else:
QMessageBox.warning(self, '警告', '请输入姓名', QMessageBox.Yes | QMessageBox.No)
def Button2_Clicked(self):
self.close()
class MyPyQT_Form(QMainWindow, Ui_MainWindow):
def __init__(self):
super(MyPyQT_Form, self).__init__()
self.timer_camera = QtCore.QTimer()
self.timer_camera2 = QtCore.QTimer()
self.camera = cv.VideoCapture(0)
self.begin_recognize = False
self.begin_take_photo = False
self.take_photo_success = False
self.path = ''
self.yourname = ''
self.num = 1
self.photo_num = 1 # 用做显示camera2
self.photos_num = 20 # 拍多少张照片
self.setupUi(self)
self.slot_ca()
def slot_ca(self):
_thread.start_new_thread(text_browser_add, (self, ))
create_dirs()
self.timer_camera.timeout.connect(self.show_camera)
self.timer_camera2.timeout.connect(self.show_camera2)
def show_camera(self):
success, img = self.camera.read()
if success:
show = cv.resize(img, (640, 480)) #把读到的帧的大小重新设置为 640x480
if self.begin_take_photo:
if self.radioButton.isChecked():
self.photos_num = 20
elif self.radioButton_2.isChecked():
self.photos_num = 50
else:
self.photos_num = 200
if self.num <= self.photos_num:
cv.imwrite(self.path + '/' + self.yourname + '_' + str(self.num) + '.jpg', show)
# os.system('Trainner_2.py') # 可以在这里直接训练数据,但是这会导致程序卡住几秒(卡住的这几秒是训练数据要的时间),这会导致程序不友好
# show = cv.cvtColor(show, cv.COLOR_BGR2RGB)
# showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
# self.label_4.setPixmap(QtGui.QPixmap.fromImage(showImage))
self.label_5.setText('是否以这张图片作为人脸识别的依据?')
self.pushButton.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.pushButton_3.setEnabled(False)
self.pushButton_4.setEnabled(True)
self.pushButton_5.setEnabled(True)
self.num += 1
else:
global yourname
self.num = 1
self.label_3.setText(yourname + '人脸录制完成!!!')
self.timer_camera2.start(10)
yourname = ''
self.begin_take_photo = False
if self.begin_recognize:
img_gray = cv.cvtColor(show, cv.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(img_gray, 1.1, 5)
for (x, y, w, h) in faces:
cv.rectangle(show, (x, y), (x+w, y+h), (0, 255, 0), 2)
idnum, confidence = recognizer.predict(img_gray[y: y+h, x: x+w])
if confidence<100:
idum = names[idnum]
confidence = "{0}%".format(round(100-confidence))
else:
idum = 'unknown'
confidence = "{0}%".format(round(100 - confidence))
cv.putText(show, str(idum), (x + 5, y - 5), font, 1, (0, 0, 255), 1)
cv.putText(show, str(confidence), (x + 5, y + h - 5), font, 1, (255, 0, 0), 1)
show = cv.cvtColor(show, cv.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
self.label_2.setPixmap(QtGui.QPixmap.fromImage(showImage))
def show_camera2(self):
if self.photo_num <= self.photos_num:
Photo_file_path = self.path + '/' + self.yourname + '_' + str(self.photo_num) + '.jpg'
img = cv.imread(Photo_file_path)
show = cv.cvtColor(img, cv.COLOR_BGR2RGB)
showImage = QtGui.QImage(show.data, show.shape[1], show.shape[0], QtGui.QImage.Format_RGB888)
self.label_4.setPixmap(QtGui.QPixmap.fromImage(showImage))
self.photo_num += 1
else:
self.photo_num = 1
def Button1_Clicked(self):
if self.pushButton.text() == '打开摄像头':
self.pushButton.setText('关闭摄像头')
self.timer_camera.start(10)
else:
self.label_2.setPixmap(QtGui.QPixmap(''))
self.timer_camera.stop()
self.pushButton.setText('打开摄像头')
def Button2_Clicked(self):
if self.pushButton_2.text() == '识别人脸':
if self.textBrowser.toPlainText() == '':
QMessageBox.warning(self, '警告', '数据库里还没有人脸数据,请先输入人脸!!!', QMessageBox.Yes | QMessageBox.No)
else:
self.label_6.setText('正在学习已有的人脸数据')
tree = ET.parse('facebook/dictionary.xml')
root = tree.getroot()
for face in root:
names.append(face.attrib['name'])
recognizer.read('facebook/trainner.xml')
self.label_6.setText('学习完成')
self.begin_recognize = True
self.pushButton_2.setText('停止识别')
else:
self.begin_recognize = False
self.pushButton_2.setText('识别人脸')
def Button3_Clicked(self):
if self.pushButton.text() == '打开摄像头':
QMessageBox.warning(self, '警告', '请先打开摄像头', QMessageBox.Yes | QMessageBox.No)
else:
self.begin_recognize = False
input_name = Input_Name()
input_name.exec_() # 这两行为调出输入姓名的窗口
global yourname
if yourname != '':
self.yourname = yourname # 得到录制的人的姓名
self.path = 'Pictures/Photo/' + self.yourname
if os.path.exists(self.path):
shutil.rmtree(self.path)
os.mkdir(self.path)
self.label_3.setText('请勿离开摄像头\n人脸录制中......')
self.begin_take_photo = True
def Button4_Clicked(self):
self.label_5.setText('正在训练'+self.yourname+'的人脸数据,请稍后...')
self.timer_camera2.stop()
self.label_4.setPixmap(QtGui.QPixmap(''))
self.pushButton.setEnabled(False)
self.pushButton_2.setEnabled(False)
self.pushButton_3.setEnabled(False)
self.pushButton_4.setEnabled(False)
self.pushButton_5.setEnabled(False)
if self.yourname != '':
_thread.start_new_thread(find_dic_name, (self.yourname, self, ))
def Button5_Clicked(self):
QMessageBox.warning(self, '警告', '你选择了取消!', QMessageBox.Yes | QMessageBox.No)
self.timer_camera2.stop()
self.label_4.setPixmap(QtGui.QPixmap(''))
shutil.rmtree('Pictures/Photo/' + self.yourname)
self.pushButton.setEnabled(True)
self.pushButton_2.setEnabled(True)
self.pushButton_3.setEnabled(True)
self.pushButton_4.setEnabled(False)
self.pushButton_5.setEnabled(False)
def Button6_Clicked(self):
QMessageBox.information(self, '帮助', '普通识别:拍20张照片作基准\n\n较精准识别:拍50张照片作基准\n\n精准识别:拍200张照片作基准', QMessageBox.Yes | QMessageBox.No)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
my_pyqt_form = MyPyQT_Form()
my_pyqt_form.show()
sys.exit(app.exec_())