计算机视觉机器学习与计算机视觉人脸识别

人脸检测与人脸识别

2019-04-10  本文已影响20人  云恒子

本文首发于【程序员微读】微信公众号

OpenCV是开源的计算机视觉库,实现了很多图像处理和计算机视觉方面的通用算法。下面主要OpenCV中的内置算法来实现人脸检测与人脸识别。

人脸检测

流程
代码
import cv2 as cv
import numpy as np

def face_detect(image):
    gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
    face_detector = cv.CascadeClassifier("haarcascade_frontalface_default.xml")
    faces = face_detector.detectMultiScale(gray, 1.02, 20)
    for x, y, w, h in faces:
        cv.rectangle(image, (x, y), (x + w, y + h), (0, 0, 255), 2)
    cv.imshow("face_detect", image)

def video_face_detect():
    capture = cv.VideoCapture(0)
    while True:
        ret, frame = capture.read()
        frame = cv.flip(frame, 1)
        face_detect(frame)
        c = cv.waitKey(10)
        if c==27:  # ESC
            break

if __name__ == '__main__':
    src = cv.imread("test.jpg")
    face_detect(src)
    # video_face_detect()
    cv.waitKey(10000)
    cv.destroyAllWindows()

人脸识别

流程

1.训练

2.测试

代码
import cv2 as cv
import numpy as np
import os
import sys

def dataset(path):
    label = 0
    imgs, labels = [], []
    for dirname, dirnames, filenames in os.walk(path):
        for subdirname in dirnames:
            subject_path = os.path.join(dirname, subdirname)
            for filename in os.listdir(subject_path):
                filepath = os.path.join(subject_path, filename)
                im = cv.imread(filepath, cv.IMREAD_GRAYSCALE)
                im = cv.resize(im, (200, 200))
                imgs.append(np.asarray(im, dtype=np.uint8))
                labels.append(label)
            label += 1
    return [imgs, labels]

def train(imgs, labels):
    labels = np.asarray(labels, dtype=np.int32)
    model = cv.face.EigenFaceRecognizer_create()
    model.train(np.asarray(imgs), np.asarray(labels))
    return model

def test(model, testimg_path):
    names = ['joe', 'jane', 'jack', 'Mike']# 每个类别实际对应的名称,按类别文件夹顺序
    img = cv.imread(testimg_path)
    #人脸检测
    face_cascade = cv.CascadeClassifier('haarcascade_frontalface_default.xml')
    faces = face_cascade.detectMultiScale(img, 1.1, 1)
    #对图片中每个人脸进行识别
    for (x, y, w, h) in faces:
        img = cv.rectangle(img, (x,y), (x+w, y+h), (255, 0, 0), 2)
        gray = cv.cvtColor(img, cv.COLOR_BGR2GRAY)
        roi = gray[x:x+w, y:y+h]
        roi = cv.resize(roi, (200, 200), interpolation=cv.INTER_LINEAR)
        params = model.predict(roi)
        print("label: %s, confidence: %.3f" % (params[0], params[1]))
        cv.putText(img, names[params[0]], (x, y), cv.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
    cv.imshow("img", img)
    cv.waitKey(10000)
    cv.destroyAllWindows()

if __name__ == '__main__':
    data_path = "数据集文件夹根路径"
    testimg_path = "测试图片路径"
    imgs, labels = dataset(data_path)
    model = train(imgs, labels)
    test(model, testimg_path)

总结

OpenCV中提供的人脸检测与人脸识别相关算法缺乏实用性且人脸识别算法只能对训练集中涉及到的人脸予以识别,所以算法适用场景小。若需更好的人脸识别算法可研究研究FaceNet框架,后期有空也将会在公众号发布FaceNet相关文章,敬请期待。

若需项目工程文件请于微信公众号【程序员微读】回复“Face代码”(建议复制发送)

版权声明:未经许可,禁止转载

上一篇下一篇

猜你喜欢

热点阅读