Reputation: 984
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()
Upvotes: 1
Views: 307
Reputation: 984
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)
Upvotes: 1
Reputation: 221
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/
Upvotes: 2