繁体   English   中英

Tkinter OpenCV 人脸识别

[英]Tkinter OpenCV Face Recognition

我有三个文件用于人脸识别项目。 它们正在编码、训练和识别。

File: encoding.py
import cv2
import os
from pathlib import Path

faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")

vc = cv2.VideoCapture(0)

print("Enter the id and name of the person: ")
userId = input()
userName = input()

count = 1

def saveImage(image, userName, userId, imgId):
    # Create a folder with the name as userName
    Path("dataset/{}".format(userName)).mkdir(parents=True, exist_ok=True)
    # Save the images inside the previously created folder
    cv2.imwrite("dataset/{}/{}_{}.jpg".format(userName, userId, imgId), image)
    print("[INFO] Image {} has been saved in folder : {}".format(imgId, userName))

print("[INFO] Video Capture is now starting please stay still...")

while True:
    _, img = vc.read()
    if img is None:
        break
    originalImg = img.copy()
    gray_img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = faceCascade.detectMultiScale(gray_img,
                                         scaleFactor=1.2,
                                         minNeighbors=5,
                                         minSize=(50, 50))

    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        coords = [x, y, w, h]
    cv2.imshow("Identified Face", img)
    key = cv2.waitKey(1) & 0xFF
    if key == ord('s'):
        if count <= 5:
            roi_img = originalImg[coords[1] : coords[1] + coords[3], coords[0] : coords[0] + coords[2]]
            saveImage(roi_img, userName, userId, count)
            count += 1
        else:
            break
    elif key == ord('q'):
        break

print("[INFO] Dataset has been created for {}".format(userName))
vc.release()
cv2.destroyAllWindows()

训练部分是:

File: training.py
import os
import cv2
import numpy as np
from PIL import Image

names = []
path = []

for users in os.listdir("dataset"):
    names.append(users)

for name in names:
    for image in os.listdir("dataset/{}".format(name)):
        path_string = os.path.join("dataset/{}".format(name), image)
        path.append(path_string)
faces = []
ids = []

for img_path in path:
    image = Image.open(img_path).convert("L")

    imgNp = np.array(image, "uint8")

    id = int(img_path.split("/")[1].split("_")[1].split(".")[0])

    faces.append(imgNp)
    ids.append(id)

ids = np.array(ids)

print("[INFO] Created faces and names Numpy Arrays")
print("[INFO] Initializing the Classifier")
trainer = cv2.face.LBPHFaceRecognizer_create()
trainer.train(faces, ids)
trainer.write("training.yml")

print("[INFO] Training Done")

最后识别部分是:

File: recognize.py
import cv2
import os
faceCascade = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
# video_capture = cv2.VideoCapture(0)

# Call the trained model yml file to recognize faces
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read("training.yml")
# Names corresponding to each id
names = []
for users in os.listdir("dataset"):
    names.append(users)
video_capture = cv2.VideoCapture(0, cv2.CAP_DSHOW)

while True:

    _, img = video_capture.read()

    gray_image = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale(
        gray_image, scaleFactor=1.2, minNeighbors=5, minSize=(100, 100)
    )

    # Try to predict the face and get the id
    # Then check if id == 1 or id == 2
    # Accordingly add the names
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (0, 255, 0), 2)
        id, _ = recognizer.predict(gray_image[y:y+h, x:x+w])
        if id == 1:
            cv2.putText(
                img,
                names[id - 1],
                (x, y - 4),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.8,
                (0, 255, 0),
                1,
                cv2.LINE_AA,
            )
        else:
            cv2.putText(
                img,
                "Unknown",
                (x, y - 4),
                cv2.FONT_HERSHEY_SIMPLEX,
                0.8,
                (255, 0, 0),
                1,
                cv2.LINE_AA,
            )

    cv2.imshow("Recognize", img)

    if cv2.waitKey(1) & 0xFF == ord("q"):
        break

# video_capture.release()
cv2.destroyAllWindows()

我需要创建这三个文件的 GUI。 我不知道从哪里开始或做什么。 如果有人可以帮助/指导我,那将对我有很大帮助。 由三个按钮组成的 GUI,将使用 3 个 py 文件。 另外,如果有人知道如何检查面部识别的准确性,请帮助我。

你的问题很笼统。 下次尝试一次问一件事。 因此,基本上要执行您的任务,您必须了解tkinterfunctionsrelative imports和基础知识。 我强烈建议您观看这些东西的教程视频。 这是一个示例,您如何使用按钮创建基本的tkinter object 您必须将文件中的代码包装到functions中,然后您可以将这些函数导入您的文件中,在其中创建tkinter object

import tkinter as tk

# relative imports
from file1 import functionX
from file2 import functionY
from file3 import functionZ

# create functions that are executed when pressing the buttons (can be the imported functions later)
def func1():
    print('Pressed Button1')
    # do something

def func2():
    print('Pressed Button2')
    # do something

def func3():
    print('Pressed Button3')
    # do something


# create a tkinter object
root = tk.Tk()

# put a frame into your tkinter object
frame1 = tk.Frame(root).grid(row=0, column=0)

# create and place the three buttons into the frame
button1 = tk.Button(frame1, height=2, width=6, text='Button1', command=func1).grid(row=0, column=0)
button2 = tk.Button(frame1, height=2, width=6, text='Button2', command=func2).grid(row=1, column=0)
button3 = tk.Button(frame1, height=2, width=6, text='Button3', command=func3).grid(row=2, column=0)


# this is needed so the tkinter object stays open until you close it manually
tk.mainloop()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM