Search code examples
pythonpython-3.xopencvglob

Issue in reading frames sequence wise from folder in Python


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


Solution

  • 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']