I'm new at image processing, I captured frames from a video and I want to convert them into arrays. These frames must be consecutive. here's the part of my code
folder = "/content/otherGrayscaleImage"
onlyfiles = [f for f in os.listdir(folder) if os.path.isfile(os.path.join(folder, f))]
print("Working with {0} images".format(len(onlyfiles)))
for i in range(len(onlyfiles)):
#do something
print(onlyfiles[i])
here is the output
Working with 328 images
241.png
312.png
27.png
149.png
42.png
296.png
182.png
99.png
64.png
120.png
102.png
208.png
79.png
325.png
......
as you can see, the print of my outputs is random and does not start from my first image which is 1.png.
here is the sorted input using .sorted() function.
1.png
10.png
100.png
101.png
.
.
199.png
2.png
my ultimate goal is to convert 64 successive 2d images array into a 3d array, to achieve that python should read my images consecutively; but it doesn't.
how should I read my images in a file consecutively?
PS: using sorting functions such as sorted() would not help
CodePudding user response:
You need a custom sort key. The manual solution is something like this:
onlyfiles.sort(key=lambda x: int(x[:x.index('.')]))
This is not a robust solution. If you have any files that have anything other than integers before the extension, or are missing an extension, this will raise an error.
Luckily, there is a library called natsort that catches the corner cases of human sorting pretty well. After pip install natsort, you can do
from natsort import natsorted
onlyfiles = natsorted(onlyfiles)
Mandatory disclaimer: I am not affiliated with natsort except as a satisfied user.
