Tobitor
Tobitor

Reputation: 1508

Sorting list by filename

I read in the filenames of some images which are stored like this:

(path/to/images/1_1.png)
(path/to/images/1_2.png) ...
(path/to/images/10_1.png) ...
(path/to/images/1000_1.png)

When reading the filenames to a list with this code

import cv2
import glob

folders = glob.glob(r'C:\Users\tobis\OneDrive\Desktop\Masterarbeit\data\2017-IWT4S-CarsReId_LP-dataset\*')
imagenames_list = []
for folder in folders:
    for f in glob.glob(folder+'/*.png'):
        imagenames_list.append(f)

The first image in my list is the one that's filename is (path/to/images/1000_1.png) instead of (path/to/images/1_1.png). It is important to get the files in the right order because I need to match the images with another list. Is there a way to sort the list in the way I need it?

Upvotes: 1

Views: 97

Answers (2)

Mo Huss
Mo Huss

Reputation: 464

Great question!

See this working example:

sorted(['path/to/images/1000_1.png',
        'path/to/images/1_1.png',
        'path/to/images/1_2.png',
        'path/to/images/10_1.png'
       ], 
        key=lambda x: int(x.split('/')[-1][:-4].replace('_','')))

Upvotes: 1

Sri
Sri

Reputation: 2318

What you are referring to is known as natural sorting, as opposed to the default lexicographical sorting.

Here is an example that I think will suit your needs.

import re

def natural_sort(l):
    convert = lambda text: int(text) if text.isdigit() else text.lower()
    alphanum_key = lambda key: [ convert(c) for c in re.split('([0-9]+)', key) ]
    return sorted(l, key = alphanum_key)

fl = ['path/to/images/1000_1.png', 'path/to/images/1_1.png']

print(natural_sort(fl))

reference : Is there a built in function for string natural sort?

Upvotes: 3

Related Questions