【问题标题】:Unable to convert os.path.split(imagePath)[-1].split('.')[1] to integer无法将 os.path.split(imagePath)[-1].split('.')[1] 转换为整数
【发布时间】:2019-10-25 11:24:09
【问题描述】:

我正在尝试使用 OpenCV 创建一个人脸识别软件,但是我在库中找到的代码是用 Python 2 编写的。是否有 Python 3 版本?

这是链接:https://github.com/thecodacus/Face-Recognition

我已经有一个用于数据集和培训师的文件夹。

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

# Path for face image database
path = 'dataset'

recognizer = cv2.face.LBPHFaceRecognizer_create()
detector = cv2.CascadeClassifier("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('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))))

错误:

Traceback (most recent call last):
  File "/Users/user/Desktop/FacialRecognition/02_face_training.py", line 46, in <module>
faces,ids = getImagesAndLabels(path)
  File "/Users/user/Desktop/FacialRecognition/02_face_training.py", line 36, in getImagesAndLabels
id = int(os.path.split(imagePath)[-1].split('.')[1])
ValueError: invalid literal for int() with base 10: 'User'

【问题讨论】:

  • 您发布的代码中的imagePath 是什么?
  • 请向我们展示您的代码。
  • 我们无法重现您的错误。请提供minimal reproducible example
  • 截至 2022 年,我从错误中吸取了教训,因此请停止查看此问题,因为它不可复制。我很抱歉在这里浪费时间的人,我现在知道了。

标签: python python-3.x numpy opencv operating-system


【解决方案1】:

在该存储库中有一个dataSet 目录,其文件名为:

In [665]: name='Face-Recognition/dataSet/face-1.1.jpg'               

应用到该名称,您的代码示例可以:

In [668]: os.path.split(name)                                                                          
Out[668]: ('Face-Recognition/dataSet', 'face-1.1.jpg')
In [669]: os.path.split(name)[-1]                                                                      
Out[669]: 'face-1.1.jpg'
In [670]: os.path.split(name)[-1].split('.')                                                           
Out[670]: ['face-1', '1', 'jpg']
In [671]: os.path.split(name)[-1].split('.')[1]                                                        
Out[671]: '1'
In [672]: int(os.path.split(name)[-1].split('.')[1])                                                   
Out[672]: 1

显然您的文件具有不同的名称格式,在此代码需要数字的位置中包含“用户”。

您需要更正文件名,或更改此解析代码。

【讨论】:

    【解决方案2】:

    您在数据集中获得的图像名称为User.*somename*,因此请从所有图像名称中删除用户。

    【讨论】:

      【解决方案3】:

      这为我完成了工作:

      Id=int(os.path.split(imagePath)[-1].split(".")[0]) 
      

      【讨论】:

        【解决方案4】:

        尝试改变格式图片是'face.1.1.jpg' 然后你可以用这段代码分割点

        faceID = int(os.path.split(imagePath)[-1].split(".")[2])
        

        【讨论】: