38.python人脸识别

获取图片

import cv2

detector = cv2.CascadeClassifier('haarcascade_frontalface_default.xml')
sampleNum = 0
Id = input('enter your id: ')
print('\n Initializing face capture. Look at the camera and wait ...')

cam = cv2.VideoCapture(0)
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)

while True:
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = detector.detectMultiScale(
        gray,
        scaleFactor=1.3,
        minNeighbors=5,
        minSize=(int(minW), int(minH))
    )
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x, y), (x + w, y + h), (255, 0, 0), 2)
        # incrementing sample number
        sampleNum = sampleNum + 1
        # saving the captured face in the dataset folder
        cv2.imwrite("dataSet/User." + str(Id) + '.' + str(sampleNum) + ".jpg", gray[y:y + h, x:x + w])  #

        cv2.imshow('frame', img)
    # wait for 100 miliseconds
    if cv2.waitKey(2) & 0xFF == ord('q'):
        print(sampleNum)
        break

    elif sampleNum >= 200:
        print(sampleNum)
        break

cam.release()
cv2.destroyAllWindows()

训练

import cv2
import os
import numpy as np
from PIL import Image


detector = cv2.CascadeClassifier("haarcascade_frontalface_default.xml")
recognizer = cv2.face.LBPHFaceRecognizer_create()


def get_images_and_labels(path):
    image_paths = [os.path.join(path, f) for f in os.listdir(path)]
    face_samples = []
    ids = []

    for image_path in image_paths:
        image = Image.open(image_path).convert('L')
        image_np = np.array(image, 'uint8')
        if os.path.split(image_path)[-1].split(".")[-1] != 'jpg':
            continue
        image_id = int(os.path.split(image_path)[-1].split(".")[1])
        faces = detector.detectMultiScale(image_np)
        for (x, y, w, h) in faces:
            face_samples.append(image_np[y:y + h, x:x + w])
            ids.append(image_id)

    return face_samples, ids


faces, Ids = get_images_and_labels('dataSet')
print('Training faces. It will take a few seconds. Wait ...')
recognizer.train(faces, np.array(Ids))
recognizer.save('trainner/trainner.yml')

识别

import cv2
import numpy as np
#加载识别器
recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainner/trainner.yml')
#加载分类器
cascade_path = "haarcascade_frontalface_default.xml"
face_cascade = cv2.CascadeClassifier(cascade_path)
#开摄像头
cam = cv2.VideoCapture(0)
minW = 0.1*cam.get(3)
minH = 0.1*cam.get(4)
#加载一个字体
font = cv2.FONT_HERSHEY_SIMPLEX
names = ['LiTingkuan', 'YiXin']
while True:
    #人脸识别
    ret, img = cam.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(
        gray,
        scaleFactor=1.3,
        minNeighbors=5,
        minSize=(int(minW), int(minH))
    )
    #加方框和名字
    for (x, y, w, h) in faces:
        cv2.rectangle(img, (x , y ), (x + w , y + h ), (225, 0, 0), 2)
        img_id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
        if confidence < 50:
            img_id = names[img_id-1]
            confidence = "{0}%".format(round(100 - confidence))
        else:
            img_id = "Unknown"
            confidence = "{0}%".format(round(100 - confidence))

        cv2.putText(img, str(img_id), (x, y + h), font, 0.55, (0, 255, 0), 1)
        cv2.putText(img, str(confidence), (x + 5, y - 5), font, 1, (0, 255, 0), 1)
    cv2.imshow('im', img)
    if cv2.waitKey(10) & 0xFF == ord('q'):
        break

cam.release()
cv2.destroyAllWindows()
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值