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

我想知道如何根据标签自动创建文件夹并存储图像。以下示例代码可以清楚地解释我的问题。我在按照这个教程学习 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,它将创建目录,除非它已经存在,在这种情况下,它将什么也不做。

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注