【问题标题】:Face recognition problem on OpenCV pythonOpenCV python上的人脸识别问题
【发布时间】:2020-05-14 20:21:35
【问题描述】:

非常感谢帮助,我在 openCV 上进行了人脸识别。问题是我需要在cmd中显示被识别的人的名字,例如,如果一个名字为Alex的人被识别了,那么这个人的名字应该通过print(id)在cmd中显示,我试过之后 如果(确定性> 20): id = 名称 [id] 插入 print(id),但它进入 while 循环并打印无限量,我需要它打印一次人名,而不是在循环中,但这样识别继续。 这是代码

import cv2
import numpy as np
import os 


recognizer = cv2.face.LBPHFaceRecognizer_create()
recognizer.read('trainer/trainer.yml')
cascadePath = "haarcascade_frontalface_default.xml"
faceCascade = cv2.CascadeClassifier(cascadePath);
font = cv2.FONT_HERSHEY_SIMPLEX#iniciate id counter

id = 0# names related to ids: example ==> Marcelo: id=1,  etc

names = ['None', 'Alex', 'Trump', 'Obama', 'Z', 'W'] # Initialize and start realtime video capture

cam = cv2.VideoCapture(1)
cam.set(3, 1280) # set video widht
cam.set(4, 720) # set video height# Define min window size to be recognized as a face

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

while True:
    ret, img =cam.read()# Flip vertically
    gray = cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)

    faces = faceCascade.detectMultiScale( 
        gray,
        scaleFactor = 1.2,
        minNeighbors = 5,
        minSize = (int(minW), int(minH)),
       )
    for(x,y,w,h) in faces:
        cv2.rectangle(img, (x,y), (x+w,y+h), (0,255,0), 2)
        id, confidence = recognizer.predict(gray[y:y+h,x:x+w])
                # If confidence is less them 100 ==> "0" : perfect match 
        if (confidence > 20):
            id = names[id]
            confidence = "  {0}%".format(round(100 - confidence))

        else:
            id = "Unknown person"
            confidence = "  {0}%".format(round(100 - confidence))

        cv2.putText(
                    img, 
                    str(id), 
                    (x+5,y-5), 
                    font, 
                    1, 
                    (255,255,255), 
                    2
                   )
        cv2.putText(
                    img, 
                    str(confidence), 
                    (x+5,y+h-5), 
                    font, 
                    1, 
                    (255,255,0), 
                    1
                   )  

    cv2.imshow('camera',img) 
    k = cv2.waitKey(10) & 0xff # Press 'ESC' for exiting video
    if k == 27:
        break# Do a bit of cleanup
print("\n [INFO] Exiting Program and cleanup stuff")
cam.release()
cv2.destroyAllWindows()

【问题讨论】:

  • id 保留在变量previous = id 中并比较if id != previous: print(id),然后分配新的previous = id
  • 非常感谢!!!

标签: python python-3.x opencv


【解决方案1】:

开始创建

previous_id = None

在循环中使用

if id != previous_id:
   print(id)
   previous_id = id

如果您只想打印一次id,即使它在其他id 之后再次打印,请使用列表

开始创建

all_previous_id = []

在循环中使用

if id not in all_previous_id:
   print(id)
   all_previous_id.append(id)

【讨论】:

    猜你喜欢
    • 2021-09-14
    • 2019-08-10
    • 2017-02-26
    • 2017-02-03
    • 2021-08-16
    • 2018-06-14
    • 2019-05-10
    • 2013-12-24
    • 2020-10-07
    相关资源
    最近更新 更多