1

I have the following code reading frames from the folder. My video frames are stored in a format frame0.jpg, frame1.jpg. I need to read frames sequence wise I am running below code but the output I am retrieving is not what I want.

filenames = [img for img in glob.glob("video-frames/*.jpg")]
filenames.sort()
images = []
for img in filenames:
 n= cv2.imread(img)
 images.append(n)
 print(img)

output received:

video-frames\frame0.jpg
video-frames\frame1.jpg
video-frames\frame10.jpg
video-frames\frame100.jpg
video-frames\frame101.jpg

I want output to read frames in sequence like below

video-frames\frame0.jpg
video-frames\frame1.jpg
video-frames\frame2.jpg

Thanks

gohar shah
  • 165
  • 1
  • 10
  • 1
    You can use the time that they are created. `filenames = sorted(filenames, key=os.path.getctime)` or `filenames.sort(key=os.path.getctime)`, if they have been generated in the right order. – Thymen Dec 10 '20 at 16:21
  • @Thymen, thanks for your wonderful suggestion. Would you please post your answer so that others will benefit for better visibility? – gohar shah Dec 10 '20 at 16:27
  • 1
    Files are typically read from disk in alphabetic order. That means xxx10.jpg is read before xxx1.jpg. So you should add leading zeros to your file names. Then reading them alphabetically will load xxx01, xxx02, ... xxx10... up to xxx99. Use more leading zeros if you have more that 99 – fmw42 Dec 10 '20 at 17:59

3 Answers3

1

Try this

files_list = os.listdir('/content/test1') # use your folderpath here 
files_list.sort(key=lambda f: int(re.sub('\D', '', f))) 

for example,

files_list = ['frame0.jpg','frame1.jpg','frame10.jpg','frame100.jpg',
              'frame101.jpg','frame2.jpg','frame20.jpg','frame3.jpg']
files_list.sort(key=lambda name: int(re.sub('\D', '', name)))

Output from above

['frame0.jpg',
 'frame1.jpg',
 'frame2.jpg',
 'frame3.jpg',
 'frame10.jpg',
 'frame20.jpg',
 'frame100.jpg',
 'frame101.jpg']
Sonia Samipillai
  • 590
  • 5
  • 15
1

Other way. Try:

filenames = sorted(filenames, key=lambda x: int("".join([i for i in x if i.isdigit()])))

Here is one example.

0

When the files are created in the original order, you can use their creation time to sort on.

import os

filenames = [img for img in glob.glob("video-frames/*.jpg")]
filenames.sort(key=os.path.getctime)

or

import os

filenames = [img for img in glob.glob("video-frames/*.jpg")]
filenames = sorted(filenames, key=os.path.getctime)
Thymen
  • 2,089
  • 1
  • 9
  • 13