简体   繁体   中英

Tkinter OpenCV Face Recognition

I have three files for face recognition project. Them being encoding, training and recognizing.

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()

And training part being:

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")

Finally the recognition part being:

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()

I need to create a GUI of these three files. I don't know where to start or what to do. If anyone can help/guide me it'll help me a lot. A GUI consisting of three buttons which will use the 3 py files. Also if anyone knows how to check the accuracy of the facial recognition, help me.

your question is very general. Try next time to ask one thing at a time. So basically to perform your task, you have to know about functions , relative imports and the basics of tkinter . I highly recommend you to watch tutorial videos to these things. Here is an example how you create a basic tkinter object with buttons. You have to wrap the code in your files into functions and then you can import these functions in your file where you create the 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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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