此代码在带有 Python 3.7 的 Windows 上完美运行,但在带有 Python 3.5 的 raspberry 上,该sorted
功能不起作用。
导致错误的代码行:
sorted_images = sorted(image_list, key=os.path.getmtime)
在 Ppython 文档中,我没有发现从一个版本到另一个版本的任何更改。有人可以给我一个替代方案吗?
我是新来的,有些错误请见谅。;-)
错误:
pi@raspberrypi:~/TCC/TimeLapse $ python timelapse.py
File "timelapse.py", line 53
sorted_images = sorted(image_list, key=os.path.getmtime)
^
SyntaxError: invalid syntax
我的代码:
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()