为 python 中的图像自动创建文件夹
Creating folder automatically for images in 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
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 的图像存储在这些文件夹中。
我希望我的问题很清楚。
任何不便敬请谅解,
任何与我的问题相关的回复都将不胜感激谢谢:)
我认为您正在寻找的答案是
cv2.imwrite(os.path.join(mainPath,filename),image)
仅供您参考,用于创建路径。有(至少 python 3)一个标志 exist_ok
到 os.makedirs()
。它默认为 False
,但如果将其设置为 True
,它将创建目录,除非它已经存在,在这种情况下它什么都不做。
我想知道如何根据标签自动创建文件夹和存储图片。下面的示例代码使我的问题很清楚。我正在学习本教程 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 的图像存储在这些文件夹中。
我希望我的问题很清楚。 任何不便敬请谅解, 任何与我的问题相关的回复都将不胜感激谢谢:)
我认为您正在寻找的答案是
cv2.imwrite(os.path.join(mainPath,filename),image)
仅供您参考,用于创建路径。有(至少 python 3)一个标志 exist_ok
到 os.makedirs()
。它默认为 False
,但如果将其设置为 True
,它将创建目录,除非它已经存在,在这种情况下它什么都不做。