Opencv中的Python多线程人脸识别

时间:2019-05-28 10:15:10

标签: python multithreading opencv multiprocessing face-recognition

我正在尝试使用带有Opencv的Python 3.6构建人脸识别程序。

我写了一个代码;当屏幕上有我的脸时,我的脸周围会有一个红色正方形,包括我的名字。而且它只会在控制台上一次打印我的名字,如果我继续坐在相机上,就说我可以去了,因为它拍了我的照片。

import face_recognition
import cv2

video_capture = cv2.VideoCapture(0)

wicaledon_image = face_recognition.load_image_file("Wicaledon.jpg")
wicaledon_face_encoding = face_recognition.face_encodings(wicaledon_image)[0]

known_face_encodings = [
    wicaledon_face_encoding
]
known_face_names = [
    "Wicaledon"
]

# Initialize some variables
face_locations = []
face_encodings = []
face_names = []
process_this_frame = True
new_name = ''

while True:
    ret, frame = video_capture.read()

    small_frame = cv2.resize(frame, (0, 0), fx=0.25, fy=0.25)

    rgb_small_frame = small_frame[:, :, ::-1]

    if process_this_frame:

        face_locations = face_recognition.face_locations(rgb_small_frame)
        face_encodings = face_recognition.face_encodings(rgb_small_frame, face_locations)

        face_names = []
        for face_encoding in face_encodings:
            matches = face_recognition.compare_faces(known_face_encodings, face_encoding)
            name = "Unknown"

            if True in matches:
                first_match_index = matches.index(True)
                name = known_face_names[first_match_index]

                if str(new_name) == str(name):
                    print("You can go Mr {}".format(name))
                else:
                    print("Hello {}".format(name))
            new_name = name

            face_names.append(name)

    process_this_frame = not process_this_frame

    for (top, right, bottom, left), name in zip(face_locations, face_names):
        # Scale back up face locations since the frame we detected in was scaled to 1/4 size
        top *= 4
        right *= 4
        bottom *= 4
        left *= 4

        # Draw a box around the face
        cv2.rectangle(frame, (left, top), (right, bottom), (0, 0, 255), 2)

        # Draw a label with a name below the face
        cv2.rectangle(frame, (left, bottom - 35), (right, bottom), (0, 0, 255), cv2.FILLED)
        font = cv2.FONT_HERSHEY_DUPLEX
        cv2.putText(frame, name, (left + 6, bottom - 6), font, 1.0, (255, 255, 255), 1)

    # Display the resulting image
    cv2.imshow('Video', frame)

    # Hit 'q' on the keyboard to quit!
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break

# Release handle to the webcam
video_capture.release()
cv2.destroyAllWindows()

问题是;屏幕上没有面孔时,FPS速度很快。但是,当屏幕上有一张脸(甚至是未知的脸)时,FPS会变得非常慢(我认为;因为拍摄了很多快照)。我想要当我的脸出现在屏幕上时,它应该始终显示红色方块,但是快速FPS和打印语句应该继续。

当我检查我必须使用Thread时,但是即使有很多尝试,我也都没有找到解决方案。你能帮我吗?

0 个答案:

没有答案