Home > Software design >  Cannot iterate over a file?
Cannot iterate over a file?

Time:02-16

I have this function which i want to apply to a file of images and save each of them in a separate file:

def MyFn(img, saveFile=None):         
.
.
.
    if saveFile is not None:
        Image.fromarray(Inorm).save(saveFile '.png')
        Image.fromarray(H).save(saveFile '_H.png')
        Image.fromarray(E).save(saveFile '_E.png')
    return Inorm, H, E

Testing on ONE image, it works succesfully:

img = np.array(Image.open('/Desktop/Dataset/Images/img1.png'))
output = 'Desktop/Dataset/Output'
MyFn(img = img,saveFile = output) #Apply this function which saves in output file

But, how can i apply this code to ALL images in the folder? The code runs but just saves one image.

import glob
images = glob.glob('/Desktop/Dataset/Images/*')

for img in images:
    img = np.array(Image.open(img))
    output = 'Desktop/Dataset/Output'
    MyFn(img = img,saveFile = output)

CodePudding user response:

try to use the library os directly with

import os
entries = os.listdir('image/') 

this will return a list of all the file into your folder

CodePudding user response:

This is because you are not setting the sv value in your loop. You should set it to a different value at each iteration in order for it to write to different files.

CodePudding user response:

You did not define the sv value in your 2nd code snippet.

As the image will be overwrite, try this code:

import glob
images = glob.glob('/Desktop/Dataset/Images/*')

i = 0
for img in images:
    i  = 1 #iteration to avoid overwrite
    img = np.array(Image.open(img))
    output = 'Desktop/Dataset/Output'
    MyFn(img = img   str(i),saveFile = output)
  • Related