2017-01-08 33 views
0

我已经编写了一个脚本,它使用cv2和其他一些模块将视频文件分割为多个帧。到目前为止,我很高兴粘贴文件路径并运行代码,但现在我希望用户输入文件路径和名称以响应提示。这应该很简单,但是我在为我做os.path工作时遇到了很多麻烦。主要的问题是,我想要每个图像文件(即帧)的名称中都有一个数字,以显示它在序列中的位置。下面的代码是什么我:使用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)MYcomputer/mydesktop/myfolder/位置.png文件的。我不确定这里出了什么问题 - 任何帮助表示感谢!

回答

2

您括号放置以及对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:它conca使用操作系统的路径分隔符(基于Unix的“/”和Windows上的“\”)提供所有参数。因此,您的原始代码将导致以下字符串:

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

感谢您为我清除这么多!但是,我现在得到了一个不同的错误: 'cv2.imwrite((os.path.join(filepath1,name +'(%d).png'%count),frame)) TypeError:必需参数'img '(pos 2)not found' 对此有何看法? – Lodore66

+0

正如我所说,检查你的“(”和“)”的位置;)imwrite需要作为第一个参数的文件路径,然后是图像。你传递一个包含文件路径和图像的元组。所以双“(”和 - “)”太多了。 – BloodyD

+0

啊,是的,我看到<咳嗽尴尬>。感谢一百万,为修复和教育!现在工作正常 – Lodore66