简体   繁体   中英

Saving multiple images with Python

For my cancer research I need to turn cancerscans into black and white images, and save them. I've this code, which turns the first file in the folder into a black and white picture, and copies it 49 times with names like result1, result2 , result3 etc.

wd = os.getcwd()
wd = os.chdir("C:\\Users\\Tije\\Documents\\School\\DeepLearning\\IDC_regular_ps50_idx5\\8863\\test")

for x in range(50):
    for file in os.listdir(wd):
        image_file = Image.open(file)  
        image_file= image_file.convert('1')
        print(image_file)
        image_file.save(f"result{x}.png")

I need the code to blackandwhite'n every picture in the folder and not just the first one of course. I can't seem to understand why it does this.

Any help?

You're looping over the entire directory 50 times and thus result{x} gets overwritten 50 times.

If you want to index for each result, just use enumerate as follows:

for index, file in enumerate(os.listdir(wd)):
    image_file = Image.open(file)  
    image_file= image_file.convert('1')
    print(image_file)
    image_file.save(f"result{index}.png")

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