2017-01-08 28 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