I want to know how to create folders and store images automatically based on labels. following example code makes my question clear. i was following this tutorial 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 output:
below labels are the different images of labels. say like -1 is image of elephant, 0 is image of lion, 1 is image of tiger. so, my question is how to create folders namely with these labeID and how to store corresponding images in it ?
-1
-1
-1
0
0
0
0
0
1
1
1
i know to create folders using os.mkdir and cv2.imwrite, but want to create specific folders from labelID for specific images.
following is the example to create folders of labelID:
path = format(labelID)
if os.path.exists(mainPath):
shutil.rmtree(mainPath)
os.mkdir(mainPath)
it deletes folders and again make directory to avoid "folder already exists" error. now i want to store images of those labelID in these folders.
I hope my questions are clear. sorry for any inconvenience, any response related to my question will be apreciated Thank you :)
I think the answer you are looking for is
cv2.imwrite(os.path.join(mainPath,filename),image)
Just an info for you, for creation of the path. There is (for python 3 at least) a flag exist_ok
to os.makedirs()
. It defaults to False
, but if you set it to True
, it will create the directory unless it already exists, in which case it will do nothing.