直接上代码:
import cv2
from PyQt5 import QtWidgets
from PyQt5 import QtCore, QtGui, QtWidgets
from pythonUI import Ui_MainWindow # 导入python模块的Ui_MainWindow类,版本相同,这个类应该不变
import sys
from PyQt5.QtWidgets import (QWidget, QMessageBox, QLabel, QDialog, QGridLayout,QVBoxLayout,QHBoxLayout,
QApplication, QPushButton, QDesktopWidget, QLineEdit, QTabWidget)
from PyQt5.QtGui import QIcon, QPixmap, QImage, QPalette, QBrush
from PyQt5.QtCore import Qt, QTimer
from PyQt5 import QtCore
import requests
from json import JSONDecoder
import datetime
face_cascade = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
key = "MWJj5TVF1nP5EpPow9lYx7ulGufb5pCq" # 不能使用
secret = "j1y0hop8UHWUMPCvaKZg6XHvW6hsu9I-" # 不能使用,请注册自己的秘钥
detect_http_url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
def FaceSet_Create(): # 建立人脸识别库
url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create"
data = {"api_key": key, "api_secret": secret, } #
# post上传
response = requests.post(url, data=data)
req_con = response.content.decode('utf-8')
req_dict = JSONDecoder().decode(req_con)
print("faceset_token : ", req_dict["faceset_token"])
# test = response.json()
# print(test)
return req_dict["faceset_token"]
faceset_token = FaceSet_Create()
class MainWindow(QtWidgets.QMainWindow,Ui_MainWindow): # 组合继承
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent=parent)
self.setupUi(self)
self.pushButton_open.clicked.connect(self.start)
self.pushButton_close.clicked.connect(self.stop)
self.pushButton_take.clicked.connect(self.cap)
self.pushButton_1.clicked.connect(self.asd)
self.cap = None
self.timer = QTimer() # 定时器
# 闹钟--timeout信号(闹铃)
self.timer.timeout.connect(self.detectface)
def asd(self):
_translate = QtCore.QCoreApplication.translate
self.labe2_face.setText(_translate("MainWindow", "上传成功"))
ret, img = self.cap.read()
if ret != None:
cv2.imwrite("FPX.jpg", img)
FaceSet_AddFace(faceset_token, detect("FPX.jpg"))
def start(self, event):
# 打开摄像头
self.cap = cv2.VideoCapture(0)
# 启动定时器
self.timer.start()
# 间隔33毫秒--每次闹铃--调用 detectface进行人脸检测
self.timer.setInterval(33)
def stop(self):
# 关闭摄像头
self.cap.release()
# 关闭定时器
self.timer.stop()
def cap(self, event):
# 拍照,保存
ret, img = self.cap.read()
if ret != None:
cv2.imwrite("FPX.jpg", img)
i = Search("FPX.jpg", faceset_token)
if(i == 1):
_translate = QtCore.QCoreApplication.translate
self.labe2_face.setText(_translate("MainWindow", "是那个人"))
elif(i == 0):
_translate = QtCore.QCoreApplication.translate
self.labe2_face.setText(_translate("MainWindow", "不是那个人"))
else:
_translate = QtCore.QCoreApplication.translate
self.labe2_face.setText(_translate("MainWindow", "未知错误"))
def detectface(self):
if (self.cap.isOpened()):
# get a frame
ret, img = self.cap.read()
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
faces = face_cascade.detectMultiScale(gray, 1.3, 5)
for (x, y, w, h) in faces:
img = cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
roi_gray = gray[y:y + h, x:x + w]
roi_color = img[y:y + h, x:x + w]
self.face = cv2.resize(img[y:y + h, x:x + w], (224, 224), interpolation=cv2.INTER_CUBIC)
height, width, bytesPerComponent = img.shape
bytesPerLine = bytesPerComponent * width
# 变换彩色空间顺序
cv2.cvtColor(img, cv2.COLOR_BGR2RGB, img)
# 转为QImage对象是,在label中显示图像
self.image = QImage(img.data, width, height, bytesPerLine, QImage.Format_RGB888)
self.label_face.setPixmap(QPixmap.fromImage(self.image).scaled(self.label_face.width(), self.label_face.height()))
# 返回值{'confidence': 85.179, 'request_id': '1521508784,c368e44a-e430-4675-858a-f8ce3bb44d50', 'time_used': 547, 'thresholds': {'1e-3': 62.327, '1e-5': 73.975, '1e-4': 69.101}}
# def FaceSet_Create(): # 建立人脸识别库
# url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/create"
# data = {"api_key": key, "api_secret": secret, } #
# # post上传
# response = requests.post(url, data=data)
# req_con = response.content.decode('utf-8')
# req_dict = JSONDecoder().decode(req_con)
# print("faceset_token : ", req_dict["faceset_token"])
# # test = response.json()
# # print(test)
# return req_dict["faceset_token"]
def FaceSet_AddFace(faceset_token, face_tokens): #添加人脸到库中
url = "https://api-cn.faceplusplus.com/facepp/v3/faceset/addface"
#data = {"api_key": key, "api_secret": secret,"faceset_token": "d1f7e9956d85f0561cc414d49008a76c","face_tokens": "cd56c0f15a3d876219ec34d6e0217157",}
data = {"api_key": key, "api_secret": secret,"faceset_token": faceset_token,"face_tokens": face_tokens,}
response = requests.post(url, data=data)
test = response.json()
print(test)
def Search(filename, faceset_token): # 在库中搜索人脸数据
url = "https://api-cn.faceplusplus.com/facepp/v3/search"
data = {"api_key": key, "api_secret": secret, "faceset_token": faceset_token} # 多个返回值用“,”隔开
files = {"image_file": open(filename, "rb")}
response = requests.post(url, data=data, files=files)
req_con = response.content.decode('utf-8')
req_dict = JSONDecoder().decode(req_con)
print("识别成功!!!!")
print(req_dict)
print(req_dict["thresholds"]["1e-5"])
print(req_dict["results"][0]["confidence"])
if(req_dict["thresholds"]["1e-5"] <= req_dict["results"][0]["confidence"]):
return 1
else:
return 0
def detect(filename): #简单人脸识别
detect_http_url = "https://api-cn.faceplusplus.com/facepp/v3/detect"
data = {"api_key": key, "api_secret": secret, "return_attributes": "age,emotion", } # 多个返回值用“,”隔开
files = {"image_file": open(filename, "rb")}
response = requests.post(detect_http_url, data=data, files=files)
req_con = response.content.decode('utf-8')
req_dict = JSONDecoder().decode(req_con)
#{'image_id': '/VoijJOwZZJSeaXqMTBJfA==', 'request_id': '1526351577,0d960673-aa73-49aa-aa63-f20c7786eabb', 'time_used': 271, 'faces': [{'attributes': {'emotion': {'sadness': 0.147, 'neutral': 97.945, 'disgust': 0.025, 'anger': 0.657, 'surprise': 0.859, 'fear': 0.287, 'happiness': 0.081}, 'age': {'value': 39}}, 'face_rectangle': {'width': 220, 'top': 256, 'left': 295, 'height': 220}, 'face_token': '1d4a9a4620d211be446acb7def50bf05'}]}
print(req_dict)
faces = req_dict['faces']
faceNum = len(faces)
print("识别到了%d个人脸" % (faceNum))
# print(req_dict['faces'][-1])
return req_dict['faces'][-1]['face_token']
if __name__ == "__main__": # 开始运行
app = QtWidgets.QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
# IG.detect("FPX.jpg")
# IG.FaceSet_Create
UI界面代码:
from PyQt5 import QtCore, QtGui, QtWidgets class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.setWindowModality(QtCore.Qt.NonModal) MainWindow.resize(765, 645) MainWindow.setMinimumSize(QtCore.QSize(765, 645)) MainWindow.setMaximumSize(QtCore.QSize(16777215, 16777215)) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(":/newPrefix/pic/pai.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) MainWindow.setWindowIcon(icon) MainWindow.setToolTip("") MainWindow.setAutoFillBackground(False) MainWindow.setTabShape(QtWidgets.QTabWidget.Rounded) self.centralwidget = QtWidgets.QWidget(MainWindow) self.centralwidget.setObjectName("centralwidget") self.horizontalLayout_2 = QtWidgets.QHBoxLayout(self.centralwidget) self.horizontalLayout_2.setObjectName("horizontalLayout_2") self.verticalLayout = QtWidgets.QVBoxLayout() self.verticalLayout.setObjectName("verticalLayout") self.label = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.MinimumExpanding, QtWidgets.QSizePolicy.Preferred) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label.sizePolicy().hasHeightForWidth()) self.label.setSizePolicy(sizePolicy) font = QtGui.QFont() font.setPointSize(20) self.label.setFont(font) self.label.setAlignment(QtCore.Qt.AlignCenter) self.label.setObjectName("label") self.verticalLayout.addWidget(self.label) self.horizontalLayout = QtWidgets.QHBoxLayout() self.horizontalLayout.setSizeConstraint(QtWidgets.QLayout.SetDefaultConstraint) self.horizontalLayout.setContentsMargins(-1, 50, -1, -1) self.horizontalLayout.setSpacing(0) self.horizontalLayout.setObjectName("horizontalLayout") self.pushButton_1 = QtWidgets.QPushButton(self.centralwidget) self.pushButton_1.setMinimumSize(QtCore.QSize(90, 40)) self.pushButton_1.setMaximumSize(QtCore.QSize(150, 40)) font = QtGui.QFont() font.setPointSize(12) self.pushButton_1.setFont(font) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/newPrefix/pic/g1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_1.setIcon(icon1) self.pushButton_1.setObjectName("pushButton_1") self.pushButton_open = QtWidgets.QPushButton(self.centralwidget) self.pushButton_open.setMinimumSize(QtCore.QSize(100, 40)) self.pushButton_open.setMaximumSize(QtCore.QSize(120, 40)) font = QtGui.QFont() font.setPointSize(12) self.pushButton_open.setFont(font) icon1 = QtGui.QIcon() icon1.addPixmap(QtGui.QPixmap(":/newPrefix/pic/g1.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_open.setIcon(icon1) self.pushButton_open.setObjectName("pushButton_open") self.horizontalLayout.addWidget(self.pushButton_open) self.pushButton_take = QtWidgets.QPushButton(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Fixed, QtWidgets.QSizePolicy.Fixed) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.pushButton_take.sizePolicy().hasHeightForWidth()) self.pushButton_take.setSizePolicy(sizePolicy) self.pushButton_take.setMinimumSize(QtCore.QSize(100, 40)) self.pushButton_take.setMaximumSize(QtCore.QSize(100, 40)) font = QtGui.QFont() font.setPointSize(12) self.pushButton_take.setFont(font) self.pushButton_take.setIcon(icon) self.pushButton_take.setObjectName("pushButton_take") self.horizontalLayout.addWidget(self.pushButton_take) self.pushButton_close = QtWidgets.QPushButton(self.centralwidget) self.pushButton_close.setMinimumSize(QtCore.QSize(100, 40)) self.pushButton_close.setMaximumSize(QtCore.QSize(130, 40)) font = QtGui.QFont() font.setPointSize(12) self.pushButton_close.setFont(font) icon2 = QtGui.QIcon() icon2.addPixmap(QtGui.QPixmap(":/newPrefix/pic/down.png"), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.pushButton_close.setIcon(icon2) self.pushButton_close.setObjectName("pushButton_close") self.horizontalLayout.addWidget(self.pushButton_close) self.horizontalLayout.setStretch(0, 1) self.horizontalLayout.setStretch(1, 1) self.horizontalLayout.setStretch(2, 1) self.verticalLayout.addLayout(self.horizontalLayout) self.label_face = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.label_face.sizePolicy().hasHeightForWidth()) self.label_face.setSizePolicy(sizePolicy) self.label_face.setMinimumSize(QtCore.QSize(0, 0)) self.label_face.setMaximumSize(QtCore.QSize(16777215, 16777215)) font = QtGui.QFont() font.setFamily("楷体") font.setPointSize(16) self.label_face.setFont(font) self.label_face.setLayoutDirection(QtCore.Qt.LeftToRight) self.label_face.setStyleSheet("background-color: rgb(192, 218, 255);") self.label_face.setAlignment(QtCore.Qt.AlignCenter) self.label_face.setObjectName("label_face") self.verticalLayout.addWidget(self.label_face) self.labe2_face = QtWidgets.QLabel(self.centralwidget) sizePolicy = QtWidgets.QSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding) sizePolicy.setHorizontalStretch(0) sizePolicy.setVerticalStretch(0) sizePolicy.setHeightForWidth(self.labe2_face.sizePolicy().hasHeightForWidth()) self.labe2_face.setSizePolicy(sizePolicy) self.labe2_face.setMinimumSize(QtCore.QSize(0, 0)) self.labe2_face.setMaximumSize(QtCore.QSize(16777215, 16777215)) font = QtGui.QFont() font.setFamily("楷体") font.setPointSize(16) self.labe2_face.setFont(font) self.labe2_face.setLayoutDirection(QtCore.Qt.LeftToRight) self.labe2_face.setStyleSheet("background-color: rgb(192, 218, 255);") self.labe2_face.setAlignment(QtCore.Qt.AlignCenter) self.labe2_face.setObjectName("label_face") self.verticalLayout.addWidget(self.labe2_face) self.verticalLayout.setStretch(2, 5) self.horizontalLayout_2.addLayout(self.verticalLayout) MainWindow.setCentralWidget(self.centralwidget) self.actionGoogle_Translate = QtWidgets.QAction(MainWindow) self.actionGoogle_Translate.setObjectName("actionGoogle_Translate") self.actionHTML_type = QtWidgets.QAction(MainWindow) self.actionHTML_type.setObjectName("actionHTML_type") self.actionsoftware_version = QtWidgets.QAction(MainWindow) self.actionsoftware_version.setObjectName("actionsoftware_version") self.retranslateUi(MainWindow) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "王中王")) self.label.setText(_translate("MainWindow", "FPX牛逼!")) self.pushButton_1.setToolTip(_translate("MainWindow", "点击上传")) self.pushButton_1.setText(_translate("MainWindow", "上传")) self.pushButton_open.setToolTip(_translate("MainWindow", "点击打开摄像头")) self.pushButton_open.setText(_translate("MainWindow", "打开摄相头")) self.pushButton_take.setToolTip(_translate("MainWindow", "点击拍照")) self.pushButton_take.setText(_translate("MainWindow", "识别")) self.pushButton_close.setToolTip(_translate("MainWindow", "点击关闭摄像头")) self.pushButton_close.setText(_translate("MainWindow", "关闭摄像头")) self.label_face.setText(_translate("MainWindow", "最长火腿肠")) self.actionGoogle_Translate.setText(_translate("MainWindow", "Google Translate")) self.actionHTML_type.setText(_translate("MainWindow", "HTML type")) self.actionsoftware_version.setText(_translate("MainWindow", "software version")) #
# class Ui_MainWindow1(object): # def setupUi1(self, MainWindow): # MainWindow.setObjectName("MainWindow") # MainWindow.resize(382, 357) # self.centralwidget = QtWidgets.QWidget(MainWindow) # self.centralwidget.setObjectName("centralwidget") # self.label = QtWidgets.QLabel(self.centralwidget) # self.label.setGeometry(QtCore.QRect(10, 40, 361, 251)) # self.label.setObjectName("label") # MainWindow.setCentralWidget(self.centralwidget) # # self.retranslateUi(MainWindow) # QtCore.QMetaObject.connectSlotsByName(MainWindow) # # def retranslateUi(self, MainWindow): # _translate = QtCore.QCoreApplication.translate # MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) # self.label.setText(_translate("MainWindow", "TextLabel")) # self.label_face.setText(_translate("MainWindow", "上传成功!!!!!!!1"))