【问题标题】:AttributeError: 'str' object has no attribute 'train'AttributeError:“str”对象没有属性“train”
【发布时间】:2019-11-07 16:18:43
【问题描述】:

我目前正在制作面部识别系统。我在网上得到了这个代码。有很多问题,wi能够解决另一个问题,但这次我想不通。下面是代码。

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

# Path for face image database
path = 'dataset'

recognizer = "help(cv2.face.createLBPHFaceRecognizer)"
detector = cv2.CascadeClassifier("/home/pi/FacialRecognitionProject/haarcascade_frontalface_default.xml");

# function to get the images and label data
def getImagesAndLabels(path):

    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]     
    faceSamples=[]
    ids = []

    for imagePath in imagePaths:

        PIL_img = Image.open(imagePath).convert('L') # convert it to grayscale
        img_numpy = np.array(PIL_img,'uint8')

        id = int(os.path.split(imagePath)[-1].split(".")[1])
        faces = detector.detectMultiScale(img_numpy)

        for (x,y,w,h) in faces:
            faceSamples.append(img_numpy[y:y+h,x:x+w])
            ids.append(id)

    return faceSamples,ids

print ("\n [INFO] Training faces. It will take a few seconds. Wait ...")
faces,ids = getImagesAndLabels(path)
recognizer.train(faces, np.array(ids))

# Save the model into trainer/trainer.yml
recognizer.write('/home/pi/FacialRecognitionProject/trainer/trainer.yml') # recognizer.save() worked on Mac, but not on Pi

# Print the numer of faces trained and end program
print("\n [INFO] {0} faces trained. Exiting Program".format(len(np.unique(ids))))

错误说 识别器.train(面孔,np.array(ids)) AttributeError:“str”对象没有属性“train” 你的程序试图调用一个字符串的方法train,但是这个类型没有这样的方法。

【问题讨论】:

  • 你在开始时将它设置为一个字符串...
  • 哪一行?我对此很陌生,所以我真的不太了解
  • 第 9 行 recognizer = "help(cv2.face.createLBPHFaceRecognizer)", the only previous line where recognizer` 被提及。

标签: python opencv


【解决方案1】:

在一行

recognizer = "help(cv2.face.createLBPHFaceRecognizer)"

您正在将识别器设置为字符串。双 qouted 初始化在 python 中被理解为字符串。改用下面的

recognizer = cv2.face.LBPHFaceRecognizer_create()

希望这会有所帮助..

更新:

您应该安装附加软件包以使用面部模块。您可以使用以下命令进行安装。所以cv2.face.LBPHFaceRecognizer_create() 可以正常工作

pip install opencv-contrib-python

注意:如果你使用的是jupyter,必须在pip安装后重启内核

【讨论】:

  • 给出错误 cv2.cv2 module has no attribute face
  • 我正在使用我的树莓派。我已经尝试过 pip3 install opencv-contrib-python,它没有解决我的问题
  • 这是你的opencv版本
  • 3.4.3版本
  • 你能试试用 >>>pip install opencv-python==4.1.0.25 安装 4.1
猜你喜欢
  • 2020-11-18
  • 1970-01-01
  • 2018-10-13
  • 1970-01-01
  • 1970-01-01
  • 2018-09-10
  • 2021-10-04
  • 2019-12-02
  • 2021-09-25
相关资源
最近更新 更多