我正在尝试运行一个面部识别训练器,该训练器查看面部jpg图像的文件夹
import os # importing the OS for path
import cv2 # importing the OpenCV library
import numpy as np # importing Numpy library
from PIL import Image # importing Image library
EigenFace = cv2.face.EigenFaceRecognizer_create(15) # creating EIGEN FACE RECOGNISER
FisherFace = cv2.face.FisherFaceRecognizer_create(2) # Create FISHER FACE RECOGNISER
LBPHFace = cv2.face.LBPHFaceRecognizer_create(1, 1, 7,7) # Create LBPH FACE RECOGNISER
path = 'dataSet' # path to the photos
def getImageWithID (path):
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
FaceList = []
IDs = []
for imagePath in imagePaths:
faceImage = Image.open(imagePath).convert('L') # Open image and convert to gray
faceImage = faceImage.resize((110,110)) # resize the image so the EIGEN recogniser can be trained
faceNP = np.array(faceImage, 'uint8') # convert the image to Numpy array
ID = int(os.path.split(imagePath)[-1].split('.')[1]) # Retrieve the ID of the array
FaceList.append(faceNP) # Append the Numpy Array to the list
IDs.append(ID) # Append the ID to the IDs list
cv2.imshow('Training Set', faceNP) # Show the images in the list
cv2.waitKey(1)
return np.array(IDs), FaceList # The IDs are converted in to a Numpy array
IDs, FaceList = getImageWithID(path)
依次返回错误Traceback (most recent call last):
File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 28, in <module>
IDs, FaceList = getImageWithID(path)
File "/Users/jef/PycharmProjects/testProject/Python/Trainer_All.py", line 19, in getImageWithID
faceImage = Image.open(imagePath).convert('L') # Open image and convert to gray
File "/Users/jef/venv1/lib/python3.6/site-packages/PIL/Image.py", line 2452, in open
% (filename if filename else fp))
OSError: cannot identify image file 'dataSet/.DS_Store'
文件夹dataSet存在,并且我正在Mac上运行代码,以及Pillow,numpy和cv2的最新版本,我已经在OSError上进行了谷歌搜索,但并没有太多帮助解决此特定问题的方法。有任何想法吗?
最佳答案
os.listdir()
将为您提供目录中的每个文件,包括.DS_Store
之类的隐藏文件。在macOS中,.DS_Store
是一个隐藏文件(以.
开头的任何文件都会从Finder中隐藏),每当您使用Finder查看目录时都将其插入目录中,以加快文件图标的加载速度以及将缩略图大小等的首选项保存在该文件夹中。您可以阅读有关文件on Wikipedia的更多信息。
如果导航到目录并使用ls -a
在终端中列出文件,则可以看到该文件。
无论如何,您只需要尝试将其作为图像文件读取即可。有无数种方法可以避免这种情况,以下是几种:
for imagePath in imagePaths:
if imagePath == directory + '.DS_Store':
continue
# rest of your program
要么
imagePaths = [os.path.join(path, f) for f in os.listdir(path)]
if directory + '.DS_Store' in imagePaths:
imagePaths.remove(directory + '.DS_Store')
或仅使用
glob
仅捕获具有所需扩展名的文件:import glob
imagePaths = [f for f in glob.glob(directory+'*.jpg')] # or .png, .tif, etc
此处
*
是通配符,表示“任何字符序列”,因此它将抓取directory/1.jpg
和directory/asdf.jpg
以及所有其他以directory/
开头并以.jpg
结尾的可能性。或者只是将其从终端中的目录中删除
rm .DS_Store
但这只是一个临时解决方案,因为macOS会在您下次在Finder中查看文件夹时再次插入文件。
关于opencv - OSError:无法识别图像文件 'dataSet/.DS_Store',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47645115/