Python人脸表情识别QT窗体

.Python人脸表情识别QT窗体

如需安装运行环境或远程调试,可加扣905733049, 或扣2945218359由专业技术人员远程协助!

运行结下:

主要代码:

# coding:utf-8
import sys
#从转换的.py文件内调用类
import cv2
import numpy as np
import sys
import tensorflow as tf

from untitled import Ui_Dialog
from PyQt5 import QtWidgets

from PyQt5 import QtWidgets, QtCore, QtGui
from PyQt5.QtCore import *

class myWin(QtWidgets.QWidget, Ui_Dialog):

    def __init__(self):
        super(myWin, self).__init__()
        self.setupUi(self)

    def openFileButton(self):
        imgName, imgType  = QFileDialog.getOpenFileName(self,"打开文件","./","files(*.*)")
        img = cv2.imread(imgName)
        cv2.imwrite("temp/original.jpg", img)
        height, width, pixels = img.shape
        print("width,height",width,height)
        print("self.label.width()",self.label.width())
        print("self.label.height()",self.label.height())


        frame = cv2.resize(img, (int(rwidth), int(rheight)))
        print("rwidth-elif,rheight-elfi", rwidth, rheight)
        img2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # opencv读取的bgr格式图片转换成rgb格式
        _image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
        jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight) #设置图片大小
        self.label.setPixmap(jpg_out) #设置图片显示


    def saveFileButton(self):
        img = cv2.imread("temp/original.jpg")
        file_path = QFileDialog.getSaveFileName(self, "save file", "./save/test","jpg files (*.jpg);;all files(*.*)")
        print(file_path[0])
        cv2.imwrite(file_path[0], img)
        cv2.waitKey(0)
        cv2.destroyAllWindows()


    def recogPerson(self):
        import os
        import cv2


        img = cv2.imread("temp/original.jpg")
        cv2.imwrite("save/recognPerson2.jpg", img)
        face_detect = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
        eye_detect = cv2.CascadeClassifier('haarcascade_eye.xml')
        # 灰度处理
        gray = cv2.cvtColor(img, code=cv2.COLOR_BGR2GRAY)
        # 检查人脸 按照1.1倍放到 周围最小像素为5
        face_zone = face_detect.detectMultiScale(gray,1.3,5)
        # print ('识别人脸的信息:\n',face_zone)
        l = len(face_zone)


        ints = 0
        # 绘制矩形和圆形检测人脸
        for x, y, w, h in face_zone:
            ints += 1
            # 绘制矩形人脸区域
            if w < 1000:
                cv2.rectangle(img, pt1=(x, y), pt2=(x + w, y + h), color=[0, 0, 255], thickness=2)
                # 绘制圆形人脸区域 radius表示半径
                cv2.circle(img, center=(x + w // 2, y + h // 2), radius=w // 2, color=[0, 255, 0], thickness=2)
                roi_face = gray[y:y + h, x:x + w]  # 灰度图
                roi_color = img[y:y + h, x:x + w]  # 彩色图
                eyes = eye_detect.detectMultiScale(roi_face)
                for (ex, ey, ew, eh) in eyes:
                    cv2.rectangle(roi_color, (ex, ey), (ex + ew, ey + eh), (0, 255, 0), 2)

        cv2.imwrite("save/recognPerson.jpg", img)
        #cv2.waitKey(0)

        #显示人数到窗体
        self.textEdit.setPlainText(str(ints))
        #self.textEdit.setPlainText('Hello PyQt5!\n单击按钮')
        frame = cv2.resize(img, (int(rwidth), int(rheight)))
        img2 = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)  # opencv读取的bgr格式图片转换成rgb格式
        _image = QtGui.QImage(img2[:], img2.shape[1], img2.shape[0], img2.shape[1] * 3, QtGui.QImage.Format_RGB888)
        jpg_out = QtGui.QPixmap(_image).scaled(rwidth, rheight) #设置图片大小
        self.label_2.setPixmap(QPixmap(""))
        self.label_2.setPixmap(jpg_out) #设置图片显示

        #emotion recog
        CASC_PATH = './data/haarcascade_files/haarcascade_frontalface_default.xml'
        cascade_classifier = cv2.CascadeClassifier(CASC_PATH)
        EMOTIONS = ['Angry', 'Disgusted', 'Fearful', 'Happy', 'Sad', 'Surprised', 'Neutral']

        def format_image(image):
            if len(image.shape) > 2 and image.shape[2] == 3:
                image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            faces = cascade_classifier.detectMultiScale(
                image,
                scaleFactor=1.3,
                minNeighbors=5
            )
            # None is no face found in image
            if not len(faces) > 0:
                return None, None
            max_are_face = faces[0]
            for face in faces:
                if face[2] * face[3] > max_are_face[2] * max_are_face[3]:
                    max_are_face = face
            # face to image
            face_coor = max_are_face
            image = image[face_coor[1]:(face_coor[1] + face_coor[2]), face_coor[0]:(face_coor[0] + face_coor[3])]
            # Resize image to network size
            try:
                image = cv2.resize(image, (48, 48), interpolation=cv2.INTER_CUBIC)
            except Exception:
                print("[+} Problem during resize")
                return None, None
            return image, face_coor

        def face_dect(image):
            """
            Detecting faces in image
            :param image:
            :return:  the coordinate of max face
            """
            if len(image.shape) > 2 and image.shape[2] == 3:
                image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
            faces = cascade_classifier.detectMultiScale(
                image,
                scaleFactor=1.3,
                minNeighbors=5
            )
            if not len(faces) > 0:
                return None
            max_face = faces[0]
            for face in faces:
                if face[2] * face[3] > max_face[2] * max_face[3]:
                    max_face = face
            face_image = image[max_face[1]:(max_face[1] + max_face[2]), max_face[0]:(max_face[0] + max_face[3])]
            try:
                image = cv2.resize(face_image, (48, 48), interpolation=cv2.INTER_CUBIC) / 255.
            except Exception:
                print("[+} Problem during resize")
                return None
            return face_image

        def resize_image(image, size):
            try:
                image = cv2.resize(image, size, interpolation=cv2.INTER_CUBIC) / 255.
            except Exception:
                print("+} Problem during resize")
                return None
            return image

        def draw_emotion():
            pass

        import os
        import sys
        def demo(modelPath, showBox=False):
            import cv2
            face_x = tf.placeholder(tf.float32, [None, 2304])
            y_conv = deepnn(face_x)
            probs = tf.nn.softmax(y_conv)
            print("test3")

            saver = tf.train.Saver()
            ckpt = tf.train.get_checkpoint_state(modelPath)
            sess = tf.Session()
            if ckpt and ckpt.model_checkpoint_path:
                saver.restore(sess, ckpt.model_checkpoint_path)
                print('Restore model sucsses!!\nNOTE: Press SPACE on keyboard to capture face.')


            feelings_faces = []
            for index, emotion in enumerate(EMOTIONS):
                feelings_faces.append(cv2.imread('./data/emojis/' + emotion + '.png', -1))
            #video_captor = cv2.VideoCapture(0)
            import cv2
            result = sess.run(probs, feed_dict={face_x: tensor})
            print("result: ", result)
            # name_list = ','.join(result)
            # print("name_list: ", name_list)

            print("test4")
            if os.path.exists("recv.txt"):
                os.remove("recv.txt")
            if os.path.exists("recv2.txt"):
                os.remove("recv2.txt")
            for index, emotion in enumerate(EMOTIONS):
                file = open('recv.txt', 'a')
                file.write(str(emotion)+": " + str(rate)+", ")
                file.write(";")
                file.close()
            file5 = open("recv.txt", 'rt')
            contents = file5.read()
            data = contents.replace(";", ";\n")

            fin = open('recv2.txt', "wt")
            fin.write(data)
            fin.close()

            with open("recv2.txt", "r") as file2:
                path = file2.read()
                print("path ", path)
                file2.close()
            self.textEdit_2.setPlainText(path)
            tf.reset_default_graph()

            # emoji_face = []
            # result = None
            #
            # while True:
            #     #ret, frame = video_captor.read()
            #     import cv2
            #     frame = cv2.imread("save/recognPerson.jpg")
            #     detected_face, face_coor = format_image(frame)
            #     if showBox:
            #         if face_coor is not None:
            #             [x, y, w, h] = face_coor
            #             cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)
            #
            #     if cv2.waitKey(1) & 0xFF == ord(' '):
            #
            #         if detected_face is not None:
            #             # cv2.imwrite('a.jpg', detected_face)
            #             tensor = image_to_tensor(detected_face)
            #             result = sess.run(probs, feed_dict={face_x: tensor})
            #             print("result: ",result)
            #     if result is not None:
            #         for index, emotion in enumerate(EMOTIONS):
            #             print("emotion: ", emotion)
            #             print("index: ", index)
            #             cv2.putText(frame, emotion, (10, index * 20 + 20), cv2.FONT_HERSHEY_PLAIN, 1.2, (0, 255, 0), 1)
            #             cv2.rectangle(frame, (130, index * 20 + 10),
            #                           (130 + int(result[0][index] * 100), (index + 1) * 20 + 4),
            #                           (255, 0, 0), -1)
            #             emoji_face = feelings_faces[np.argmax(result[0])]
            #             print("int(result[0][index]: ", int(result[0][index] * 100))
            #
            #         for c in range(0, 3):
            #             frame[200:320, 10:130, c] = emoji_face[:, :, c] * (emoji_face[:, :, 3] / 255.0) + frame[200:320,
            #                                                                                               10:130, c] * (
            #                                                     1.0 - emoji_face[:, :, 3] / 255.0)
            #
            #     cv2.imshow('face', frame)
            #     if cv2.waitKey(1) & 0xFF == ord('q'):
            #         break



        if __name__ == '__main__':
            modelPath = "ckpt"
            demo(modelPath)



if __name__=="__main__":

    app=QtWidgets.QApplication(sys.argv)
    Widget=myWin()
    Widget.showMaximized();
    Widget.show()
    sys.exit(app.exec_())

运行结下:

 

你可能感兴趣的:(Python,qt,开发语言)