简体   繁体   中英

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

应该用"/dataset/{Name}/"替换"/dataset/Name/" ,如果你想使用用户输入的值,或者使用.format()来填充,如果你的 python 不支持 f' '-字符串。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM