我想知道如何根据标签自动创建文件夹并存储图像。以下示例代码可以清楚地解释我的问题。我在按照这个教程学习 https://www.pyimagesearch.com/2018/07/09/face-clustering-with-python/
from imutils import pathsimport face_recognitionimport argparseimport pickleimport cv2import osimport shutilto_load = "encodings.pickle"data = pickle.loads(open(to_load, "rb").read())data = np.array(data)encodings = [d["encoding"] for d in data]clt = DBSCAN(metric="euclidean", n_jobs=-1)clt.fit(encodings)labelIDs = np.unique(clt.labels_)numUniqueFaces = len(np.where(labelIDs > -1)[0])for labelID in labelIDs: mainPath = format(labelID) idxs = np.where(clt.labels_ == labelID)[0] for i in idxs: image = cv2.imread(data[i]["imagepath"]) # <----- 这个图像数组是我想要存储在每个以labelID命名的文件夹中的
labelID输出:
以下是不同标签的图像。假设-1是大象的图像,0是狮子的图像,1是老虎的图像。所以,我的疑问是如何创建以这些labelID命名的文件夹,以及如何将相应的图像存储到这些文件夹中?
-1 -1 -1 0 0 0 0 0 1 1 1
我知道如何使用os.mkdir创建文件夹并使用cv2.imwrite存储图像,但我想根据labelID为特定图像创建特定的文件夹。
以下是创建labelID文件夹的示例:
path = format(labelID)if os.path.exists(mainPath): shutil.rmtree(mainPath)os.mkdir(mainPath)
它会删除文件夹并重新创建目录,以避免“文件夹已存在”的错误。现在我想将这些labelID的图像存储到这些文件夹中。
希望我的问题已经清楚表达。抱歉造成任何不便,任何与我的问题相关的回应都将不胜感激,谢谢您 🙂
回答:
我想您寻找的答案是
cv2.imwrite(os.path.join(mainPath,filename),image)
顺便提一下,关于路径的创建。在Python 3中,os.makedirs()
有一个标志exist_ok
。它的默认值是False
,但如果你将其设置为True
,它将创建目录,除非它已经存在,在这种情况下,它将什么也不做。