简体   繁体   English

使用python将多个图像保存到一个目录

[英]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_' cv2.imwrite(p, orig) cv2.error: OpenCV(4.0.0) /home/pi/opencv/modules/imgcodecs/src/loadsave.cpp:661: >error: (-2:Unspecified error) 找不到指定扩展名的编写器 > 在函数“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.尝试了 john 从 p 中删除 os.path.sep.join() 的建议,但它正在保存到一个名为 Name 的不存在的目录中。 Name is supposed to be the variable for the users input. Name 应该是用户输入的变量。 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' '-字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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