人工智能-人脸识别

人脸识别

import cv2, os, numpy as np

# 共享配置

recognizer = cv2.face.LBPHFaceRecognizer_create()

dataset_dir = "dataset"

face_cascade = cv2.CascadeClassifier(os.getcwd() + '\\' + 'haarcascade_frontalface_default.xml')

def collect_data():

    user_id = input("用户ID(数字): ")

    user_dir = f"{dataset_dir}/User_{user_id}_{input('用户名: ')}"

    os.makedirs(user_dir, exist_ok=True)

    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)

   

    count = 0

    while count < 50 and cv2.waitKey(1) != 27:

        _, frame = cap.read()

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        faces = face_cascade.detectMultiScale(gray, 1.3, 5)

        for x, y, w, h in faces:

            cv2.imwrite(

                f"{user_dir}/{count}.jpg",

                cv2.resize(gray[y : y + h, x : x + w], (200, 200)),

            )

            cv2.rectangle(frame, (x, y), (x + w, y + h), (255, 0, 0), 2)

            count += 1

        cv2.imshow("Collecting...", frame)

    cap.release()

    cv2.destroyAllWindows()


 

def train_model():

    faces, ids = [], []

    for root, _, files in os.walk(dataset_dir):

        for file in files:

            if file.endswith(".jpg"):

                path = os.path.join(root, file)

                faces.append(cv2.imread(path, 0))

                ids.append(int(os.path.basename(root).split("_")[1]))

    recognizer.train(faces, np.array(ids))

    recognizer.save("model.yml")


 

def recognize():

    id_map = {0: "Unknown"}

    for d in os.listdir(dataset_dir):

        if d.startswith("User_"):

            id_map[int(d.split("_")[1])] = d.split("_")[2]

    recognizer.read("model.yml")

    cap = cv2.VideoCapture(0,cv2.CAP_DSHOW)

    while cv2.waitKey(1) != 27:

        _, frame = cap.read()

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        for x, y, w, h in face_cascade.detectMultiScale(gray, 1.3, 5):

            label, conf = recognizer.predict(

                cv2.resize(gray[y : y + h, x : x + w], (200, 200))

            )

            name = id_map.get(label, "Unknown") if conf < 60 else "Unknown"

            color = (0, 255, 0) if name != "Unknown" else (0, 0, 255)

            cv2.rectangle(frame, (x, y), (x + w, y + h), color, 2)

            cv2.putText(frame, name, (x, y - 10), cv2.FONT_HERSHEY_SIMPLEX, 1, color, 2)

        cv2.imshow("Recognizing...", frame)

    cap.release()

    cv2.destroyAllWindows()


 

if __name__ == "__main__":

    func = [collect_data, train_model, recognize][

        int(input("功能选择 (1采集 2训练 3识别): ")) - 1

    ]

    func()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值