pythonpython-3.ximagepython-2.7storing-data

Read images from from the folder in the same order in which they appears and store in the same order


I have 10k images in one folder. In that, I have images in the order, 0.jpg, 1.jpg, 2.jpg to 10000.jpg. I have to read the images in the same order, process them, and store them in the same order. I have used the below code. But I can't get the expected output. Randomly it is reading files from the folder so, the output folder is randomly ordered. What should I change?

path = "location of the image folder"
i=0
for fname in os.listdir(path):    
    img = imageio.imread(path + '/' + fname)
    img_aug = seq.augment_image(img) # perform imgaug library data augmentation
    imageio.imwrite(os.path.join(path, path+ '/output/'+ "%1d.jpg" % (i,)), img_aug)
    print(i)
    i += 1


Solution

  • The updated code is:

    path = "location of the image folder"
    i=0
    list_dir=[int(file.split(".")[0]) for file in os.listdir(path)]
    list_dir.sort()
    for fname in list_dir:    
        img = imageio.imread(path + '/' + str(fname)+".jpg")
        img_aug = seq.augment_image(img) # perform imgaug library data augmentation
        imageio.imwrite(os.path.join(path, path+ '/output/'+ "%1d.jpg" % (i,)), img_aug)
        print(i)
        i += 1
    

    I'm assuming all the images in the directory are .jpg images. I have just extracted the file no for all files in the directory and sorted them as integers. Hope this helps