1

Am trying to put a timelapse on my OpenCV code but it seems i am doing something that is not right and i don't know why i have the error. The erorr i got is for this line: filename = f"{timelapse_img_dir}/{i}.jpg" What should i do in order not to have an error?

This is the error i have from my IDE:

File "/Users/Dropbox/OpenCV/src/timelapse.py", line 34
    filename        = f"{timelapse}/{i}.jpg"
                                           ^
SyntaxError: invalid syntax
[Finished in 0.1s with exit code 1]
[shell_cmd: python -u "/Users/Dropbox/OpenCV/src/timelapse.py"]
[dir: /Users/Dropbox/OpenCV/src]
[path: /usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/opt/X11/bin]

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)


frames_per_seconds = 20
save_path='saved-media/timelapse.mp4'
config = CFEVideoConf(cap, filepath=save_path, res='720p')
out = cv2.VideoWriter(save_path, config.video_type, frames_per_seconds, config.dims)
timelapse_img_dir = '/Users/Dropbox/OpenCV/src/images/timelapse/'
seconds_duration = 20
seconds_between_shots = .25

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        = f"{timelapse_img_dir}/{i}.jpg"
    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")
    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()

2 Answers 2

2

I believe the format you are using is only supported on python 3.6 "Literal String Interpolation":

https://www.python.org/dev/peps/pep-0498/#raw-f-strings

filename  = f"{timelapse_img_dir}/{i}.jpg"

here are 2 other options depends on what python you are using:

python 2.7:

filename = '%(timelapse_img_dir)s %(i)s' % locals()

python 3+

filename = '{timelapse_img_dir} {i}'.format(**locals())

Based on: https://pyformat.info/

Sign up to request clarification or add additional context in comments.

5 Comments

Thank you Elad! And this line of code, how is transforming? image_list = glob.glob(f"{image_dir}/*.jpg")
what python version are you using?
3 Elad! thanks! and in my code i want to have different images saved as jpg in a timelapse dir. Does this part of code save as jpg, 's' % locals()'
@cohen, "%(..)s" % locals is for python 2.7 and is just transforming a local defined variable to a string
so my timelapse_img_dir = "/Users/Dropbox/OpenCV/src/images/timelapse/". i just need to format in this folder jpg images starting from 1 to infinite. My code is for dir/1.jpg. is this right for filename = '{timelapse_img_dir} {i}'.format(**locals())? i dont find the jpg extension here.
1

I dont know why i was not able to use the f function. I had to do another concatenation to work.

 filename        = timelapse_img_dir +str(i) +file_format

and for the rest i used the wild card

filetomake = image_dir + "/*.jpg"

    image_list = glob.glob(filetomake)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.