【问题标题】:Creating folder automatically for images in python自动为python中的图像创建文件夹
【发布时间】:2023-03-30 00:09:01
【问题描述】:

我想知道如何根据标签自动创建文件夹和存储图像。以下示例代码使我的问题清楚。我正在关注本教程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

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)

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

我希望我的问题很清楚。 任何不便敬请谅解, 任何与我的问题相关的回复都将不胜感激谢谢:)

【问题讨论】:

    标签: python image numpy machine-learning subdirectory


    【解决方案1】:

    我认为您正在寻找的答案是

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

    只是为您提供的信息,用于创建路径。 (至少对于 python 3)有一个标志 exist_ok 到 os.makedirs()。默认为False,但如果你设置为True,它会创建目录,除非它已经存在,在这种情况下它什么也不做。

    【讨论】:

    • 感谢您的建议。让我检查一下。
    • 谢谢它的工作,但只保存单个图像到每个文件夹:(我什至使用此代码保存所有图像:d=0, d+=1, filename = "file_%d.jpg" % d
    • 现在可以了,我添加了你提到的 True 方法!谢谢!
    • 请告诉我创建这些文件夹后如何重命名?请!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-13
    • 1970-01-01
    • 1970-01-01
    • 2014-12-23
    • 2018-03-12
    • 1970-01-01
    • 2011-03-10
    相关资源
    最近更新 更多