Sin Clair
Sin Clair

Reputation: 31

Saving multiple images to a directory using python

Im trying to save multiple images to a directory which is created by the user's input. Below is the code of how to create the directory:

while True:
        Name = input("Enter your name: ")
        try:
            os.mkdir(Name)
            break
        except FileExistsError:
            while True:
                remove =  str(input("Do you want to rewrite the directory?"))
                if remove=="yes" or remove=="Yes" or remove=="y" or remove=="Y":
                    shutil.rmtree(Name)
                    os.mkdir(Name)
                    break
                if remove=="no" or remove=="No" or remove=="n" or remove=="N":
                    pass
                else:
                    continue
            break

i know i did something wrong with the below code but i dont what is it since im only a beginner

if key == ord("k"):
        p = ("/dataset/Name/" + "{}.png".format(str(total).zfill(5)))
        cv2.imwrite(p, orig)
        total += 1


    elif key == ord("q"):
        break

it is giving off this error

cv2.imwrite(p, orig) cv2.error: OpenCV(4.0.0) /home/pi/opencv/modules/imgcodecs/src/loadsave.cpp:661: >error: (-2:Unspecified error) could not find a writer for the specified extension >in function 'imwrite_'

tried john's suggestion of removing os.path.sep.join() from the p but it is saving to a non existent directory called Name. Name is supposed to be the variable for the users input. The images that were supposed to be saved where also nowhere to be found.

I dont know what happened but it is not working again. Below was the edited code

if key == ord("k"):
    p = (f"/dataset/{Name}/" + '.' + str(total) + ".png")
    cv2.imwrite(p, orig)
    total += 1

Upvotes: 1

Views: 926

Answers (1)

lenik
lenik

Reputation: 23556

should have replaced "/dataset/Name/" with "/dataset/{Name}/", if you want to use the value of the user input, or use .format() to fill that if your python does not support f''-strings.

Upvotes: 1

Related Questions