提问者:小点点

在python中为图像自动创建文件夹


我想知道如何创建文件夹和存储图像自动基于标签。 下面的示例代码澄清了我的问题。 我正在学习本教程https://www.pyimagesearch.com/2018/07/09/face-clustering-with-python/

from imutils import paths
import face_recognition
import argparse
import pickle
import cv2
import os
import shutil

to_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"])   # <----- This image array is what i want 
                                                  #         to store in each folder named by 
                                                  #         labelID

标签输出:

下面的标签是标签的不同图像。 比如说-1是大象的形象,0是狮子的形象,1是老虎的形象。 所以,我的问题是如何创建文件夹,即用这些labeID和如何存储相应的图像在其中?

   -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)

它删除文件夹并再次创建目录,以避免“文件夹已存在”错误。 现在我想在这些文件夹中存储这些标签的图像。

我希望我的问题是清楚的。 对于给您带来的不便,敬请原谅,任何与我的问题有关的答复将被回复。谢谢:)


共1个答案

匿名用户

我想你要找的答案是

cv2.imwrite(os.path.join(mainPath,filename),image)

只是给你一个信息,用于创建路径。 有一个标志exist_okos.makeDirs()(至少对于Python3)。 它默认为false,但是如果您将它设置为true,它将创建该目录,除非它已经存在,在这种情况下它将什么也不做。