一个视频脸部识别和训练的小程序

发布时间:2023年12月20日

https://download.csdn.net/download/nn_84/88644035

这是本人没事用 opencv 写的脸部识别训练 小程序? 所有文件都在里面?

看懂了会笑死人? 一个算法也没有

识别脸部训练:

import cv2, numpy, os ,time

os.environ["CUDA_VISIBLE_DEVICES"] = "1"  
 

labels, faces = [], []
file = 'haarcascade_frontalface_default.xml'     
face_cascade = cv2.CascadeClassifier(file)
recognizer = cv2.face.LBPHFaceRecognizer_create()  
cap = cv2.VideoCapture(0)

 

def detect_face(image):
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5, minSize=(20, 20))
    if (len(faces) == 0):
        return None
    (x, y, w, h) = faces[0]
    return gray[y:y+w, x:x+h]

 

def read_face(label):

    while (True):
        ret,image = cap.read()
        face = detect_face(image)

     #   time.sleep(0.08)
        cv2.imshow("windows",image)
        if cv2.waitKey(1) & 0xFF == ord('q'):
            break

        if face is not None:
            face = cv2.resize(face, (256, 256))
            faces.append(face)
            labels.append(label)

 

if __name__ == '__main__':
    print("请问需要识别几个人:")
    numb = int(input())
    i = 1
    while (i <= numb):
        read_face(i)
        time.sleep(8)
        print("第" + str(i) + "个人完成训练 ")
        i += 1
    recognizer.train(faces, numpy.array(labels))
    recognizer.save('trainner.yml')

脸部识别主程序:

import cv2, os, time

os.environ["CUDA_VISIBLE_DEVICES"] = "1"


names = ('None', 'Your name')  
file = 'haarcascade_frontalface_default.xml'
face_cascade = cv2.CascadeClassifier(file)
recognizer = cv2.face.LBPHFaceRecognizer_create()   
recognizer.read('trainner.yml')  
cap = cv2.VideoCapture(0)

 

while (True):
    ret,img = cap.read()
    gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray, 1.2, 5)


    for (x, y, w, h) in faces:
        face = gray[y:y+w, x:x+h]
        face = cv2.resize(face, (256, 256))


        label, confidence = recognizer.predict(face)
        confidence = 100 - confidence

 

        if label > 0 and confidence > 75 :  
            cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 0), 3)
            text = 'Name: %s %i' %(names[label],confidence)
            font = cv2.FONT_HERSHEY_PLAIN
            cv2.putText(img, text, (x, y), font, 1.2, (220, 220, 220), 2)
      #  else:
      #     cv2.rectangle(img, (x, y), (x+w, y+h), (0, 0, 255), 3)
      #  time.sleep(0.5)
        cv2.imshow('Image', img)

    if cv2.waitKey(1) & 0xFF == ord('q'):
            break

关于opencv 安装

fedora 38 39 :? # sudo yum install opencv opencv-contrib python3-opencv

文章来源:https://blog.csdn.net/nn_84/article/details/135089547
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。