Alex freires marques
Alex freires marques

Reputation: 11

Sorted Function Error in Python3.5 Raspberry

This code works perfectly on Windows with Python 3.7, but on raspberry with Python 3.5 the sorted function does not work.

Line of the code that causes the error:

sorted_images = sorted(image_list, key=os.path.getmtime)

In thePpython documentation I did not find any changes from one version to another. Can someone give me an alternative?

I'm new here, sorry for some mistake. ;-)

Error:

pi@raspberrypi:~/TCC/TimeLapse $ python timelapse.py
File "timelapse.py", line 53
sorted_images = sorted(image_list, key=os.path.getmtime)
        ^

SyntaxError: invalid syntax

My code:

import os
import numpy as np
import cv2
import time
import datetime

from utils import CFEVideoConf, image_resize
import glob

cap = cv2.VideoCapture(0) #0 pra webcam interna , 1 para externa

frames_per_seconds = 20
save_path='saved-media/timelapse.mp4'
config = CFEVideoConf(cap, filepath=save_path, res='480p')
out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims)
timelapse_img_dir = 'images/timelapse/'
seconds_duration = 60
seconds_between_shots = 1

if not os.path.exists(timelapse_img_dir):
   os.mkdir(timelapse_img_dir)

now = datetime.datetime.now()
finish_time = now + datetime.timedelta(seconds=seconds_duration)
i = 0
while datetime.datetime.now() < finish_time:
   '''
   Ensure that the current time is still less
   than the preset finish time
   '''
   ret, frame      = cap.read()
   #filename        = f"{timelapse_img_dir}/{i}.jpg"
   filename        = '{timelapse_img_dir}/{i}.jpg'.format(**locals())
   i               += 1
   cv2.imwrite(filename, frame)
   time.sleep(seconds_between_shots)
   if cv2.waitKey(20) & 0xFF == ord('q'):
       break


def images_to_video(out, image_dir, clear_images=True):
    #image_list = glob.glob(f"{image_dir}/*.jpg")
    image_list = glob.glob('{image_dir}/*.jpg'.format(**locals()))
    #sorted_images = sorted(image_list, key=lambda c: os.path.getmtime(c))
    sorted_images = sorted(image_list, key=os.path.getmtime)
    for file in sorted_images:
       image_frame  = cv2.imread(file)
       out.write(image_frame)
    if clear_images:
        '''
        Remove stored timelapse images
        '''
        for file in image_list:
            os.remove(file)

images_to_video(out, timelapse_img_dir)
# When everything done, release the capture

cap.release()
out.release()
cv2.destroyAllWindows()

Upvotes: 1

Views: 70

Answers (0)

Related Questions