其他分享
首页 > 其他分享> > Simple face recognition based on opencv3

Simple face recognition based on opencv3

作者:互联网

我使用的语言为python,识别率不高,只是简单实现了人脸识别的步骤,参考<OpenCV3 计算机视觉>,部分的opencv库接口有所改变.

 

import cv2
import os
 
def generate(dirname):
     
    face_cascade = cv2.CascadeClassifier('/home/yuanqi/opencv-3.4.6/yuanqi opencv/cascades/haarcascade_frontalface_default.xml')
    eye_cascade = cv2.CascadeClassifier('/home/yuanqi/opencv-3.4.6/yuanqi opencv/cascades/haarcascade_eye_tree_eyeglasses.xml')
    if(not os.path.isdir(dirname)):
        os.makedirs(dirname)
  
    camera = cv2.VideoCapture(0)
    count = 0
    while (True):
        ret, frame = camera.read()
        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        faces = face_cascade.detectMultiScale(gray, 1.3, 5)
        for (x,y,w,h) in faces:
            img = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)
            f = cv2.resize(gray[y:y+h, x:x+w], (200, 200))
            cv2.imwrite(dirname+'/%s.pgm' % str(count), f)
            print(count)
            count += 1
 
        cv2.imshow("camera", frame)
        if cv2.waitKey(100) & 0xff == ord("q"):
            break
        elif count > 20:
            break
 
    camera.release()
    cv2.destroyAllWindows()

if __name__ == "__main__":
    generate("/home/yuanqi/opencvname/jm")

import sys
import os.path
if __name__ == "__main__":
    BASE_PATH="/home/yuanqi/opencvname"
    
    SEPARATOR=";"
 
    fh = open("/home/yuanqi/opencvname/jm/at.text",'w')
 
    label = 0
    for dirname, dirnames, filenames in os.walk(BASE_PATH):
        for subdirname in dirnames:
            subject_path = os.path.join(dirname, subdirname)
            for filename in os.listdir(subject_path):
                abs_path = "%s/%s" % (subject_path, filename)
                print ("%s%s%d" % (abs_path, SEPARATOR, label))
                fh.write(abs_path)
                fh.write(SEPARATOR)
                fh.write(str(label))
                fh.write("\n")      
            label = label + 1
    fh.close()




import cv2,os,sys
import numpy as np

def read_images(path, sz = None):
    c = 0
    X, y = [], []

    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):
                try:
                    if not filename.endswith('.pgm'):
                        continue
                    filepath = os.path.join(subject_path, filename)
                    im = cv2.imread(filepath, cv2.IMREAD_GRAYSCALE)
                    if sz is not None:
                        im = cv2.resize(im,(200,200))
                    X.append(np.asarray(im, dtype=np.uint8))
                    y.append(c)
                except:
                    print("Unexpected error:",sys.exc_info()[0])
            c = c + 1
    return [X, y]

def face_rec(img_path):
    names = ['yaq']
    [X,y] = read_images(img_path)
    y = np.asarray(y, dtype=np.int32)
    model = cv2.face.EigenFaceRecognizer_create()
    model.train(np.asarray(X), np.asarray(y))

    camera = cv2.VideoCapture(0)
    face_cascade = cv2.CascadeClassifier(
            r'/home/yuanqi/opencv-3.4.6/yuanqi opencv/cascades/haarcascade_frontalface_default.xml')
    while (True):
        read, img = camera.read()
        faces = face_cascade.detectMultiScale(img, 1.3, 5)
        for (x, y, w, h) in faces:
            img = cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2)
            gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
            roi = gray[x: x+w, y: y+h]
            try:
                roi = cv2.resize(roi, (200, 200), interpolation=cv2.INTER_LINEAR)
                params = model.predict(roi)
                print("Label: %s, Confidence: %.2f" % (params[0], params[1]))
                cv2.putText(img, names[params[0]], (x, y - 20), cv2.FONT_HERSHEY_SIMPLEX, 1, 255, 2)
            except:
                continue
        cv2.imshow("camera", img)
        if cv2.waitKey(1000 // 12) & 0xff == ord('q'):
            break
    cv2.destroyAllWindows()

if __name__ == "__main__":
    face_rec(r'/home/yuanqi/opencvname')

标签:__,based,img,Simple,yuanqi,cv2,opencv3,path,os
来源: https://www.cnblogs.com/abadrabbit/p/12813169.html