gpt4 book ai didi

Python-OpenCV --F 函数错误--找不到正确的目录

转载 作者:太空宇宙 更新时间:2023-11-03 22:08:31 32 4
gpt4 key购买 nike

我正在尝试对我的 OpenCV 代码进行延时处理,但似乎我正在做一些不正确的事情,而且我不知道为什么会出现错误。我得到的错误是这一行: filename = f"{timelapse_img_dir}/{i}.jpg" 我应该怎么做才能不出错?

这是我在 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]

我的代码:

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()

最佳答案

我相信您使用的格式仅在 python 3.6“Literal String Interpolation”上受支持:

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

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

这里还有 2 个其他选项,具体取决于您使用的是什么 python:

python 2.7:

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

python 3+

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

基于: https://pyformat.info/

关于Python-OpenCV --F 函数错误--找不到正确的目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50551410/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com