【问题标题】:Formatting filepaths using variables on in os.path使用 os.path 中的变量格式化文件路径
【发布时间】:2017-01-08 15:35:46
【问题描述】:

我编写了一个脚本,它使用 cv2 和其他一些模块将视频文件分割成帧。到目前为止,我很高兴粘贴文件路径并运行代码,但现在我希望用户输入文件路径和名称以响应提示。这应该很容易,但我在让 os.path 为我工作时遇到了很多麻烦。主要问题是我希望每个图像文件(即帧)的名称中都有一个数字,以显示它在序列中的位置。下面的代码是我所拥有的:

filepath = input('Please enter the filepath for the clip: ') 

clip = cv2.VideoCapture(filepath)

#### This code splits the clip into scenes

filepath1 = input('Please enter the filepath for where the frames should be saved: ') 

name = input('Please enter the name of the clip: ') 

ret, frame = clip.read()
count = 0
ret == True
while ret:
    ret, frame = clip.read()
    cv2.imwrite((os.path.join(filepath1,name, '(%d)','.png') % count, frame))
    count += 1

但是,会产生以下错误:

cv2.imwrite((os.path.join(filepath1,name, '(%d)','.png') % count, frame))
    TypeError: Required argument 'img' (pos 2) not found

在 os.path.join 命令的括号中包含 % count, frame 变量会产生不同的错误:

TypeError: not all arguments converted during string formatting

它应该做的是将一些名为name(x)的.png文件写入MYcomputer/mydesktop/myfolder/这样的位置。我不确定这里出了什么问题——感谢任何帮助!

【问题讨论】:

    标签: python filepath os.path cv2


    【解决方案1】:

    你的括号位置以及join的用法是错误的这个

    cv2.imwrite((os.path.join(filepath1,name, '(%d)','.png') % count, frame))
    

    应该更正如下:

    cv2.imwrite(os.path.join(filepath1, name+'(%d).png'%count), frame)
    

    为了进一步改进我建议的代码

    fname = "{name}({count}).png".format(name=name, count=count)
    cv2.imwrite(os.path.join(filepath1, fname), frame)
    

    这里是os.path.join 的简要说明:它将所有参数与您的操作系统的路径分隔符连接起来(“/”在 Unix-Based 上,“\”在 Windows 上)。结果,您的原始代码将产生以下字符串:

    filepath1 = "some_dir"
    name = "some_name"
    count = 10
    print(os.path.join(filepath1, name, '(%d)' % count,'.png'))
    >>> "some_dir/some_name/10/.png"
    

    【讨论】:

    • 感谢您为我解决了这么多问题!但是,我现在遇到了另一个错误:cv2.imwrite((os.path.join(filepath1,name+'(%d).png'%count), frame)) TypeError: Required argument 'img' (pos 2) not found 对此有何想法?
    • 正如我所说,检查您的“(”和“)”位置;) imwrite 需要作为文件路径的第一个参数,然后是图像。你传递一个带有文件路径和图像的元组。所以双-“(”和-“)”太多了。
    • 啊,是的,我看到了。感谢一百万,为修复和教育!现在工作正常
    猜你喜欢
    • 2014-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-04-22
    • 1970-01-01
    • 2015-06-23
    • 1970-01-01
    相关资源
    最近更新 更多